rollup.js 873 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954
  1. /*
  2. @license
  3. Rollup.js v2.79.1
  4. Thu, 22 Sep 2022 04:55:29 GMT - commit 69ff4181e701a0fe0026d0ba147f31bc86beffa8
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import require$$0, { resolve, basename, extname, dirname, relative as relative$1, win32, posix, isAbsolute as isAbsolute$1 } from 'path';
  9. import process$1 from 'process';
  10. import { performance } from 'perf_hooks';
  11. import { createHash as createHash$1 } from 'crypto';
  12. import { promises } from 'fs';
  13. import { EventEmitter } from 'events';
  14. var version$1 = "2.79.1";
  15. var charToInteger = {};
  16. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17. for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
  18. charToInteger[chars$1.charCodeAt(i$1)] = i$1;
  19. }
  20. function decode(mappings) {
  21. var decoded = [];
  22. var line = [];
  23. var segment = [
  24. 0,
  25. 0,
  26. 0,
  27. 0,
  28. 0,
  29. ];
  30. var j = 0;
  31. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  32. var c = mappings.charCodeAt(i);
  33. if (c === 44) { // ","
  34. segmentify(line, segment, j);
  35. j = 0;
  36. }
  37. else if (c === 59) { // ";"
  38. segmentify(line, segment, j);
  39. j = 0;
  40. decoded.push(line);
  41. line = [];
  42. segment[0] = 0;
  43. }
  44. else {
  45. var integer = charToInteger[c];
  46. if (integer === undefined) {
  47. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  48. }
  49. var hasContinuationBit = integer & 32;
  50. integer &= 31;
  51. value += integer << shift;
  52. if (hasContinuationBit) {
  53. shift += 5;
  54. }
  55. else {
  56. var shouldNegate = value & 1;
  57. value >>>= 1;
  58. if (shouldNegate) {
  59. value = value === 0 ? -0x80000000 : -value;
  60. }
  61. segment[j] += value;
  62. j++;
  63. value = shift = 0; // reset
  64. }
  65. }
  66. }
  67. segmentify(line, segment, j);
  68. decoded.push(line);
  69. return decoded;
  70. }
  71. function segmentify(line, segment, j) {
  72. // This looks ugly, but we're creating specialized arrays with a specific
  73. // length. This is much faster than creating a new array (which v8 expands to
  74. // a capacity of 17 after pushing the first item), or slicing out a subarray
  75. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  76. // length 5 (since not everything will have an associated name), followed by
  77. // length 1 (it's probably rare for a source substring to not have an
  78. // associated segment data).
  79. if (j === 4)
  80. line.push([segment[0], segment[1], segment[2], segment[3]]);
  81. else if (j === 5)
  82. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  83. else if (j === 1)
  84. line.push([segment[0]]);
  85. }
  86. function encode(decoded) {
  87. var sourceFileIndex = 0; // second field
  88. var sourceCodeLine = 0; // third field
  89. var sourceCodeColumn = 0; // fourth field
  90. var nameIndex = 0; // fifth field
  91. var mappings = '';
  92. for (var i = 0; i < decoded.length; i++) {
  93. var line = decoded[i];
  94. if (i > 0)
  95. mappings += ';';
  96. if (line.length === 0)
  97. continue;
  98. var generatedCodeColumn = 0; // first field
  99. var lineMappings = [];
  100. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  101. var segment = line_1[_i];
  102. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  103. generatedCodeColumn = segment[0];
  104. if (segment.length > 1) {
  105. segmentMappings +=
  106. encodeInteger(segment[1] - sourceFileIndex) +
  107. encodeInteger(segment[2] - sourceCodeLine) +
  108. encodeInteger(segment[3] - sourceCodeColumn);
  109. sourceFileIndex = segment[1];
  110. sourceCodeLine = segment[2];
  111. sourceCodeColumn = segment[3];
  112. }
  113. if (segment.length === 5) {
  114. segmentMappings += encodeInteger(segment[4] - nameIndex);
  115. nameIndex = segment[4];
  116. }
  117. lineMappings.push(segmentMappings);
  118. }
  119. mappings += lineMappings.join(',');
  120. }
  121. return mappings;
  122. }
  123. function encodeInteger(num) {
  124. var result = '';
  125. num = num < 0 ? (-num << 1) | 1 : num << 1;
  126. do {
  127. var clamped = num & 31;
  128. num >>>= 5;
  129. if (num > 0) {
  130. clamped |= 32;
  131. }
  132. result += chars$1[clamped];
  133. } while (num > 0);
  134. return result;
  135. }
  136. class BitSet {
  137. constructor(arg) {
  138. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  139. }
  140. add(n) {
  141. this.bits[n >> 5] |= 1 << (n & 31);
  142. }
  143. has(n) {
  144. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  145. }
  146. }
  147. class Chunk$1 {
  148. constructor(start, end, content) {
  149. this.start = start;
  150. this.end = end;
  151. this.original = content;
  152. this.intro = '';
  153. this.outro = '';
  154. this.content = content;
  155. this.storeName = false;
  156. this.edited = false;
  157. // we make these non-enumerable, for sanity while debugging
  158. Object.defineProperties(this, {
  159. previous: { writable: true, value: null },
  160. next: { writable: true, value: null },
  161. });
  162. }
  163. appendLeft(content) {
  164. this.outro += content;
  165. }
  166. appendRight(content) {
  167. this.intro = this.intro + content;
  168. }
  169. clone() {
  170. const chunk = new Chunk$1(this.start, this.end, this.original);
  171. chunk.intro = this.intro;
  172. chunk.outro = this.outro;
  173. chunk.content = this.content;
  174. chunk.storeName = this.storeName;
  175. chunk.edited = this.edited;
  176. return chunk;
  177. }
  178. contains(index) {
  179. return this.start < index && index < this.end;
  180. }
  181. eachNext(fn) {
  182. let chunk = this;
  183. while (chunk) {
  184. fn(chunk);
  185. chunk = chunk.next;
  186. }
  187. }
  188. eachPrevious(fn) {
  189. let chunk = this;
  190. while (chunk) {
  191. fn(chunk);
  192. chunk = chunk.previous;
  193. }
  194. }
  195. edit(content, storeName, contentOnly) {
  196. this.content = content;
  197. if (!contentOnly) {
  198. this.intro = '';
  199. this.outro = '';
  200. }
  201. this.storeName = storeName;
  202. this.edited = true;
  203. return this;
  204. }
  205. prependLeft(content) {
  206. this.outro = content + this.outro;
  207. }
  208. prependRight(content) {
  209. this.intro = content + this.intro;
  210. }
  211. split(index) {
  212. const sliceIndex = index - this.start;
  213. const originalBefore = this.original.slice(0, sliceIndex);
  214. const originalAfter = this.original.slice(sliceIndex);
  215. this.original = originalBefore;
  216. const newChunk = new Chunk$1(index, this.end, originalAfter);
  217. newChunk.outro = this.outro;
  218. this.outro = '';
  219. this.end = index;
  220. if (this.edited) {
  221. // TODO is this block necessary?...
  222. newChunk.edit('', false);
  223. this.content = '';
  224. } else {
  225. this.content = originalBefore;
  226. }
  227. newChunk.next = this.next;
  228. if (newChunk.next) newChunk.next.previous = newChunk;
  229. newChunk.previous = this;
  230. this.next = newChunk;
  231. return newChunk;
  232. }
  233. toString() {
  234. return this.intro + this.content + this.outro;
  235. }
  236. trimEnd(rx) {
  237. this.outro = this.outro.replace(rx, '');
  238. if (this.outro.length) return true;
  239. const trimmed = this.content.replace(rx, '');
  240. if (trimmed.length) {
  241. if (trimmed !== this.content) {
  242. this.split(this.start + trimmed.length).edit('', undefined, true);
  243. }
  244. return true;
  245. } else {
  246. this.edit('', undefined, true);
  247. this.intro = this.intro.replace(rx, '');
  248. if (this.intro.length) return true;
  249. }
  250. }
  251. trimStart(rx) {
  252. this.intro = this.intro.replace(rx, '');
  253. if (this.intro.length) return true;
  254. const trimmed = this.content.replace(rx, '');
  255. if (trimmed.length) {
  256. if (trimmed !== this.content) {
  257. this.split(this.end - trimmed.length);
  258. this.edit('', undefined, true);
  259. }
  260. return true;
  261. } else {
  262. this.edit('', undefined, true);
  263. this.outro = this.outro.replace(rx, '');
  264. if (this.outro.length) return true;
  265. }
  266. }
  267. }
  268. let btoa = () => {
  269. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  270. };
  271. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  272. btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
  273. } else if (typeof Buffer === 'function') {
  274. btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
  275. }
  276. class SourceMap {
  277. constructor(properties) {
  278. this.version = 3;
  279. this.file = properties.file;
  280. this.sources = properties.sources;
  281. this.sourcesContent = properties.sourcesContent;
  282. this.names = properties.names;
  283. this.mappings = encode(properties.mappings);
  284. }
  285. toString() {
  286. return JSON.stringify(this);
  287. }
  288. toUrl() {
  289. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  290. }
  291. }
  292. function guessIndent(code) {
  293. const lines = code.split('\n');
  294. const tabbed = lines.filter((line) => /^\t+/.test(line));
  295. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  296. if (tabbed.length === 0 && spaced.length === 0) {
  297. return null;
  298. }
  299. // More lines tabbed than spaced? Assume tabs, and
  300. // default to tabs in the case of a tie (or nothing
  301. // to go on)
  302. if (tabbed.length >= spaced.length) {
  303. return '\t';
  304. }
  305. // Otherwise, we need to guess the multiple
  306. const min = spaced.reduce((previous, current) => {
  307. const numSpaces = /^ +/.exec(current)[0].length;
  308. return Math.min(numSpaces, previous);
  309. }, Infinity);
  310. return new Array(min + 1).join(' ');
  311. }
  312. function getRelativePath(from, to) {
  313. const fromParts = from.split(/[/\\]/);
  314. const toParts = to.split(/[/\\]/);
  315. fromParts.pop(); // get dirname
  316. while (fromParts[0] === toParts[0]) {
  317. fromParts.shift();
  318. toParts.shift();
  319. }
  320. if (fromParts.length) {
  321. let i = fromParts.length;
  322. while (i--) fromParts[i] = '..';
  323. }
  324. return fromParts.concat(toParts).join('/');
  325. }
  326. const toString$1 = Object.prototype.toString;
  327. function isObject$1(thing) {
  328. return toString$1.call(thing) === '[object Object]';
  329. }
  330. function getLocator$1(source) {
  331. const originalLines = source.split('\n');
  332. const lineOffsets = [];
  333. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  334. lineOffsets.push(pos);
  335. pos += originalLines[i].length + 1;
  336. }
  337. return function locate(index) {
  338. let i = 0;
  339. let j = lineOffsets.length;
  340. while (i < j) {
  341. const m = (i + j) >> 1;
  342. if (index < lineOffsets[m]) {
  343. j = m;
  344. } else {
  345. i = m + 1;
  346. }
  347. }
  348. const line = i - 1;
  349. const column = index - lineOffsets[line];
  350. return { line, column };
  351. };
  352. }
  353. class Mappings {
  354. constructor(hires) {
  355. this.hires = hires;
  356. this.generatedCodeLine = 0;
  357. this.generatedCodeColumn = 0;
  358. this.raw = [];
  359. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  360. this.pending = null;
  361. }
  362. addEdit(sourceIndex, content, loc, nameIndex) {
  363. if (content.length) {
  364. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  365. if (nameIndex >= 0) {
  366. segment.push(nameIndex);
  367. }
  368. this.rawSegments.push(segment);
  369. } else if (this.pending) {
  370. this.rawSegments.push(this.pending);
  371. }
  372. this.advance(content);
  373. this.pending = null;
  374. }
  375. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  376. let originalCharIndex = chunk.start;
  377. let first = true;
  378. while (originalCharIndex < chunk.end) {
  379. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  380. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  381. }
  382. if (original[originalCharIndex] === '\n') {
  383. loc.line += 1;
  384. loc.column = 0;
  385. this.generatedCodeLine += 1;
  386. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  387. this.generatedCodeColumn = 0;
  388. first = true;
  389. } else {
  390. loc.column += 1;
  391. this.generatedCodeColumn += 1;
  392. first = false;
  393. }
  394. originalCharIndex += 1;
  395. }
  396. this.pending = null;
  397. }
  398. advance(str) {
  399. if (!str) return;
  400. const lines = str.split('\n');
  401. if (lines.length > 1) {
  402. for (let i = 0; i < lines.length - 1; i++) {
  403. this.generatedCodeLine++;
  404. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  405. }
  406. this.generatedCodeColumn = 0;
  407. }
  408. this.generatedCodeColumn += lines[lines.length - 1].length;
  409. }
  410. }
  411. const n = '\n';
  412. const warned = {
  413. insertLeft: false,
  414. insertRight: false,
  415. storeName: false,
  416. };
  417. class MagicString {
  418. constructor(string, options = {}) {
  419. const chunk = new Chunk$1(0, string.length, string);
  420. Object.defineProperties(this, {
  421. original: { writable: true, value: string },
  422. outro: { writable: true, value: '' },
  423. intro: { writable: true, value: '' },
  424. firstChunk: { writable: true, value: chunk },
  425. lastChunk: { writable: true, value: chunk },
  426. lastSearchedChunk: { writable: true, value: chunk },
  427. byStart: { writable: true, value: {} },
  428. byEnd: { writable: true, value: {} },
  429. filename: { writable: true, value: options.filename },
  430. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  431. sourcemapLocations: { writable: true, value: new BitSet() },
  432. storedNames: { writable: true, value: {} },
  433. indentStr: { writable: true, value: guessIndent(string) },
  434. });
  435. this.byStart[0] = chunk;
  436. this.byEnd[string.length] = chunk;
  437. }
  438. addSourcemapLocation(char) {
  439. this.sourcemapLocations.add(char);
  440. }
  441. append(content) {
  442. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  443. this.outro += content;
  444. return this;
  445. }
  446. appendLeft(index, content) {
  447. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  448. this._split(index);
  449. const chunk = this.byEnd[index];
  450. if (chunk) {
  451. chunk.appendLeft(content);
  452. } else {
  453. this.intro += content;
  454. }
  455. return this;
  456. }
  457. appendRight(index, content) {
  458. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  459. this._split(index);
  460. const chunk = this.byStart[index];
  461. if (chunk) {
  462. chunk.appendRight(content);
  463. } else {
  464. this.outro += content;
  465. }
  466. return this;
  467. }
  468. clone() {
  469. const cloned = new MagicString(this.original, { filename: this.filename });
  470. let originalChunk = this.firstChunk;
  471. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  472. while (originalChunk) {
  473. cloned.byStart[clonedChunk.start] = clonedChunk;
  474. cloned.byEnd[clonedChunk.end] = clonedChunk;
  475. const nextOriginalChunk = originalChunk.next;
  476. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  477. if (nextClonedChunk) {
  478. clonedChunk.next = nextClonedChunk;
  479. nextClonedChunk.previous = clonedChunk;
  480. clonedChunk = nextClonedChunk;
  481. }
  482. originalChunk = nextOriginalChunk;
  483. }
  484. cloned.lastChunk = clonedChunk;
  485. if (this.indentExclusionRanges) {
  486. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  487. }
  488. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  489. cloned.intro = this.intro;
  490. cloned.outro = this.outro;
  491. return cloned;
  492. }
  493. generateDecodedMap(options) {
  494. options = options || {};
  495. const sourceIndex = 0;
  496. const names = Object.keys(this.storedNames);
  497. const mappings = new Mappings(options.hires);
  498. const locate = getLocator$1(this.original);
  499. if (this.intro) {
  500. mappings.advance(this.intro);
  501. }
  502. this.firstChunk.eachNext((chunk) => {
  503. const loc = locate(chunk.start);
  504. if (chunk.intro.length) mappings.advance(chunk.intro);
  505. if (chunk.edited) {
  506. mappings.addEdit(
  507. sourceIndex,
  508. chunk.content,
  509. loc,
  510. chunk.storeName ? names.indexOf(chunk.original) : -1
  511. );
  512. } else {
  513. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  514. }
  515. if (chunk.outro.length) mappings.advance(chunk.outro);
  516. });
  517. return {
  518. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  519. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  520. sourcesContent: options.includeContent ? [this.original] : [null],
  521. names,
  522. mappings: mappings.raw,
  523. };
  524. }
  525. generateMap(options) {
  526. return new SourceMap(this.generateDecodedMap(options));
  527. }
  528. getIndentString() {
  529. return this.indentStr === null ? '\t' : this.indentStr;
  530. }
  531. indent(indentStr, options) {
  532. const pattern = /^[^\r\n]/gm;
  533. if (isObject$1(indentStr)) {
  534. options = indentStr;
  535. indentStr = undefined;
  536. }
  537. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  538. if (indentStr === '') return this; // noop
  539. options = options || {};
  540. // Process exclusion ranges
  541. const isExcluded = {};
  542. if (options.exclude) {
  543. const exclusions =
  544. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  545. exclusions.forEach((exclusion) => {
  546. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  547. isExcluded[i] = true;
  548. }
  549. });
  550. }
  551. let shouldIndentNextCharacter = options.indentStart !== false;
  552. const replacer = (match) => {
  553. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  554. shouldIndentNextCharacter = true;
  555. return match;
  556. };
  557. this.intro = this.intro.replace(pattern, replacer);
  558. let charIndex = 0;
  559. let chunk = this.firstChunk;
  560. while (chunk) {
  561. const end = chunk.end;
  562. if (chunk.edited) {
  563. if (!isExcluded[charIndex]) {
  564. chunk.content = chunk.content.replace(pattern, replacer);
  565. if (chunk.content.length) {
  566. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  567. }
  568. }
  569. } else {
  570. charIndex = chunk.start;
  571. while (charIndex < end) {
  572. if (!isExcluded[charIndex]) {
  573. const char = this.original[charIndex];
  574. if (char === '\n') {
  575. shouldIndentNextCharacter = true;
  576. } else if (char !== '\r' && shouldIndentNextCharacter) {
  577. shouldIndentNextCharacter = false;
  578. if (charIndex === chunk.start) {
  579. chunk.prependRight(indentStr);
  580. } else {
  581. this._splitChunk(chunk, charIndex);
  582. chunk = chunk.next;
  583. chunk.prependRight(indentStr);
  584. }
  585. }
  586. }
  587. charIndex += 1;
  588. }
  589. }
  590. charIndex = chunk.end;
  591. chunk = chunk.next;
  592. }
  593. this.outro = this.outro.replace(pattern, replacer);
  594. return this;
  595. }
  596. insert() {
  597. throw new Error(
  598. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  599. );
  600. }
  601. insertLeft(index, content) {
  602. if (!warned.insertLeft) {
  603. console.warn(
  604. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  605. ); // eslint-disable-line no-console
  606. warned.insertLeft = true;
  607. }
  608. return this.appendLeft(index, content);
  609. }
  610. insertRight(index, content) {
  611. if (!warned.insertRight) {
  612. console.warn(
  613. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  614. ); // eslint-disable-line no-console
  615. warned.insertRight = true;
  616. }
  617. return this.prependRight(index, content);
  618. }
  619. move(start, end, index) {
  620. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  621. this._split(start);
  622. this._split(end);
  623. this._split(index);
  624. const first = this.byStart[start];
  625. const last = this.byEnd[end];
  626. const oldLeft = first.previous;
  627. const oldRight = last.next;
  628. const newRight = this.byStart[index];
  629. if (!newRight && last === this.lastChunk) return this;
  630. const newLeft = newRight ? newRight.previous : this.lastChunk;
  631. if (oldLeft) oldLeft.next = oldRight;
  632. if (oldRight) oldRight.previous = oldLeft;
  633. if (newLeft) newLeft.next = first;
  634. if (newRight) newRight.previous = last;
  635. if (!first.previous) this.firstChunk = last.next;
  636. if (!last.next) {
  637. this.lastChunk = first.previous;
  638. this.lastChunk.next = null;
  639. }
  640. first.previous = newLeft;
  641. last.next = newRight || null;
  642. if (!newLeft) this.firstChunk = first;
  643. if (!newRight) this.lastChunk = last;
  644. return this;
  645. }
  646. overwrite(start, end, content, options) {
  647. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  648. while (start < 0) start += this.original.length;
  649. while (end < 0) end += this.original.length;
  650. if (end > this.original.length) throw new Error('end is out of bounds');
  651. if (start === end)
  652. throw new Error(
  653. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  654. );
  655. this._split(start);
  656. this._split(end);
  657. if (options === true) {
  658. if (!warned.storeName) {
  659. console.warn(
  660. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  661. ); // eslint-disable-line no-console
  662. warned.storeName = true;
  663. }
  664. options = { storeName: true };
  665. }
  666. const storeName = options !== undefined ? options.storeName : false;
  667. const contentOnly = options !== undefined ? options.contentOnly : false;
  668. if (storeName) {
  669. const original = this.original.slice(start, end);
  670. Object.defineProperty(this.storedNames, original, {
  671. writable: true,
  672. value: true,
  673. enumerable: true,
  674. });
  675. }
  676. const first = this.byStart[start];
  677. const last = this.byEnd[end];
  678. if (first) {
  679. let chunk = first;
  680. while (chunk !== last) {
  681. if (chunk.next !== this.byStart[chunk.end]) {
  682. throw new Error('Cannot overwrite across a split point');
  683. }
  684. chunk = chunk.next;
  685. chunk.edit('', false);
  686. }
  687. first.edit(content, storeName, contentOnly);
  688. } else {
  689. // must be inserting at the end
  690. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  691. // TODO last chunk in the array may not be the last chunk, if it's moved...
  692. last.next = newChunk;
  693. newChunk.previous = last;
  694. }
  695. return this;
  696. }
  697. prepend(content) {
  698. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  699. this.intro = content + this.intro;
  700. return this;
  701. }
  702. prependLeft(index, content) {
  703. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  704. this._split(index);
  705. const chunk = this.byEnd[index];
  706. if (chunk) {
  707. chunk.prependLeft(content);
  708. } else {
  709. this.intro = content + this.intro;
  710. }
  711. return this;
  712. }
  713. prependRight(index, content) {
  714. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  715. this._split(index);
  716. const chunk = this.byStart[index];
  717. if (chunk) {
  718. chunk.prependRight(content);
  719. } else {
  720. this.outro = content + this.outro;
  721. }
  722. return this;
  723. }
  724. remove(start, end) {
  725. while (start < 0) start += this.original.length;
  726. while (end < 0) end += this.original.length;
  727. if (start === end) return this;
  728. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  729. if (start > end) throw new Error('end must be greater than start');
  730. this._split(start);
  731. this._split(end);
  732. let chunk = this.byStart[start];
  733. while (chunk) {
  734. chunk.intro = '';
  735. chunk.outro = '';
  736. chunk.edit('');
  737. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  738. }
  739. return this;
  740. }
  741. lastChar() {
  742. if (this.outro.length) return this.outro[this.outro.length - 1];
  743. let chunk = this.lastChunk;
  744. do {
  745. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  746. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  747. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  748. } while ((chunk = chunk.previous));
  749. if (this.intro.length) return this.intro[this.intro.length - 1];
  750. return '';
  751. }
  752. lastLine() {
  753. let lineIndex = this.outro.lastIndexOf(n);
  754. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  755. let lineStr = this.outro;
  756. let chunk = this.lastChunk;
  757. do {
  758. if (chunk.outro.length > 0) {
  759. lineIndex = chunk.outro.lastIndexOf(n);
  760. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  761. lineStr = chunk.outro + lineStr;
  762. }
  763. if (chunk.content.length > 0) {
  764. lineIndex = chunk.content.lastIndexOf(n);
  765. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  766. lineStr = chunk.content + lineStr;
  767. }
  768. if (chunk.intro.length > 0) {
  769. lineIndex = chunk.intro.lastIndexOf(n);
  770. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  771. lineStr = chunk.intro + lineStr;
  772. }
  773. } while ((chunk = chunk.previous));
  774. lineIndex = this.intro.lastIndexOf(n);
  775. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  776. return this.intro + lineStr;
  777. }
  778. slice(start = 0, end = this.original.length) {
  779. while (start < 0) start += this.original.length;
  780. while (end < 0) end += this.original.length;
  781. let result = '';
  782. // find start chunk
  783. let chunk = this.firstChunk;
  784. while (chunk && (chunk.start > start || chunk.end <= start)) {
  785. // found end chunk before start
  786. if (chunk.start < end && chunk.end >= end) {
  787. return result;
  788. }
  789. chunk = chunk.next;
  790. }
  791. if (chunk && chunk.edited && chunk.start !== start)
  792. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  793. const startChunk = chunk;
  794. while (chunk) {
  795. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  796. result += chunk.intro;
  797. }
  798. const containsEnd = chunk.start < end && chunk.end >= end;
  799. if (containsEnd && chunk.edited && chunk.end !== end)
  800. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  801. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  802. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  803. result += chunk.content.slice(sliceStart, sliceEnd);
  804. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  805. result += chunk.outro;
  806. }
  807. if (containsEnd) {
  808. break;
  809. }
  810. chunk = chunk.next;
  811. }
  812. return result;
  813. }
  814. // TODO deprecate this? not really very useful
  815. snip(start, end) {
  816. const clone = this.clone();
  817. clone.remove(0, start);
  818. clone.remove(end, clone.original.length);
  819. return clone;
  820. }
  821. _split(index) {
  822. if (this.byStart[index] || this.byEnd[index]) return;
  823. let chunk = this.lastSearchedChunk;
  824. const searchForward = index > chunk.end;
  825. while (chunk) {
  826. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  827. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  828. }
  829. }
  830. _splitChunk(chunk, index) {
  831. if (chunk.edited && chunk.content.length) {
  832. // zero-length edited chunks are a special case (overlapping replacements)
  833. const loc = getLocator$1(this.original)(index);
  834. throw new Error(
  835. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  836. );
  837. }
  838. const newChunk = chunk.split(index);
  839. this.byEnd[index] = chunk;
  840. this.byStart[index] = newChunk;
  841. this.byEnd[newChunk.end] = newChunk;
  842. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  843. this.lastSearchedChunk = chunk;
  844. return true;
  845. }
  846. toString() {
  847. let str = this.intro;
  848. let chunk = this.firstChunk;
  849. while (chunk) {
  850. str += chunk.toString();
  851. chunk = chunk.next;
  852. }
  853. return str + this.outro;
  854. }
  855. isEmpty() {
  856. let chunk = this.firstChunk;
  857. do {
  858. if (
  859. (chunk.intro.length && chunk.intro.trim()) ||
  860. (chunk.content.length && chunk.content.trim()) ||
  861. (chunk.outro.length && chunk.outro.trim())
  862. )
  863. return false;
  864. } while ((chunk = chunk.next));
  865. return true;
  866. }
  867. length() {
  868. let chunk = this.firstChunk;
  869. let length = 0;
  870. do {
  871. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  872. } while ((chunk = chunk.next));
  873. return length;
  874. }
  875. trimLines() {
  876. return this.trim('[\\r\\n]');
  877. }
  878. trim(charType) {
  879. return this.trimStart(charType).trimEnd(charType);
  880. }
  881. trimEndAborted(charType) {
  882. const rx = new RegExp((charType || '\\s') + '+$');
  883. this.outro = this.outro.replace(rx, '');
  884. if (this.outro.length) return true;
  885. let chunk = this.lastChunk;
  886. do {
  887. const end = chunk.end;
  888. const aborted = chunk.trimEnd(rx);
  889. // if chunk was trimmed, we have a new lastChunk
  890. if (chunk.end !== end) {
  891. if (this.lastChunk === chunk) {
  892. this.lastChunk = chunk.next;
  893. }
  894. this.byEnd[chunk.end] = chunk;
  895. this.byStart[chunk.next.start] = chunk.next;
  896. this.byEnd[chunk.next.end] = chunk.next;
  897. }
  898. if (aborted) return true;
  899. chunk = chunk.previous;
  900. } while (chunk);
  901. return false;
  902. }
  903. trimEnd(charType) {
  904. this.trimEndAborted(charType);
  905. return this;
  906. }
  907. trimStartAborted(charType) {
  908. const rx = new RegExp('^' + (charType || '\\s') + '+');
  909. this.intro = this.intro.replace(rx, '');
  910. if (this.intro.length) return true;
  911. let chunk = this.firstChunk;
  912. do {
  913. const end = chunk.end;
  914. const aborted = chunk.trimStart(rx);
  915. if (chunk.end !== end) {
  916. // special case...
  917. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  918. this.byEnd[chunk.end] = chunk;
  919. this.byStart[chunk.next.start] = chunk.next;
  920. this.byEnd[chunk.next.end] = chunk.next;
  921. }
  922. if (aborted) return true;
  923. chunk = chunk.next;
  924. } while (chunk);
  925. return false;
  926. }
  927. trimStart(charType) {
  928. this.trimStartAborted(charType);
  929. return this;
  930. }
  931. hasChanged() {
  932. return this.original !== this.toString();
  933. }
  934. replace(searchValue, replacement) {
  935. function getReplacement(match, str) {
  936. if (typeof replacement === 'string') {
  937. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  938. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  939. if (i === '$') return '$';
  940. if (i === '&') return match[0];
  941. const num = +i;
  942. if (num < match.length) return match[+i];
  943. return `$${i}`;
  944. });
  945. } else {
  946. return replacement(...match, match.index, str, match.groups);
  947. }
  948. }
  949. function matchAll(re, str) {
  950. let match;
  951. const matches = [];
  952. while ((match = re.exec(str))) {
  953. matches.push(match);
  954. }
  955. return matches;
  956. }
  957. if (typeof searchValue !== 'string' && searchValue.global) {
  958. const matches = matchAll(searchValue, this.original);
  959. matches.forEach((match) => {
  960. if (match.index != null)
  961. this.overwrite(
  962. match.index,
  963. match.index + match[0].length,
  964. getReplacement(match, this.original)
  965. );
  966. });
  967. } else {
  968. const match = this.original.match(searchValue);
  969. if (match && match.index != null)
  970. this.overwrite(
  971. match.index,
  972. match.index + match[0].length,
  973. getReplacement(match, this.original)
  974. );
  975. }
  976. return this;
  977. }
  978. }
  979. const hasOwnProp = Object.prototype.hasOwnProperty;
  980. class Bundle$1 {
  981. constructor(options = {}) {
  982. this.intro = options.intro || '';
  983. this.separator = options.separator !== undefined ? options.separator : '\n';
  984. this.sources = [];
  985. this.uniqueSources = [];
  986. this.uniqueSourceIndexByFilename = {};
  987. }
  988. addSource(source) {
  989. if (source instanceof MagicString) {
  990. return this.addSource({
  991. content: source,
  992. filename: source.filename,
  993. separator: this.separator,
  994. });
  995. }
  996. if (!isObject$1(source) || !source.content) {
  997. throw new Error(
  998. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  999. );
  1000. }
  1001. ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1002. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1003. });
  1004. if (source.separator === undefined) {
  1005. // TODO there's a bunch of this sort of thing, needs cleaning up
  1006. source.separator = this.separator;
  1007. }
  1008. if (source.filename) {
  1009. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1010. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1011. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1012. } else {
  1013. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1014. if (source.content.original !== uniqueSource.content) {
  1015. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1016. }
  1017. }
  1018. }
  1019. this.sources.push(source);
  1020. return this;
  1021. }
  1022. append(str, options) {
  1023. this.addSource({
  1024. content: new MagicString(str),
  1025. separator: (options && options.separator) || '',
  1026. });
  1027. return this;
  1028. }
  1029. clone() {
  1030. const bundle = new Bundle$1({
  1031. intro: this.intro,
  1032. separator: this.separator,
  1033. });
  1034. this.sources.forEach((source) => {
  1035. bundle.addSource({
  1036. filename: source.filename,
  1037. content: source.content.clone(),
  1038. separator: source.separator,
  1039. });
  1040. });
  1041. return bundle;
  1042. }
  1043. generateDecodedMap(options = {}) {
  1044. const names = [];
  1045. this.sources.forEach((source) => {
  1046. Object.keys(source.content.storedNames).forEach((name) => {
  1047. if (!~names.indexOf(name)) names.push(name);
  1048. });
  1049. });
  1050. const mappings = new Mappings(options.hires);
  1051. if (this.intro) {
  1052. mappings.advance(this.intro);
  1053. }
  1054. this.sources.forEach((source, i) => {
  1055. if (i > 0) {
  1056. mappings.advance(this.separator);
  1057. }
  1058. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1059. const magicString = source.content;
  1060. const locate = getLocator$1(magicString.original);
  1061. if (magicString.intro) {
  1062. mappings.advance(magicString.intro);
  1063. }
  1064. magicString.firstChunk.eachNext((chunk) => {
  1065. const loc = locate(chunk.start);
  1066. if (chunk.intro.length) mappings.advance(chunk.intro);
  1067. if (source.filename) {
  1068. if (chunk.edited) {
  1069. mappings.addEdit(
  1070. sourceIndex,
  1071. chunk.content,
  1072. loc,
  1073. chunk.storeName ? names.indexOf(chunk.original) : -1
  1074. );
  1075. } else {
  1076. mappings.addUneditedChunk(
  1077. sourceIndex,
  1078. chunk,
  1079. magicString.original,
  1080. loc,
  1081. magicString.sourcemapLocations
  1082. );
  1083. }
  1084. } else {
  1085. mappings.advance(chunk.content);
  1086. }
  1087. if (chunk.outro.length) mappings.advance(chunk.outro);
  1088. });
  1089. if (magicString.outro) {
  1090. mappings.advance(magicString.outro);
  1091. }
  1092. });
  1093. return {
  1094. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1095. sources: this.uniqueSources.map((source) => {
  1096. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1097. }),
  1098. sourcesContent: this.uniqueSources.map((source) => {
  1099. return options.includeContent ? source.content : null;
  1100. }),
  1101. names,
  1102. mappings: mappings.raw,
  1103. };
  1104. }
  1105. generateMap(options) {
  1106. return new SourceMap(this.generateDecodedMap(options));
  1107. }
  1108. getIndentString() {
  1109. const indentStringCounts = {};
  1110. this.sources.forEach((source) => {
  1111. const indentStr = source.content.indentStr;
  1112. if (indentStr === null) return;
  1113. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1114. indentStringCounts[indentStr] += 1;
  1115. });
  1116. return (
  1117. Object.keys(indentStringCounts).sort((a, b) => {
  1118. return indentStringCounts[a] - indentStringCounts[b];
  1119. })[0] || '\t'
  1120. );
  1121. }
  1122. indent(indentStr) {
  1123. if (!arguments.length) {
  1124. indentStr = this.getIndentString();
  1125. }
  1126. if (indentStr === '') return this; // noop
  1127. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1128. this.sources.forEach((source, i) => {
  1129. const separator = source.separator !== undefined ? source.separator : this.separator;
  1130. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1131. source.content.indent(indentStr, {
  1132. exclude: source.indentExclusionRanges,
  1133. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1134. });
  1135. trailingNewline = source.content.lastChar() === '\n';
  1136. });
  1137. if (this.intro) {
  1138. this.intro =
  1139. indentStr +
  1140. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1141. return index > 0 ? indentStr + match : match;
  1142. });
  1143. }
  1144. return this;
  1145. }
  1146. prepend(str) {
  1147. this.intro = str + this.intro;
  1148. return this;
  1149. }
  1150. toString() {
  1151. const body = this.sources
  1152. .map((source, i) => {
  1153. const separator = source.separator !== undefined ? source.separator : this.separator;
  1154. const str = (i > 0 ? separator : '') + source.content.toString();
  1155. return str;
  1156. })
  1157. .join('');
  1158. return this.intro + body;
  1159. }
  1160. isEmpty() {
  1161. if (this.intro.length && this.intro.trim()) return false;
  1162. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1163. return true;
  1164. }
  1165. length() {
  1166. return this.sources.reduce(
  1167. (length, source) => length + source.content.length(),
  1168. this.intro.length
  1169. );
  1170. }
  1171. trimLines() {
  1172. return this.trim('[\\r\\n]');
  1173. }
  1174. trim(charType) {
  1175. return this.trimStart(charType).trimEnd(charType);
  1176. }
  1177. trimStart(charType) {
  1178. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1179. this.intro = this.intro.replace(rx, '');
  1180. if (!this.intro) {
  1181. let source;
  1182. let i = 0;
  1183. do {
  1184. source = this.sources[i++];
  1185. if (!source) {
  1186. break;
  1187. }
  1188. } while (!source.content.trimStartAborted(charType));
  1189. }
  1190. return this;
  1191. }
  1192. trimEnd(charType) {
  1193. const rx = new RegExp((charType || '\\s') + '+$');
  1194. let source;
  1195. let i = this.sources.length - 1;
  1196. do {
  1197. source = this.sources[i--];
  1198. if (!source) {
  1199. this.intro = this.intro.replace(rx, '');
  1200. break;
  1201. }
  1202. } while (!source.content.trimEndAborted(charType));
  1203. return this;
  1204. }
  1205. }
  1206. const ANY_SLASH_REGEX = /[/\\]/;
  1207. function relative(from, to) {
  1208. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  1209. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  1210. if (fromParts[0] === '.')
  1211. fromParts.shift();
  1212. if (toParts[0] === '.')
  1213. toParts.shift();
  1214. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1215. fromParts.shift();
  1216. toParts.shift();
  1217. }
  1218. while (toParts[0] === '..' && fromParts.length > 0) {
  1219. toParts.shift();
  1220. fromParts.pop();
  1221. }
  1222. while (fromParts.pop()) {
  1223. toParts.unshift('..');
  1224. }
  1225. return toParts.join('/');
  1226. }
  1227. function getOrCreate(map, key, init) {
  1228. const existing = map.get(key);
  1229. if (existing) {
  1230. return existing;
  1231. }
  1232. const value = init();
  1233. map.set(key, value);
  1234. return value;
  1235. }
  1236. const UnknownKey = Symbol('Unknown Key');
  1237. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1238. const UnknownInteger = Symbol('Unknown Integer');
  1239. const EMPTY_PATH = [];
  1240. const UNKNOWN_PATH = [UnknownKey];
  1241. // For deoptimizations, this means we are modifying an unknown property but did
  1242. // not lose track of the object or are creating a setter/getter;
  1243. // For assignment effects it means we do not check for setter/getter effects
  1244. // but only if something is mutated that is included, which is relevant for
  1245. // Object.defineProperty
  1246. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1247. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1248. const EntitiesKey = Symbol('Entities');
  1249. class PathTracker {
  1250. constructor() {
  1251. this.entityPaths = Object.create(null, {
  1252. [EntitiesKey]: { value: new Set() }
  1253. });
  1254. }
  1255. trackEntityAtPathAndGetIfTracked(path, entity) {
  1256. const trackedEntities = this.getEntities(path);
  1257. if (trackedEntities.has(entity))
  1258. return true;
  1259. trackedEntities.add(entity);
  1260. return false;
  1261. }
  1262. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1263. const trackedEntities = this.getEntities(path);
  1264. if (trackedEntities.has(entity))
  1265. return returnIfTracked;
  1266. trackedEntities.add(entity);
  1267. const result = onUntracked();
  1268. trackedEntities.delete(entity);
  1269. return result;
  1270. }
  1271. getEntities(path) {
  1272. let currentPaths = this.entityPaths;
  1273. for (const pathSegment of path) {
  1274. currentPaths = currentPaths[pathSegment] =
  1275. currentPaths[pathSegment] ||
  1276. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1277. }
  1278. return currentPaths[EntitiesKey];
  1279. }
  1280. }
  1281. const SHARED_RECURSION_TRACKER = new PathTracker();
  1282. class DiscriminatedPathTracker {
  1283. constructor() {
  1284. this.entityPaths = Object.create(null, {
  1285. [EntitiesKey]: { value: new Map() }
  1286. });
  1287. }
  1288. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1289. let currentPaths = this.entityPaths;
  1290. for (const pathSegment of path) {
  1291. currentPaths = currentPaths[pathSegment] =
  1292. currentPaths[pathSegment] ||
  1293. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1294. }
  1295. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1296. if (trackedEntities.has(entity))
  1297. return true;
  1298. trackedEntities.add(entity);
  1299. return false;
  1300. }
  1301. }
  1302. const UnknownValue = Symbol('Unknown Value');
  1303. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1304. class ExpressionEntity {
  1305. constructor() {
  1306. this.included = false;
  1307. }
  1308. deoptimizePath(_path) { }
  1309. deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
  1310. thisArg.deoptimizePath(UNKNOWN_PATH);
  1311. }
  1312. /**
  1313. * If possible it returns a stringifyable literal value for this node that can be used
  1314. * for inlining or comparing values.
  1315. * Otherwise it should return UnknownValue.
  1316. */
  1317. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1318. return UnknownValue;
  1319. }
  1320. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1321. return UNKNOWN_EXPRESSION;
  1322. }
  1323. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1324. return true;
  1325. }
  1326. include(_context, _includeChildrenRecursively, _options) {
  1327. this.included = true;
  1328. }
  1329. includeCallArguments(context, args) {
  1330. for (const arg of args) {
  1331. arg.include(context, false);
  1332. }
  1333. }
  1334. shouldBeIncluded(_context) {
  1335. return true;
  1336. }
  1337. }
  1338. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1339. })();
  1340. const INTERACTION_ACCESSED = 0;
  1341. const INTERACTION_ASSIGNED = 1;
  1342. const INTERACTION_CALLED = 2;
  1343. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1344. thisArg: null,
  1345. type: INTERACTION_ACCESSED
  1346. };
  1347. const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
  1348. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1349. args: UNKNOWN_ARG,
  1350. thisArg: null,
  1351. type: INTERACTION_ASSIGNED
  1352. };
  1353. const NO_ARGS = [];
  1354. // While this is technically a call without arguments, we can compare against
  1355. // this reference in places where precise values or thisArg would make a
  1356. // difference
  1357. const NODE_INTERACTION_UNKNOWN_CALL = {
  1358. args: NO_ARGS,
  1359. thisArg: null,
  1360. type: INTERACTION_CALLED,
  1361. withNew: false
  1362. };
  1363. class Variable extends ExpressionEntity {
  1364. constructor(name) {
  1365. super();
  1366. this.name = name;
  1367. this.alwaysRendered = false;
  1368. this.initReached = false;
  1369. this.isId = false;
  1370. this.isReassigned = false;
  1371. this.kind = null;
  1372. this.renderBaseName = null;
  1373. this.renderName = null;
  1374. }
  1375. /**
  1376. * Binds identifiers that reference this variable to this variable.
  1377. * Necessary to be able to change variable names.
  1378. */
  1379. addReference(_identifier) { }
  1380. getBaseVariableName() {
  1381. return this.renderBaseName || this.renderName || this.name;
  1382. }
  1383. getName(getPropertyAccess) {
  1384. const name = this.renderName || this.name;
  1385. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  1386. }
  1387. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  1388. return type !== INTERACTION_ACCESSED || path.length > 0;
  1389. }
  1390. /**
  1391. * Marks this variable as being part of the bundle, which is usually the case when one of
  1392. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1393. * previously.
  1394. * Once a variable is included, it should take care all its declarations are included.
  1395. */
  1396. include() {
  1397. this.included = true;
  1398. }
  1399. markCalledFromTryStatement() { }
  1400. setRenderNames(baseName, name) {
  1401. this.renderBaseName = baseName;
  1402. this.renderName = name;
  1403. }
  1404. }
  1405. class ExternalVariable extends Variable {
  1406. constructor(module, name) {
  1407. super(name);
  1408. this.referenced = false;
  1409. this.module = module;
  1410. this.isNamespace = name === '*';
  1411. }
  1412. addReference(identifier) {
  1413. this.referenced = true;
  1414. if (this.name === 'default' || this.name === '*') {
  1415. this.module.suggestName(identifier.name);
  1416. }
  1417. }
  1418. hasEffectsOnInteractionAtPath(path, { type }) {
  1419. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  1420. }
  1421. include() {
  1422. if (!this.included) {
  1423. this.included = true;
  1424. this.module.used = true;
  1425. }
  1426. }
  1427. }
  1428. const BLANK = Object.freeze(Object.create(null));
  1429. const EMPTY_OBJECT = Object.freeze({});
  1430. const EMPTY_ARRAY = Object.freeze([]);
  1431. function getLocator(source, options) {
  1432. if (options === void 0) { options = {}; }
  1433. var offsetLine = options.offsetLine || 0;
  1434. var offsetColumn = options.offsetColumn || 0;
  1435. var originalLines = source.split('\n');
  1436. var start = 0;
  1437. var lineRanges = originalLines.map(function (line, i) {
  1438. var end = start + line.length + 1;
  1439. var range = { start: start, end: end, line: i };
  1440. start = end;
  1441. return range;
  1442. });
  1443. var i = 0;
  1444. function rangeContains(range, index) {
  1445. return range.start <= index && index < range.end;
  1446. }
  1447. function getLocation(range, index) {
  1448. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  1449. }
  1450. function locate(search, startIndex) {
  1451. if (typeof search === 'string') {
  1452. search = source.indexOf(search, startIndex || 0);
  1453. }
  1454. var range = lineRanges[i];
  1455. var d = search >= range.end ? 1 : -1;
  1456. while (range) {
  1457. if (rangeContains(range, search))
  1458. return getLocation(range, search);
  1459. i += d;
  1460. range = lineRanges[i];
  1461. }
  1462. }
  1463. return locate;
  1464. }
  1465. function locate(source, search, options) {
  1466. if (typeof options === 'number') {
  1467. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  1468. }
  1469. return getLocator(source, options)(search, options && options.startIndex);
  1470. }
  1471. function spaces(i) {
  1472. let result = '';
  1473. while (i--)
  1474. result += ' ';
  1475. return result;
  1476. }
  1477. function tabsToSpaces(str) {
  1478. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  1479. }
  1480. function getCodeFrame(source, line, column) {
  1481. let lines = source.split('\n');
  1482. const frameStart = Math.max(0, line - 3);
  1483. let frameEnd = Math.min(line + 2, lines.length);
  1484. lines = lines.slice(frameStart, frameEnd);
  1485. while (!/\S/.test(lines[lines.length - 1])) {
  1486. lines.pop();
  1487. frameEnd -= 1;
  1488. }
  1489. const digits = String(frameEnd).length;
  1490. return lines
  1491. .map((str, i) => {
  1492. const isErrorLine = frameStart + i + 1 === line;
  1493. let lineNum = String(i + frameStart + 1);
  1494. while (lineNum.length < digits)
  1495. lineNum = ` ${lineNum}`;
  1496. if (isErrorLine) {
  1497. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  1498. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  1499. }
  1500. return `${lineNum}: ${tabsToSpaces(str)}`;
  1501. })
  1502. .join('\n');
  1503. }
  1504. function printQuotedStringList(list, verbs) {
  1505. const isSingleItem = list.length <= 1;
  1506. const quotedList = list.map(item => `"${item}"`);
  1507. let output = isSingleItem
  1508. ? quotedList[0]
  1509. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  1510. if (verbs) {
  1511. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  1512. }
  1513. return output;
  1514. }
  1515. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  1516. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  1517. function isAbsolute(path) {
  1518. return ABSOLUTE_PATH_REGEX.test(path);
  1519. }
  1520. function isRelative(path) {
  1521. return RELATIVE_PATH_REGEX.test(path);
  1522. }
  1523. const BACKSLASH_REGEX = /\\/g;
  1524. function normalize(path) {
  1525. return path.replace(BACKSLASH_REGEX, '/');
  1526. }
  1527. function getAliasName(id) {
  1528. const base = basename(id);
  1529. return base.substring(0, base.length - extname(id).length);
  1530. }
  1531. function relativeId(id) {
  1532. if (!isAbsolute(id))
  1533. return id;
  1534. return relative(resolve(), id);
  1535. }
  1536. function isPathFragment(name) {
  1537. // starting with "/", "./", "../", "C:/"
  1538. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  1539. }
  1540. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  1541. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  1542. let relativePath = normalize(relative(dirname(importerId), targetPath));
  1543. if (stripJsExtension && relativePath.endsWith('.js')) {
  1544. relativePath = relativePath.slice(0, -3);
  1545. }
  1546. if (ensureFileName) {
  1547. if (relativePath === '')
  1548. return '../' + basename(targetPath);
  1549. if (UPPER_DIR_REGEX.test(relativePath)) {
  1550. return relativePath
  1551. .split('/')
  1552. .concat(['..', basename(targetPath)])
  1553. .join('/');
  1554. }
  1555. }
  1556. return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
  1557. }
  1558. function error(base) {
  1559. if (!(base instanceof Error))
  1560. base = Object.assign(new Error(base.message), base);
  1561. throw base;
  1562. }
  1563. function augmentCodeLocation(props, pos, source, id) {
  1564. if (typeof pos === 'object') {
  1565. const { line, column } = pos;
  1566. props.loc = { column, file: id, line };
  1567. }
  1568. else {
  1569. props.pos = pos;
  1570. const { line, column } = locate(source, pos, { offsetLine: 1 });
  1571. props.loc = { column, file: id, line };
  1572. }
  1573. if (props.frame === undefined) {
  1574. const { line, column } = props.loc;
  1575. props.frame = getCodeFrame(source, line, column);
  1576. }
  1577. }
  1578. var Errors;
  1579. (function (Errors) {
  1580. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  1581. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  1582. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  1583. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  1584. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  1585. Errors["BAD_LOADER"] = "BAD_LOADER";
  1586. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  1587. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  1588. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  1589. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  1590. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  1591. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  1592. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  1593. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  1594. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  1595. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  1596. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  1597. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  1598. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  1599. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  1600. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  1601. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  1602. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  1603. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  1604. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  1605. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  1606. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  1607. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  1608. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  1609. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  1610. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  1611. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  1612. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  1613. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  1614. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  1615. })(Errors || (Errors = {}));
  1616. function errAssetNotFinalisedForFileName(name) {
  1617. return {
  1618. code: Errors.ASSET_NOT_FINALISED,
  1619. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  1620. };
  1621. }
  1622. function errCannotEmitFromOptionsHook() {
  1623. return {
  1624. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  1625. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  1626. };
  1627. }
  1628. function errChunkNotGeneratedForFileName(name) {
  1629. return {
  1630. code: Errors.CHUNK_NOT_GENERATED,
  1631. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  1632. };
  1633. }
  1634. function errChunkInvalid({ fileName, code }, exception) {
  1635. const errorProps = {
  1636. code: Errors.CHUNK_INVALID,
  1637. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  1638. };
  1639. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  1640. return errorProps;
  1641. }
  1642. function errCircularReexport(exportName, importedModule) {
  1643. return {
  1644. code: Errors.CIRCULAR_REEXPORT,
  1645. id: importedModule,
  1646. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  1647. };
  1648. }
  1649. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  1650. return {
  1651. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  1652. exporter,
  1653. importer,
  1654. 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 do not use "preserveModules" to ensure these modules end up in the same chunk.`,
  1655. reexporter
  1656. };
  1657. }
  1658. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  1659. return {
  1660. code: Errors.ASSET_NOT_FOUND,
  1661. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  1662. };
  1663. }
  1664. function errAssetSourceAlreadySet(name) {
  1665. return {
  1666. code: Errors.ASSET_SOURCE_ALREADY_SET,
  1667. message: `Unable to set the source for asset "${name}", source already set.`
  1668. };
  1669. }
  1670. function errNoAssetSourceSet(assetName) {
  1671. return {
  1672. code: Errors.ASSET_SOURCE_MISSING,
  1673. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  1674. };
  1675. }
  1676. function errBadLoader(id) {
  1677. return {
  1678. code: Errors.BAD_LOADER,
  1679. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  1680. };
  1681. }
  1682. function errDeprecation(deprecation) {
  1683. return {
  1684. code: Errors.DEPRECATED_FEATURE,
  1685. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  1686. };
  1687. }
  1688. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  1689. return {
  1690. code: Errors.FILE_NOT_FOUND,
  1691. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  1692. };
  1693. }
  1694. function errFileNameConflict(fileName) {
  1695. return {
  1696. code: Errors.FILE_NAME_CONFLICT,
  1697. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  1698. };
  1699. }
  1700. function errInputHookInOutputPlugin(pluginName, hookName) {
  1701. return {
  1702. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  1703. 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.`
  1704. };
  1705. }
  1706. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  1707. return {
  1708. code: Errors.INVALID_CHUNK,
  1709. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  1710. };
  1711. }
  1712. function errInvalidExportOptionValue(optionValue) {
  1713. return {
  1714. code: Errors.INVALID_EXPORT_OPTION,
  1715. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  1716. url: `https://rollupjs.org/guide/en/#outputexports`
  1717. };
  1718. }
  1719. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  1720. return {
  1721. code: 'INVALID_EXPORT_OPTION',
  1722. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  1723. };
  1724. }
  1725. function errInternalIdCannotBeExternal(source, importer) {
  1726. return {
  1727. code: Errors.INVALID_EXTERNAL_ID,
  1728. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  1729. };
  1730. }
  1731. function errInvalidOption(option, urlHash, explanation, value) {
  1732. return {
  1733. code: Errors.INVALID_OPTION,
  1734. message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
  1735. url: `https://rollupjs.org/guide/en/#${urlHash}`
  1736. };
  1737. }
  1738. function errInvalidAddonPluginHook(hook, plugin) {
  1739. return {
  1740. code: Errors.INVALID_PLUGIN_HOOK,
  1741. hook,
  1742. message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a string, a function hook or an object with a "handler" string or function.`,
  1743. plugin
  1744. };
  1745. }
  1746. function errInvalidFunctionPluginHook(hook, plugin) {
  1747. return {
  1748. code: Errors.INVALID_PLUGIN_HOOK,
  1749. hook,
  1750. message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a function hook or an object with a "handler" function.`,
  1751. plugin
  1752. };
  1753. }
  1754. function errInvalidRollupPhaseForAddWatchFile() {
  1755. return {
  1756. code: Errors.INVALID_ROLLUP_PHASE,
  1757. message: `Cannot call addWatchFile after the build has finished.`
  1758. };
  1759. }
  1760. function errInvalidRollupPhaseForChunkEmission() {
  1761. return {
  1762. code: Errors.INVALID_ROLLUP_PHASE,
  1763. message: `Cannot emit chunks after module loading has finished.`
  1764. };
  1765. }
  1766. function errMissingExport(exportName, importingModule, importedModule) {
  1767. return {
  1768. code: Errors.MISSING_EXPORT,
  1769. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  1770. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  1771. };
  1772. }
  1773. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  1774. return {
  1775. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1776. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  1777. };
  1778. }
  1779. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  1780. return {
  1781. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1782. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  1783. };
  1784. }
  1785. function errImplicitDependantIsNotIncluded(module) {
  1786. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  1787. return {
  1788. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1789. 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.`
  1790. };
  1791. }
  1792. function errMixedExport(facadeModuleId, name) {
  1793. return {
  1794. code: Errors.MIXED_EXPORTS,
  1795. id: facadeModuleId,
  1796. 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`,
  1797. url: `https://rollupjs.org/guide/en/#outputexports`
  1798. };
  1799. }
  1800. function errNamespaceConflict(name, reexportingModuleId, sources) {
  1801. return {
  1802. code: Errors.NAMESPACE_CONFLICT,
  1803. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
  1804. name,
  1805. reexporter: reexportingModuleId,
  1806. sources
  1807. };
  1808. }
  1809. function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
  1810. return {
  1811. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  1812. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
  1813. name,
  1814. reexporter: reexportingModule,
  1815. sources
  1816. };
  1817. }
  1818. function errNoTransformMapOrAstWithoutCode(pluginName) {
  1819. return {
  1820. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  1821. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  1822. 'a "code". This will be ignored.'
  1823. };
  1824. }
  1825. function errPreferNamedExports(facadeModuleId) {
  1826. const file = relativeId(facadeModuleId);
  1827. return {
  1828. code: Errors.PREFER_NAMED_EXPORTS,
  1829. id: facadeModuleId,
  1830. message: `Entry module "${file}" is implicitly using "default" export mode, which means for CommonJS output that its default export is assigned to "module.exports". For many tools, such CommonJS output will not be interchangeable with the original ES module. If this is intended, explicitly set "output.exports" to either "auto" or "default", otherwise you might want to consider changing the signature of "${file}" to use named exports only.`,
  1831. url: `https://rollupjs.org/guide/en/#outputexports`
  1832. };
  1833. }
  1834. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  1835. return {
  1836. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  1837. id,
  1838. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  1839. ? `an explicit export named "${syntheticNamedExportsOption}"`
  1840. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  1841. };
  1842. }
  1843. function errUnexpectedNamedImport(id, imported, isReexport) {
  1844. const importType = isReexport ? 'reexport' : 'import';
  1845. return {
  1846. code: Errors.UNEXPECTED_NAMED_IMPORT,
  1847. id,
  1848. 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.`,
  1849. url: 'https://rollupjs.org/guide/en/#outputinterop'
  1850. };
  1851. }
  1852. function errUnexpectedNamespaceReexport(id) {
  1853. return {
  1854. code: Errors.UNEXPECTED_NAMED_IMPORT,
  1855. id,
  1856. 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.`,
  1857. url: 'https://rollupjs.org/guide/en/#outputinterop'
  1858. };
  1859. }
  1860. function errEntryCannotBeExternal(unresolvedId) {
  1861. return {
  1862. code: Errors.UNRESOLVED_ENTRY,
  1863. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  1864. };
  1865. }
  1866. function errUnresolvedEntry(unresolvedId) {
  1867. return {
  1868. code: Errors.UNRESOLVED_ENTRY,
  1869. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  1870. };
  1871. }
  1872. function errUnresolvedImport(source, importer) {
  1873. return {
  1874. code: Errors.UNRESOLVED_IMPORT,
  1875. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  1876. };
  1877. }
  1878. function errUnresolvedImportTreatedAsExternal(source, importer) {
  1879. return {
  1880. code: Errors.UNRESOLVED_IMPORT,
  1881. importer: relativeId(importer),
  1882. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  1883. source,
  1884. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  1885. };
  1886. }
  1887. function errExternalSyntheticExports(source, importer) {
  1888. return {
  1889. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  1890. importer: relativeId(importer),
  1891. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  1892. source
  1893. };
  1894. }
  1895. function errFailedValidation(message) {
  1896. return {
  1897. code: Errors.VALIDATION_ERROR,
  1898. message
  1899. };
  1900. }
  1901. function errAlreadyClosed() {
  1902. return {
  1903. code: Errors.ALREADY_CLOSED,
  1904. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  1905. };
  1906. }
  1907. function warnDeprecation(deprecation, activeDeprecation, options) {
  1908. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  1909. }
  1910. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  1911. if (activeDeprecation || strictDeprecations) {
  1912. const warning = errDeprecation(deprecation);
  1913. if (strictDeprecations) {
  1914. return error(warning);
  1915. }
  1916. warn(warning);
  1917. }
  1918. }
  1919. const RESERVED_NAMES = new Set([
  1920. 'await',
  1921. 'break',
  1922. 'case',
  1923. 'catch',
  1924. 'class',
  1925. 'const',
  1926. 'continue',
  1927. 'debugger',
  1928. 'default',
  1929. 'delete',
  1930. 'do',
  1931. 'else',
  1932. 'enum',
  1933. 'eval',
  1934. 'export',
  1935. 'extends',
  1936. 'false',
  1937. 'finally',
  1938. 'for',
  1939. 'function',
  1940. 'if',
  1941. 'implements',
  1942. 'import',
  1943. 'in',
  1944. 'instanceof',
  1945. 'interface',
  1946. 'let',
  1947. 'NaN',
  1948. 'new',
  1949. 'null',
  1950. 'package',
  1951. 'private',
  1952. 'protected',
  1953. 'public',
  1954. 'return',
  1955. 'static',
  1956. 'super',
  1957. 'switch',
  1958. 'this',
  1959. 'throw',
  1960. 'true',
  1961. 'try',
  1962. 'typeof',
  1963. 'undefined',
  1964. 'var',
  1965. 'void',
  1966. 'while',
  1967. 'with',
  1968. 'yield'
  1969. ]);
  1970. const RESERVED_NAMES$1 = RESERVED_NAMES;
  1971. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  1972. const startsWithDigit = (str) => /\d/.test(str[0]);
  1973. const needsEscape = (str) => startsWithDigit(str) || RESERVED_NAMES$1.has(str) || str === 'arguments';
  1974. function isLegal(str) {
  1975. if (needsEscape(str)) {
  1976. return false;
  1977. }
  1978. return !illegalCharacters.test(str);
  1979. }
  1980. function makeLegal(str) {
  1981. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  1982. if (needsEscape(str))
  1983. str = `_${str}`;
  1984. return str || '_';
  1985. }
  1986. class ExternalModule {
  1987. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
  1988. this.options = options;
  1989. this.id = id;
  1990. this.renormalizeRenderPath = renormalizeRenderPath;
  1991. this.declarations = new Map();
  1992. this.defaultVariableName = '';
  1993. this.dynamicImporters = [];
  1994. this.execIndex = Infinity;
  1995. this.exportedVariables = new Map();
  1996. this.importers = [];
  1997. this.mostCommonSuggestion = 0;
  1998. this.nameSuggestions = new Map();
  1999. this.namespaceVariableName = '';
  2000. this.reexported = false;
  2001. this.renderPath = undefined;
  2002. this.used = false;
  2003. this.variableName = '';
  2004. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  2005. const { importers, dynamicImporters } = this;
  2006. const info = (this.info = {
  2007. ast: null,
  2008. code: null,
  2009. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2010. dynamicallyImportedIds: EMPTY_ARRAY,
  2011. get dynamicImporters() {
  2012. return dynamicImporters.sort();
  2013. },
  2014. hasDefaultExport: null,
  2015. get hasModuleSideEffects() {
  2016. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  2017. return info.moduleSideEffects;
  2018. },
  2019. id,
  2020. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2021. implicitlyLoadedBefore: EMPTY_ARRAY,
  2022. importedIdResolutions: EMPTY_ARRAY,
  2023. importedIds: EMPTY_ARRAY,
  2024. get importers() {
  2025. return importers.sort();
  2026. },
  2027. isEntry: false,
  2028. isExternal: true,
  2029. isIncluded: null,
  2030. meta,
  2031. moduleSideEffects,
  2032. syntheticNamedExports: false
  2033. });
  2034. // Hide the deprecated key so that it only warns when accessed explicitly
  2035. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2036. enumerable: false
  2037. });
  2038. }
  2039. getVariableForExportName(name) {
  2040. const declaration = this.declarations.get(name);
  2041. if (declaration)
  2042. return [declaration];
  2043. const externalVariable = new ExternalVariable(this, name);
  2044. this.declarations.set(name, externalVariable);
  2045. this.exportedVariables.set(externalVariable, name);
  2046. return [externalVariable];
  2047. }
  2048. setRenderPath(options, inputBase) {
  2049. this.renderPath =
  2050. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2051. if (!this.renderPath) {
  2052. this.renderPath = this.renormalizeRenderPath
  2053. ? normalize(relative$1(inputBase, this.id))
  2054. : this.id;
  2055. }
  2056. }
  2057. suggestName(name) {
  2058. var _a;
  2059. const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
  2060. this.nameSuggestions.set(name, value);
  2061. if (value > this.mostCommonSuggestion) {
  2062. this.mostCommonSuggestion = value;
  2063. this.suggestedVariableName = name;
  2064. }
  2065. }
  2066. warnUnusedImports() {
  2067. const unused = Array.from(this.declarations)
  2068. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2069. .map(([name]) => name);
  2070. if (unused.length === 0)
  2071. return;
  2072. const importersSet = new Set();
  2073. for (const name of unused) {
  2074. for (const importer of this.declarations.get(name).module.importers) {
  2075. importersSet.add(importer);
  2076. }
  2077. }
  2078. const importersArray = [...importersSet];
  2079. this.options.onwarn({
  2080. code: 'UNUSED_EXTERNAL_IMPORT',
  2081. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  2082. names: unused,
  2083. source: this.id,
  2084. sources: importersArray
  2085. });
  2086. }
  2087. }
  2088. function getDefaultExportFromCjs (x) {
  2089. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2090. }
  2091. function getAugmentedNamespace(n) {
  2092. var f = n.default;
  2093. if (typeof f == "function") {
  2094. var a = function () {
  2095. return f.apply(this, arguments);
  2096. };
  2097. a.prototype = f.prototype;
  2098. } else a = {};
  2099. Object.defineProperty(a, '__esModule', {value: true});
  2100. Object.keys(n).forEach(function (k) {
  2101. var d = Object.getOwnPropertyDescriptor(n, k);
  2102. Object.defineProperty(a, k, d.get ? d : {
  2103. enumerable: true,
  2104. get: function () {
  2105. return n[k];
  2106. }
  2107. });
  2108. });
  2109. return a;
  2110. }
  2111. var picomatch$1 = {exports: {}};
  2112. var utils$3 = {};
  2113. const path$1 = require$$0;
  2114. const WIN_SLASH = '\\\\/';
  2115. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2116. /**
  2117. * Posix glob regex
  2118. */
  2119. const DOT_LITERAL = '\\.';
  2120. const PLUS_LITERAL = '\\+';
  2121. const QMARK_LITERAL = '\\?';
  2122. const SLASH_LITERAL = '\\/';
  2123. const ONE_CHAR = '(?=.)';
  2124. const QMARK = '[^/]';
  2125. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2126. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2127. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2128. const NO_DOT = `(?!${DOT_LITERAL})`;
  2129. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2130. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2131. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2132. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2133. const STAR = `${QMARK}*?`;
  2134. const POSIX_CHARS = {
  2135. DOT_LITERAL,
  2136. PLUS_LITERAL,
  2137. QMARK_LITERAL,
  2138. SLASH_LITERAL,
  2139. ONE_CHAR,
  2140. QMARK,
  2141. END_ANCHOR,
  2142. DOTS_SLASH,
  2143. NO_DOT,
  2144. NO_DOTS,
  2145. NO_DOT_SLASH,
  2146. NO_DOTS_SLASH,
  2147. QMARK_NO_DOT,
  2148. STAR,
  2149. START_ANCHOR
  2150. };
  2151. /**
  2152. * Windows glob regex
  2153. */
  2154. const WINDOWS_CHARS = {
  2155. ...POSIX_CHARS,
  2156. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2157. QMARK: WIN_NO_SLASH,
  2158. STAR: `${WIN_NO_SLASH}*?`,
  2159. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2160. NO_DOT: `(?!${DOT_LITERAL})`,
  2161. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2162. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2163. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2164. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2165. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2166. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2167. };
  2168. /**
  2169. * POSIX Bracket Regex
  2170. */
  2171. const POSIX_REGEX_SOURCE$1 = {
  2172. alnum: 'a-zA-Z0-9',
  2173. alpha: 'a-zA-Z',
  2174. ascii: '\\x00-\\x7F',
  2175. blank: ' \\t',
  2176. cntrl: '\\x00-\\x1F\\x7F',
  2177. digit: '0-9',
  2178. graph: '\\x21-\\x7E',
  2179. lower: 'a-z',
  2180. print: '\\x20-\\x7E ',
  2181. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2182. space: ' \\t\\r\\n\\v\\f',
  2183. upper: 'A-Z',
  2184. word: 'A-Za-z0-9_',
  2185. xdigit: 'A-Fa-f0-9'
  2186. };
  2187. var constants$2 = {
  2188. MAX_LENGTH: 1024 * 64,
  2189. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2190. // regular expressions
  2191. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2192. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2193. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2194. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2195. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2196. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2197. // Replace globs with equivalent patterns to reduce parsing time.
  2198. REPLACEMENTS: {
  2199. '***': '*',
  2200. '**/**': '**',
  2201. '**/**/**': '**'
  2202. },
  2203. // Digits
  2204. CHAR_0: 48, /* 0 */
  2205. CHAR_9: 57, /* 9 */
  2206. // Alphabet chars.
  2207. CHAR_UPPERCASE_A: 65, /* A */
  2208. CHAR_LOWERCASE_A: 97, /* a */
  2209. CHAR_UPPERCASE_Z: 90, /* Z */
  2210. CHAR_LOWERCASE_Z: 122, /* z */
  2211. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2212. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2213. CHAR_ASTERISK: 42, /* * */
  2214. // Non-alphabetic chars.
  2215. CHAR_AMPERSAND: 38, /* & */
  2216. CHAR_AT: 64, /* @ */
  2217. CHAR_BACKWARD_SLASH: 92, /* \ */
  2218. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2219. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2220. CHAR_COLON: 58, /* : */
  2221. CHAR_COMMA: 44, /* , */
  2222. CHAR_DOT: 46, /* . */
  2223. CHAR_DOUBLE_QUOTE: 34, /* " */
  2224. CHAR_EQUAL: 61, /* = */
  2225. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2226. CHAR_FORM_FEED: 12, /* \f */
  2227. CHAR_FORWARD_SLASH: 47, /* / */
  2228. CHAR_GRAVE_ACCENT: 96, /* ` */
  2229. CHAR_HASH: 35, /* # */
  2230. CHAR_HYPHEN_MINUS: 45, /* - */
  2231. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2232. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2233. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2234. CHAR_LINE_FEED: 10, /* \n */
  2235. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2236. CHAR_PERCENT: 37, /* % */
  2237. CHAR_PLUS: 43, /* + */
  2238. CHAR_QUESTION_MARK: 63, /* ? */
  2239. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2240. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2241. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2242. CHAR_SEMICOLON: 59, /* ; */
  2243. CHAR_SINGLE_QUOTE: 39, /* ' */
  2244. CHAR_SPACE: 32, /* */
  2245. CHAR_TAB: 9, /* \t */
  2246. CHAR_UNDERSCORE: 95, /* _ */
  2247. CHAR_VERTICAL_LINE: 124, /* | */
  2248. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2249. SEP: path$1.sep,
  2250. /**
  2251. * Create EXTGLOB_CHARS
  2252. */
  2253. extglobChars(chars) {
  2254. return {
  2255. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2256. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2257. '+': { type: 'plus', open: '(?:', close: ')+' },
  2258. '*': { type: 'star', open: '(?:', close: ')*' },
  2259. '@': { type: 'at', open: '(?:', close: ')' }
  2260. };
  2261. },
  2262. /**
  2263. * Create GLOB_CHARS
  2264. */
  2265. globChars(win32) {
  2266. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2267. }
  2268. };
  2269. (function (exports) {
  2270. const path = require$$0;
  2271. const win32 = process.platform === 'win32';
  2272. const {
  2273. REGEX_BACKSLASH,
  2274. REGEX_REMOVE_BACKSLASH,
  2275. REGEX_SPECIAL_CHARS,
  2276. REGEX_SPECIAL_CHARS_GLOBAL
  2277. } = constants$2;
  2278. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2279. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2280. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2281. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2282. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2283. exports.removeBackslashes = str => {
  2284. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2285. return match === '\\' ? '' : match;
  2286. });
  2287. };
  2288. exports.supportsLookbehinds = () => {
  2289. const segs = process.version.slice(1).split('.').map(Number);
  2290. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2291. return true;
  2292. }
  2293. return false;
  2294. };
  2295. exports.isWindows = options => {
  2296. if (options && typeof options.windows === 'boolean') {
  2297. return options.windows;
  2298. }
  2299. return win32 === true || path.sep === '\\';
  2300. };
  2301. exports.escapeLast = (input, char, lastIdx) => {
  2302. const idx = input.lastIndexOf(char, lastIdx);
  2303. if (idx === -1) return input;
  2304. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2305. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2306. };
  2307. exports.removePrefix = (input, state = {}) => {
  2308. let output = input;
  2309. if (output.startsWith('./')) {
  2310. output = output.slice(2);
  2311. state.prefix = './';
  2312. }
  2313. return output;
  2314. };
  2315. exports.wrapOutput = (input, state = {}, options = {}) => {
  2316. const prepend = options.contains ? '' : '^';
  2317. const append = options.contains ? '' : '$';
  2318. let output = `${prepend}(?:${input})${append}`;
  2319. if (state.negated === true) {
  2320. output = `(?:^(?!${output}).*$)`;
  2321. }
  2322. return output;
  2323. };
  2324. } (utils$3));
  2325. const utils$2 = utils$3;
  2326. const {
  2327. CHAR_ASTERISK, /* * */
  2328. CHAR_AT, /* @ */
  2329. CHAR_BACKWARD_SLASH, /* \ */
  2330. CHAR_COMMA, /* , */
  2331. CHAR_DOT, /* . */
  2332. CHAR_EXCLAMATION_MARK, /* ! */
  2333. CHAR_FORWARD_SLASH, /* / */
  2334. CHAR_LEFT_CURLY_BRACE, /* { */
  2335. CHAR_LEFT_PARENTHESES, /* ( */
  2336. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2337. CHAR_PLUS, /* + */
  2338. CHAR_QUESTION_MARK, /* ? */
  2339. CHAR_RIGHT_CURLY_BRACE, /* } */
  2340. CHAR_RIGHT_PARENTHESES, /* ) */
  2341. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2342. } = constants$2;
  2343. const isPathSeparator = code => {
  2344. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2345. };
  2346. const depth = token => {
  2347. if (token.isPrefix !== true) {
  2348. token.depth = token.isGlobstar ? Infinity : 1;
  2349. }
  2350. };
  2351. /**
  2352. * Quickly scans a glob pattern and returns an object with a handful of
  2353. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2354. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2355. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2356. *
  2357. * ```js
  2358. * const pm = require('picomatch');
  2359. * console.log(pm.scan('foo/bar/*.js'));
  2360. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2361. * ```
  2362. * @param {String} `str`
  2363. * @param {Object} `options`
  2364. * @return {Object} Returns an object with tokens and regex source string.
  2365. * @api public
  2366. */
  2367. const scan$1 = (input, options) => {
  2368. const opts = options || {};
  2369. const length = input.length - 1;
  2370. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2371. const slashes = [];
  2372. const tokens = [];
  2373. const parts = [];
  2374. let str = input;
  2375. let index = -1;
  2376. let start = 0;
  2377. let lastIndex = 0;
  2378. let isBrace = false;
  2379. let isBracket = false;
  2380. let isGlob = false;
  2381. let isExtglob = false;
  2382. let isGlobstar = false;
  2383. let braceEscaped = false;
  2384. let backslashes = false;
  2385. let negated = false;
  2386. let negatedExtglob = false;
  2387. let finished = false;
  2388. let braces = 0;
  2389. let prev;
  2390. let code;
  2391. let token = { value: '', depth: 0, isGlob: false };
  2392. const eos = () => index >= length;
  2393. const peek = () => str.charCodeAt(index + 1);
  2394. const advance = () => {
  2395. prev = code;
  2396. return str.charCodeAt(++index);
  2397. };
  2398. while (index < length) {
  2399. code = advance();
  2400. let next;
  2401. if (code === CHAR_BACKWARD_SLASH) {
  2402. backslashes = token.backslashes = true;
  2403. code = advance();
  2404. if (code === CHAR_LEFT_CURLY_BRACE) {
  2405. braceEscaped = true;
  2406. }
  2407. continue;
  2408. }
  2409. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2410. braces++;
  2411. while (eos() !== true && (code = advance())) {
  2412. if (code === CHAR_BACKWARD_SLASH) {
  2413. backslashes = token.backslashes = true;
  2414. advance();
  2415. continue;
  2416. }
  2417. if (code === CHAR_LEFT_CURLY_BRACE) {
  2418. braces++;
  2419. continue;
  2420. }
  2421. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2422. isBrace = token.isBrace = true;
  2423. isGlob = token.isGlob = true;
  2424. finished = true;
  2425. if (scanToEnd === true) {
  2426. continue;
  2427. }
  2428. break;
  2429. }
  2430. if (braceEscaped !== true && code === CHAR_COMMA) {
  2431. isBrace = token.isBrace = true;
  2432. isGlob = token.isGlob = true;
  2433. finished = true;
  2434. if (scanToEnd === true) {
  2435. continue;
  2436. }
  2437. break;
  2438. }
  2439. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2440. braces--;
  2441. if (braces === 0) {
  2442. braceEscaped = false;
  2443. isBrace = token.isBrace = true;
  2444. finished = true;
  2445. break;
  2446. }
  2447. }
  2448. }
  2449. if (scanToEnd === true) {
  2450. continue;
  2451. }
  2452. break;
  2453. }
  2454. if (code === CHAR_FORWARD_SLASH) {
  2455. slashes.push(index);
  2456. tokens.push(token);
  2457. token = { value: '', depth: 0, isGlob: false };
  2458. if (finished === true) continue;
  2459. if (prev === CHAR_DOT && index === (start + 1)) {
  2460. start += 2;
  2461. continue;
  2462. }
  2463. lastIndex = index + 1;
  2464. continue;
  2465. }
  2466. if (opts.noext !== true) {
  2467. const isExtglobChar = code === CHAR_PLUS
  2468. || code === CHAR_AT
  2469. || code === CHAR_ASTERISK
  2470. || code === CHAR_QUESTION_MARK
  2471. || code === CHAR_EXCLAMATION_MARK;
  2472. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2473. isGlob = token.isGlob = true;
  2474. isExtglob = token.isExtglob = true;
  2475. finished = true;
  2476. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2477. negatedExtglob = true;
  2478. }
  2479. if (scanToEnd === true) {
  2480. while (eos() !== true && (code = advance())) {
  2481. if (code === CHAR_BACKWARD_SLASH) {
  2482. backslashes = token.backslashes = true;
  2483. code = advance();
  2484. continue;
  2485. }
  2486. if (code === CHAR_RIGHT_PARENTHESES) {
  2487. isGlob = token.isGlob = true;
  2488. finished = true;
  2489. break;
  2490. }
  2491. }
  2492. continue;
  2493. }
  2494. break;
  2495. }
  2496. }
  2497. if (code === CHAR_ASTERISK) {
  2498. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2499. isGlob = token.isGlob = true;
  2500. finished = true;
  2501. if (scanToEnd === true) {
  2502. continue;
  2503. }
  2504. break;
  2505. }
  2506. if (code === CHAR_QUESTION_MARK) {
  2507. isGlob = token.isGlob = true;
  2508. finished = true;
  2509. if (scanToEnd === true) {
  2510. continue;
  2511. }
  2512. break;
  2513. }
  2514. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2515. while (eos() !== true && (next = advance())) {
  2516. if (next === CHAR_BACKWARD_SLASH) {
  2517. backslashes = token.backslashes = true;
  2518. advance();
  2519. continue;
  2520. }
  2521. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2522. isBracket = token.isBracket = true;
  2523. isGlob = token.isGlob = true;
  2524. finished = true;
  2525. break;
  2526. }
  2527. }
  2528. if (scanToEnd === true) {
  2529. continue;
  2530. }
  2531. break;
  2532. }
  2533. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2534. negated = token.negated = true;
  2535. start++;
  2536. continue;
  2537. }
  2538. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2539. isGlob = token.isGlob = true;
  2540. if (scanToEnd === true) {
  2541. while (eos() !== true && (code = advance())) {
  2542. if (code === CHAR_LEFT_PARENTHESES) {
  2543. backslashes = token.backslashes = true;
  2544. code = advance();
  2545. continue;
  2546. }
  2547. if (code === CHAR_RIGHT_PARENTHESES) {
  2548. finished = true;
  2549. break;
  2550. }
  2551. }
  2552. continue;
  2553. }
  2554. break;
  2555. }
  2556. if (isGlob === true) {
  2557. finished = true;
  2558. if (scanToEnd === true) {
  2559. continue;
  2560. }
  2561. break;
  2562. }
  2563. }
  2564. if (opts.noext === true) {
  2565. isExtglob = false;
  2566. isGlob = false;
  2567. }
  2568. let base = str;
  2569. let prefix = '';
  2570. let glob = '';
  2571. if (start > 0) {
  2572. prefix = str.slice(0, start);
  2573. str = str.slice(start);
  2574. lastIndex -= start;
  2575. }
  2576. if (base && isGlob === true && lastIndex > 0) {
  2577. base = str.slice(0, lastIndex);
  2578. glob = str.slice(lastIndex);
  2579. } else if (isGlob === true) {
  2580. base = '';
  2581. glob = str;
  2582. } else {
  2583. base = str;
  2584. }
  2585. if (base && base !== '' && base !== '/' && base !== str) {
  2586. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2587. base = base.slice(0, -1);
  2588. }
  2589. }
  2590. if (opts.unescape === true) {
  2591. if (glob) glob = utils$2.removeBackslashes(glob);
  2592. if (base && backslashes === true) {
  2593. base = utils$2.removeBackslashes(base);
  2594. }
  2595. }
  2596. const state = {
  2597. prefix,
  2598. input,
  2599. start,
  2600. base,
  2601. glob,
  2602. isBrace,
  2603. isBracket,
  2604. isGlob,
  2605. isExtglob,
  2606. isGlobstar,
  2607. negated,
  2608. negatedExtglob
  2609. };
  2610. if (opts.tokens === true) {
  2611. state.maxDepth = 0;
  2612. if (!isPathSeparator(code)) {
  2613. tokens.push(token);
  2614. }
  2615. state.tokens = tokens;
  2616. }
  2617. if (opts.parts === true || opts.tokens === true) {
  2618. let prevIndex;
  2619. for (let idx = 0; idx < slashes.length; idx++) {
  2620. const n = prevIndex ? prevIndex + 1 : start;
  2621. const i = slashes[idx];
  2622. const value = input.slice(n, i);
  2623. if (opts.tokens) {
  2624. if (idx === 0 && start !== 0) {
  2625. tokens[idx].isPrefix = true;
  2626. tokens[idx].value = prefix;
  2627. } else {
  2628. tokens[idx].value = value;
  2629. }
  2630. depth(tokens[idx]);
  2631. state.maxDepth += tokens[idx].depth;
  2632. }
  2633. if (idx !== 0 || value !== '') {
  2634. parts.push(value);
  2635. }
  2636. prevIndex = i;
  2637. }
  2638. if (prevIndex && prevIndex + 1 < input.length) {
  2639. const value = input.slice(prevIndex + 1);
  2640. parts.push(value);
  2641. if (opts.tokens) {
  2642. tokens[tokens.length - 1].value = value;
  2643. depth(tokens[tokens.length - 1]);
  2644. state.maxDepth += tokens[tokens.length - 1].depth;
  2645. }
  2646. }
  2647. state.slashes = slashes;
  2648. state.parts = parts;
  2649. }
  2650. return state;
  2651. };
  2652. var scan_1 = scan$1;
  2653. const constants$1 = constants$2;
  2654. const utils$1 = utils$3;
  2655. /**
  2656. * Constants
  2657. */
  2658. const {
  2659. MAX_LENGTH,
  2660. POSIX_REGEX_SOURCE,
  2661. REGEX_NON_SPECIAL_CHARS,
  2662. REGEX_SPECIAL_CHARS_BACKREF,
  2663. REPLACEMENTS
  2664. } = constants$1;
  2665. /**
  2666. * Helpers
  2667. */
  2668. const expandRange = (args, options) => {
  2669. if (typeof options.expandRange === 'function') {
  2670. return options.expandRange(...args, options);
  2671. }
  2672. args.sort();
  2673. const value = `[${args.join('-')}]`;
  2674. return value;
  2675. };
  2676. /**
  2677. * Create the message for a syntax error
  2678. */
  2679. const syntaxError = (type, char) => {
  2680. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2681. };
  2682. /**
  2683. * Parse the given input string.
  2684. * @param {String} input
  2685. * @param {Object} options
  2686. * @return {Object}
  2687. */
  2688. const parse$1 = (input, options) => {
  2689. if (typeof input !== 'string') {
  2690. throw new TypeError('Expected a string');
  2691. }
  2692. input = REPLACEMENTS[input] || input;
  2693. const opts = { ...options };
  2694. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2695. let len = input.length;
  2696. if (len > max) {
  2697. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2698. }
  2699. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2700. const tokens = [bos];
  2701. const capture = opts.capture ? '' : '?:';
  2702. const win32 = utils$1.isWindows(options);
  2703. // create constants based on platform, for windows or posix
  2704. const PLATFORM_CHARS = constants$1.globChars(win32);
  2705. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  2706. const {
  2707. DOT_LITERAL,
  2708. PLUS_LITERAL,
  2709. SLASH_LITERAL,
  2710. ONE_CHAR,
  2711. DOTS_SLASH,
  2712. NO_DOT,
  2713. NO_DOT_SLASH,
  2714. NO_DOTS_SLASH,
  2715. QMARK,
  2716. QMARK_NO_DOT,
  2717. STAR,
  2718. START_ANCHOR
  2719. } = PLATFORM_CHARS;
  2720. const globstar = opts => {
  2721. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2722. };
  2723. const nodot = opts.dot ? '' : NO_DOT;
  2724. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2725. let star = opts.bash === true ? globstar(opts) : STAR;
  2726. if (opts.capture) {
  2727. star = `(${star})`;
  2728. }
  2729. // minimatch options support
  2730. if (typeof opts.noext === 'boolean') {
  2731. opts.noextglob = opts.noext;
  2732. }
  2733. const state = {
  2734. input,
  2735. index: -1,
  2736. start: 0,
  2737. dot: opts.dot === true,
  2738. consumed: '',
  2739. output: '',
  2740. prefix: '',
  2741. backtrack: false,
  2742. negated: false,
  2743. brackets: 0,
  2744. braces: 0,
  2745. parens: 0,
  2746. quotes: 0,
  2747. globstar: false,
  2748. tokens
  2749. };
  2750. input = utils$1.removePrefix(input, state);
  2751. len = input.length;
  2752. const extglobs = [];
  2753. const braces = [];
  2754. const stack = [];
  2755. let prev = bos;
  2756. let value;
  2757. /**
  2758. * Tokenizing helpers
  2759. */
  2760. const eos = () => state.index === len - 1;
  2761. const peek = state.peek = (n = 1) => input[state.index + n];
  2762. const advance = state.advance = () => input[++state.index] || '';
  2763. const remaining = () => input.slice(state.index + 1);
  2764. const consume = (value = '', num = 0) => {
  2765. state.consumed += value;
  2766. state.index += num;
  2767. };
  2768. const append = token => {
  2769. state.output += token.output != null ? token.output : token.value;
  2770. consume(token.value);
  2771. };
  2772. const negate = () => {
  2773. let count = 1;
  2774. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2775. advance();
  2776. state.start++;
  2777. count++;
  2778. }
  2779. if (count % 2 === 0) {
  2780. return false;
  2781. }
  2782. state.negated = true;
  2783. state.start++;
  2784. return true;
  2785. };
  2786. const increment = type => {
  2787. state[type]++;
  2788. stack.push(type);
  2789. };
  2790. const decrement = type => {
  2791. state[type]--;
  2792. stack.pop();
  2793. };
  2794. /**
  2795. * Push tokens onto the tokens array. This helper speeds up
  2796. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2797. * and 2) helping us avoid creating extra tokens when consecutive
  2798. * characters are plain text. This improves performance and simplifies
  2799. * lookbehinds.
  2800. */
  2801. const push = tok => {
  2802. if (prev.type === 'globstar') {
  2803. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2804. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2805. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2806. state.output = state.output.slice(0, -prev.output.length);
  2807. prev.type = 'star';
  2808. prev.value = '*';
  2809. prev.output = star;
  2810. state.output += prev.output;
  2811. }
  2812. }
  2813. if (extglobs.length && tok.type !== 'paren') {
  2814. extglobs[extglobs.length - 1].inner += tok.value;
  2815. }
  2816. if (tok.value || tok.output) append(tok);
  2817. if (prev && prev.type === 'text' && tok.type === 'text') {
  2818. prev.value += tok.value;
  2819. prev.output = (prev.output || '') + tok.value;
  2820. return;
  2821. }
  2822. tok.prev = prev;
  2823. tokens.push(tok);
  2824. prev = tok;
  2825. };
  2826. const extglobOpen = (type, value) => {
  2827. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2828. token.prev = prev;
  2829. token.parens = state.parens;
  2830. token.output = state.output;
  2831. const output = (opts.capture ? '(' : '') + token.open;
  2832. increment('parens');
  2833. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2834. push({ type: 'paren', extglob: true, value: advance(), output });
  2835. extglobs.push(token);
  2836. };
  2837. const extglobClose = token => {
  2838. let output = token.close + (opts.capture ? ')' : '');
  2839. let rest;
  2840. if (token.type === 'negate') {
  2841. let extglobStar = star;
  2842. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2843. extglobStar = globstar(opts);
  2844. }
  2845. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2846. output = token.close = `)$))${extglobStar}`;
  2847. }
  2848. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2849. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2850. // In this case, we need to parse the string and use it in the output of the original pattern.
  2851. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2852. //
  2853. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2854. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2855. output = token.close = `)${expression})${extglobStar})`;
  2856. }
  2857. if (token.prev.type === 'bos') {
  2858. state.negatedExtglob = true;
  2859. }
  2860. }
  2861. push({ type: 'paren', extglob: true, value, output });
  2862. decrement('parens');
  2863. };
  2864. /**
  2865. * Fast paths
  2866. */
  2867. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2868. let backslashes = false;
  2869. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2870. if (first === '\\') {
  2871. backslashes = true;
  2872. return m;
  2873. }
  2874. if (first === '?') {
  2875. if (esc) {
  2876. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2877. }
  2878. if (index === 0) {
  2879. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2880. }
  2881. return QMARK.repeat(chars.length);
  2882. }
  2883. if (first === '.') {
  2884. return DOT_LITERAL.repeat(chars.length);
  2885. }
  2886. if (first === '*') {
  2887. if (esc) {
  2888. return esc + first + (rest ? star : '');
  2889. }
  2890. return star;
  2891. }
  2892. return esc ? m : `\\${m}`;
  2893. });
  2894. if (backslashes === true) {
  2895. if (opts.unescape === true) {
  2896. output = output.replace(/\\/g, '');
  2897. } else {
  2898. output = output.replace(/\\+/g, m => {
  2899. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2900. });
  2901. }
  2902. }
  2903. if (output === input && opts.contains === true) {
  2904. state.output = input;
  2905. return state;
  2906. }
  2907. state.output = utils$1.wrapOutput(output, state, options);
  2908. return state;
  2909. }
  2910. /**
  2911. * Tokenize input until we reach end-of-string
  2912. */
  2913. while (!eos()) {
  2914. value = advance();
  2915. if (value === '\u0000') {
  2916. continue;
  2917. }
  2918. /**
  2919. * Escaped characters
  2920. */
  2921. if (value === '\\') {
  2922. const next = peek();
  2923. if (next === '/' && opts.bash !== true) {
  2924. continue;
  2925. }
  2926. if (next === '.' || next === ';') {
  2927. continue;
  2928. }
  2929. if (!next) {
  2930. value += '\\';
  2931. push({ type: 'text', value });
  2932. continue;
  2933. }
  2934. // collapse slashes to reduce potential for exploits
  2935. const match = /^\\+/.exec(remaining());
  2936. let slashes = 0;
  2937. if (match && match[0].length > 2) {
  2938. slashes = match[0].length;
  2939. state.index += slashes;
  2940. if (slashes % 2 !== 0) {
  2941. value += '\\';
  2942. }
  2943. }
  2944. if (opts.unescape === true) {
  2945. value = advance();
  2946. } else {
  2947. value += advance();
  2948. }
  2949. if (state.brackets === 0) {
  2950. push({ type: 'text', value });
  2951. continue;
  2952. }
  2953. }
  2954. /**
  2955. * If we're inside a regex character class, continue
  2956. * until we reach the closing bracket.
  2957. */
  2958. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2959. if (opts.posix !== false && value === ':') {
  2960. const inner = prev.value.slice(1);
  2961. if (inner.includes('[')) {
  2962. prev.posix = true;
  2963. if (inner.includes(':')) {
  2964. const idx = prev.value.lastIndexOf('[');
  2965. const pre = prev.value.slice(0, idx);
  2966. const rest = prev.value.slice(idx + 2);
  2967. const posix = POSIX_REGEX_SOURCE[rest];
  2968. if (posix) {
  2969. prev.value = pre + posix;
  2970. state.backtrack = true;
  2971. advance();
  2972. if (!bos.output && tokens.indexOf(prev) === 1) {
  2973. bos.output = ONE_CHAR;
  2974. }
  2975. continue;
  2976. }
  2977. }
  2978. }
  2979. }
  2980. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2981. value = `\\${value}`;
  2982. }
  2983. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2984. value = `\\${value}`;
  2985. }
  2986. if (opts.posix === true && value === '!' && prev.value === '[') {
  2987. value = '^';
  2988. }
  2989. prev.value += value;
  2990. append({ value });
  2991. continue;
  2992. }
  2993. /**
  2994. * If we're inside a quoted string, continue
  2995. * until we reach the closing double quote.
  2996. */
  2997. if (state.quotes === 1 && value !== '"') {
  2998. value = utils$1.escapeRegex(value);
  2999. prev.value += value;
  3000. append({ value });
  3001. continue;
  3002. }
  3003. /**
  3004. * Double quotes
  3005. */
  3006. if (value === '"') {
  3007. state.quotes = state.quotes === 1 ? 0 : 1;
  3008. if (opts.keepQuotes === true) {
  3009. push({ type: 'text', value });
  3010. }
  3011. continue;
  3012. }
  3013. /**
  3014. * Parentheses
  3015. */
  3016. if (value === '(') {
  3017. increment('parens');
  3018. push({ type: 'paren', value });
  3019. continue;
  3020. }
  3021. if (value === ')') {
  3022. if (state.parens === 0 && opts.strictBrackets === true) {
  3023. throw new SyntaxError(syntaxError('opening', '('));
  3024. }
  3025. const extglob = extglobs[extglobs.length - 1];
  3026. if (extglob && state.parens === extglob.parens + 1) {
  3027. extglobClose(extglobs.pop());
  3028. continue;
  3029. }
  3030. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3031. decrement('parens');
  3032. continue;
  3033. }
  3034. /**
  3035. * Square brackets
  3036. */
  3037. if (value === '[') {
  3038. if (opts.nobracket === true || !remaining().includes(']')) {
  3039. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3040. throw new SyntaxError(syntaxError('closing', ']'));
  3041. }
  3042. value = `\\${value}`;
  3043. } else {
  3044. increment('brackets');
  3045. }
  3046. push({ type: 'bracket', value });
  3047. continue;
  3048. }
  3049. if (value === ']') {
  3050. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3051. push({ type: 'text', value, output: `\\${value}` });
  3052. continue;
  3053. }
  3054. if (state.brackets === 0) {
  3055. if (opts.strictBrackets === true) {
  3056. throw new SyntaxError(syntaxError('opening', '['));
  3057. }
  3058. push({ type: 'text', value, output: `\\${value}` });
  3059. continue;
  3060. }
  3061. decrement('brackets');
  3062. const prevValue = prev.value.slice(1);
  3063. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3064. value = `/${value}`;
  3065. }
  3066. prev.value += value;
  3067. append({ value });
  3068. // when literal brackets are explicitly disabled
  3069. // assume we should match with a regex character class
  3070. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3071. continue;
  3072. }
  3073. const escaped = utils$1.escapeRegex(prev.value);
  3074. state.output = state.output.slice(0, -prev.value.length);
  3075. // when literal brackets are explicitly enabled
  3076. // assume we should escape the brackets to match literal characters
  3077. if (opts.literalBrackets === true) {
  3078. state.output += escaped;
  3079. prev.value = escaped;
  3080. continue;
  3081. }
  3082. // when the user specifies nothing, try to match both
  3083. prev.value = `(${capture}${escaped}|${prev.value})`;
  3084. state.output += prev.value;
  3085. continue;
  3086. }
  3087. /**
  3088. * Braces
  3089. */
  3090. if (value === '{' && opts.nobrace !== true) {
  3091. increment('braces');
  3092. const open = {
  3093. type: 'brace',
  3094. value,
  3095. output: '(',
  3096. outputIndex: state.output.length,
  3097. tokensIndex: state.tokens.length
  3098. };
  3099. braces.push(open);
  3100. push(open);
  3101. continue;
  3102. }
  3103. if (value === '}') {
  3104. const brace = braces[braces.length - 1];
  3105. if (opts.nobrace === true || !brace) {
  3106. push({ type: 'text', value, output: value });
  3107. continue;
  3108. }
  3109. let output = ')';
  3110. if (brace.dots === true) {
  3111. const arr = tokens.slice();
  3112. const range = [];
  3113. for (let i = arr.length - 1; i >= 0; i--) {
  3114. tokens.pop();
  3115. if (arr[i].type === 'brace') {
  3116. break;
  3117. }
  3118. if (arr[i].type !== 'dots') {
  3119. range.unshift(arr[i].value);
  3120. }
  3121. }
  3122. output = expandRange(range, opts);
  3123. state.backtrack = true;
  3124. }
  3125. if (brace.comma !== true && brace.dots !== true) {
  3126. const out = state.output.slice(0, brace.outputIndex);
  3127. const toks = state.tokens.slice(brace.tokensIndex);
  3128. brace.value = brace.output = '\\{';
  3129. value = output = '\\}';
  3130. state.output = out;
  3131. for (const t of toks) {
  3132. state.output += (t.output || t.value);
  3133. }
  3134. }
  3135. push({ type: 'brace', value, output });
  3136. decrement('braces');
  3137. braces.pop();
  3138. continue;
  3139. }
  3140. /**
  3141. * Pipes
  3142. */
  3143. if (value === '|') {
  3144. if (extglobs.length > 0) {
  3145. extglobs[extglobs.length - 1].conditions++;
  3146. }
  3147. push({ type: 'text', value });
  3148. continue;
  3149. }
  3150. /**
  3151. * Commas
  3152. */
  3153. if (value === ',') {
  3154. let output = value;
  3155. const brace = braces[braces.length - 1];
  3156. if (brace && stack[stack.length - 1] === 'braces') {
  3157. brace.comma = true;
  3158. output = '|';
  3159. }
  3160. push({ type: 'comma', value, output });
  3161. continue;
  3162. }
  3163. /**
  3164. * Slashes
  3165. */
  3166. if (value === '/') {
  3167. // if the beginning of the glob is "./", advance the start
  3168. // to the current index, and don't add the "./" characters
  3169. // to the state. This greatly simplifies lookbehinds when
  3170. // checking for BOS characters like "!" and "." (not "./")
  3171. if (prev.type === 'dot' && state.index === state.start + 1) {
  3172. state.start = state.index + 1;
  3173. state.consumed = '';
  3174. state.output = '';
  3175. tokens.pop();
  3176. prev = bos; // reset "prev" to the first token
  3177. continue;
  3178. }
  3179. push({ type: 'slash', value, output: SLASH_LITERAL });
  3180. continue;
  3181. }
  3182. /**
  3183. * Dots
  3184. */
  3185. if (value === '.') {
  3186. if (state.braces > 0 && prev.type === 'dot') {
  3187. if (prev.value === '.') prev.output = DOT_LITERAL;
  3188. const brace = braces[braces.length - 1];
  3189. prev.type = 'dots';
  3190. prev.output += value;
  3191. prev.value += value;
  3192. brace.dots = true;
  3193. continue;
  3194. }
  3195. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3196. push({ type: 'text', value, output: DOT_LITERAL });
  3197. continue;
  3198. }
  3199. push({ type: 'dot', value, output: DOT_LITERAL });
  3200. continue;
  3201. }
  3202. /**
  3203. * Question marks
  3204. */
  3205. if (value === '?') {
  3206. const isGroup = prev && prev.value === '(';
  3207. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3208. extglobOpen('qmark', value);
  3209. continue;
  3210. }
  3211. if (prev && prev.type === 'paren') {
  3212. const next = peek();
  3213. let output = value;
  3214. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3215. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3216. }
  3217. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3218. output = `\\${value}`;
  3219. }
  3220. push({ type: 'text', value, output });
  3221. continue;
  3222. }
  3223. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3224. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3225. continue;
  3226. }
  3227. push({ type: 'qmark', value, output: QMARK });
  3228. continue;
  3229. }
  3230. /**
  3231. * Exclamation
  3232. */
  3233. if (value === '!') {
  3234. if (opts.noextglob !== true && peek() === '(') {
  3235. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3236. extglobOpen('negate', value);
  3237. continue;
  3238. }
  3239. }
  3240. if (opts.nonegate !== true && state.index === 0) {
  3241. negate();
  3242. continue;
  3243. }
  3244. }
  3245. /**
  3246. * Plus
  3247. */
  3248. if (value === '+') {
  3249. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3250. extglobOpen('plus', value);
  3251. continue;
  3252. }
  3253. if ((prev && prev.value === '(') || opts.regex === false) {
  3254. push({ type: 'plus', value, output: PLUS_LITERAL });
  3255. continue;
  3256. }
  3257. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3258. push({ type: 'plus', value });
  3259. continue;
  3260. }
  3261. push({ type: 'plus', value: PLUS_LITERAL });
  3262. continue;
  3263. }
  3264. /**
  3265. * Plain text
  3266. */
  3267. if (value === '@') {
  3268. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3269. push({ type: 'at', extglob: true, value, output: '' });
  3270. continue;
  3271. }
  3272. push({ type: 'text', value });
  3273. continue;
  3274. }
  3275. /**
  3276. * Plain text
  3277. */
  3278. if (value !== '*') {
  3279. if (value === '$' || value === '^') {
  3280. value = `\\${value}`;
  3281. }
  3282. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3283. if (match) {
  3284. value += match[0];
  3285. state.index += match[0].length;
  3286. }
  3287. push({ type: 'text', value });
  3288. continue;
  3289. }
  3290. /**
  3291. * Stars
  3292. */
  3293. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3294. prev.type = 'star';
  3295. prev.star = true;
  3296. prev.value += value;
  3297. prev.output = star;
  3298. state.backtrack = true;
  3299. state.globstar = true;
  3300. consume(value);
  3301. continue;
  3302. }
  3303. let rest = remaining();
  3304. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3305. extglobOpen('star', value);
  3306. continue;
  3307. }
  3308. if (prev.type === 'star') {
  3309. if (opts.noglobstar === true) {
  3310. consume(value);
  3311. continue;
  3312. }
  3313. const prior = prev.prev;
  3314. const before = prior.prev;
  3315. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3316. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3317. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3318. push({ type: 'star', value, output: '' });
  3319. continue;
  3320. }
  3321. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3322. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3323. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3324. push({ type: 'star', value, output: '' });
  3325. continue;
  3326. }
  3327. // strip consecutive `/**/`
  3328. while (rest.slice(0, 3) === '/**') {
  3329. const after = input[state.index + 4];
  3330. if (after && after !== '/') {
  3331. break;
  3332. }
  3333. rest = rest.slice(3);
  3334. consume('/**', 3);
  3335. }
  3336. if (prior.type === 'bos' && eos()) {
  3337. prev.type = 'globstar';
  3338. prev.value += value;
  3339. prev.output = globstar(opts);
  3340. state.output = prev.output;
  3341. state.globstar = true;
  3342. consume(value);
  3343. continue;
  3344. }
  3345. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3346. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3347. prior.output = `(?:${prior.output}`;
  3348. prev.type = 'globstar';
  3349. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3350. prev.value += value;
  3351. state.globstar = true;
  3352. state.output += prior.output + prev.output;
  3353. consume(value);
  3354. continue;
  3355. }
  3356. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3357. const end = rest[1] !== void 0 ? '|$' : '';
  3358. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3359. prior.output = `(?:${prior.output}`;
  3360. prev.type = 'globstar';
  3361. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3362. prev.value += value;
  3363. state.output += prior.output + prev.output;
  3364. state.globstar = true;
  3365. consume(value + advance());
  3366. push({ type: 'slash', value: '/', output: '' });
  3367. continue;
  3368. }
  3369. if (prior.type === 'bos' && rest[0] === '/') {
  3370. prev.type = 'globstar';
  3371. prev.value += value;
  3372. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3373. state.output = prev.output;
  3374. state.globstar = true;
  3375. consume(value + advance());
  3376. push({ type: 'slash', value: '/', output: '' });
  3377. continue;
  3378. }
  3379. // remove single star from output
  3380. state.output = state.output.slice(0, -prev.output.length);
  3381. // reset previous token to globstar
  3382. prev.type = 'globstar';
  3383. prev.output = globstar(opts);
  3384. prev.value += value;
  3385. // reset output with globstar
  3386. state.output += prev.output;
  3387. state.globstar = true;
  3388. consume(value);
  3389. continue;
  3390. }
  3391. const token = { type: 'star', value, output: star };
  3392. if (opts.bash === true) {
  3393. token.output = '.*?';
  3394. if (prev.type === 'bos' || prev.type === 'slash') {
  3395. token.output = nodot + token.output;
  3396. }
  3397. push(token);
  3398. continue;
  3399. }
  3400. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3401. token.output = value;
  3402. push(token);
  3403. continue;
  3404. }
  3405. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3406. if (prev.type === 'dot') {
  3407. state.output += NO_DOT_SLASH;
  3408. prev.output += NO_DOT_SLASH;
  3409. } else if (opts.dot === true) {
  3410. state.output += NO_DOTS_SLASH;
  3411. prev.output += NO_DOTS_SLASH;
  3412. } else {
  3413. state.output += nodot;
  3414. prev.output += nodot;
  3415. }
  3416. if (peek() !== '*') {
  3417. state.output += ONE_CHAR;
  3418. prev.output += ONE_CHAR;
  3419. }
  3420. }
  3421. push(token);
  3422. }
  3423. while (state.brackets > 0) {
  3424. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3425. state.output = utils$1.escapeLast(state.output, '[');
  3426. decrement('brackets');
  3427. }
  3428. while (state.parens > 0) {
  3429. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3430. state.output = utils$1.escapeLast(state.output, '(');
  3431. decrement('parens');
  3432. }
  3433. while (state.braces > 0) {
  3434. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3435. state.output = utils$1.escapeLast(state.output, '{');
  3436. decrement('braces');
  3437. }
  3438. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3439. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3440. }
  3441. // rebuild the output if we had to backtrack at any point
  3442. if (state.backtrack === true) {
  3443. state.output = '';
  3444. for (const token of state.tokens) {
  3445. state.output += token.output != null ? token.output : token.value;
  3446. if (token.suffix) {
  3447. state.output += token.suffix;
  3448. }
  3449. }
  3450. }
  3451. return state;
  3452. };
  3453. /**
  3454. * Fast paths for creating regular expressions for common glob patterns.
  3455. * This can significantly speed up processing and has very little downside
  3456. * impact when none of the fast paths match.
  3457. */
  3458. parse$1.fastpaths = (input, options) => {
  3459. const opts = { ...options };
  3460. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3461. const len = input.length;
  3462. if (len > max) {
  3463. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3464. }
  3465. input = REPLACEMENTS[input] || input;
  3466. const win32 = utils$1.isWindows(options);
  3467. // create constants based on platform, for windows or posix
  3468. const {
  3469. DOT_LITERAL,
  3470. SLASH_LITERAL,
  3471. ONE_CHAR,
  3472. DOTS_SLASH,
  3473. NO_DOT,
  3474. NO_DOTS,
  3475. NO_DOTS_SLASH,
  3476. STAR,
  3477. START_ANCHOR
  3478. } = constants$1.globChars(win32);
  3479. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3480. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3481. const capture = opts.capture ? '' : '?:';
  3482. const state = { negated: false, prefix: '' };
  3483. let star = opts.bash === true ? '.*?' : STAR;
  3484. if (opts.capture) {
  3485. star = `(${star})`;
  3486. }
  3487. const globstar = opts => {
  3488. if (opts.noglobstar === true) return star;
  3489. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3490. };
  3491. const create = str => {
  3492. switch (str) {
  3493. case '*':
  3494. return `${nodot}${ONE_CHAR}${star}`;
  3495. case '.*':
  3496. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3497. case '*.*':
  3498. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3499. case '*/*':
  3500. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3501. case '**':
  3502. return nodot + globstar(opts);
  3503. case '**/*':
  3504. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3505. case '**/*.*':
  3506. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3507. case '**/.*':
  3508. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3509. default: {
  3510. const match = /^(.*?)\.(\w+)$/.exec(str);
  3511. if (!match) return;
  3512. const source = create(match[1]);
  3513. if (!source) return;
  3514. return source + DOT_LITERAL + match[2];
  3515. }
  3516. }
  3517. };
  3518. const output = utils$1.removePrefix(input, state);
  3519. let source = create(output);
  3520. if (source && opts.strictSlashes !== true) {
  3521. source += `${SLASH_LITERAL}?`;
  3522. }
  3523. return source;
  3524. };
  3525. var parse_1 = parse$1;
  3526. const path = require$$0;
  3527. const scan = scan_1;
  3528. const parse = parse_1;
  3529. const utils = utils$3;
  3530. const constants = constants$2;
  3531. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3532. /**
  3533. * Creates a matcher function from one or more glob patterns. The
  3534. * returned function takes a string to match as its first argument,
  3535. * and returns true if the string is a match. The returned matcher
  3536. * function also takes a boolean as the second argument that, when true,
  3537. * returns an object with additional information.
  3538. *
  3539. * ```js
  3540. * const picomatch = require('picomatch');
  3541. * // picomatch(glob[, options]);
  3542. *
  3543. * const isMatch = picomatch('*.!(*a)');
  3544. * console.log(isMatch('a.a')); //=> false
  3545. * console.log(isMatch('a.b')); //=> true
  3546. * ```
  3547. * @name picomatch
  3548. * @param {String|Array} `globs` One or more glob patterns.
  3549. * @param {Object=} `options`
  3550. * @return {Function=} Returns a matcher function.
  3551. * @api public
  3552. */
  3553. const picomatch = (glob, options, returnState = false) => {
  3554. if (Array.isArray(glob)) {
  3555. const fns = glob.map(input => picomatch(input, options, returnState));
  3556. const arrayMatcher = str => {
  3557. for (const isMatch of fns) {
  3558. const state = isMatch(str);
  3559. if (state) return state;
  3560. }
  3561. return false;
  3562. };
  3563. return arrayMatcher;
  3564. }
  3565. const isState = isObject(glob) && glob.tokens && glob.input;
  3566. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3567. throw new TypeError('Expected pattern to be a non-empty string');
  3568. }
  3569. const opts = options || {};
  3570. const posix = utils.isWindows(options);
  3571. const regex = isState
  3572. ? picomatch.compileRe(glob, options)
  3573. : picomatch.makeRe(glob, options, false, true);
  3574. const state = regex.state;
  3575. delete regex.state;
  3576. let isIgnored = () => false;
  3577. if (opts.ignore) {
  3578. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3579. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  3580. }
  3581. const matcher = (input, returnObject = false) => {
  3582. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  3583. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3584. if (typeof opts.onResult === 'function') {
  3585. opts.onResult(result);
  3586. }
  3587. if (isMatch === false) {
  3588. result.isMatch = false;
  3589. return returnObject ? result : false;
  3590. }
  3591. if (isIgnored(input)) {
  3592. if (typeof opts.onIgnore === 'function') {
  3593. opts.onIgnore(result);
  3594. }
  3595. result.isMatch = false;
  3596. return returnObject ? result : false;
  3597. }
  3598. if (typeof opts.onMatch === 'function') {
  3599. opts.onMatch(result);
  3600. }
  3601. return returnObject ? result : true;
  3602. };
  3603. if (returnState) {
  3604. matcher.state = state;
  3605. }
  3606. return matcher;
  3607. };
  3608. /**
  3609. * Test `input` with the given `regex`. This is used by the main
  3610. * `picomatch()` function to test the input string.
  3611. *
  3612. * ```js
  3613. * const picomatch = require('picomatch');
  3614. * // picomatch.test(input, regex[, options]);
  3615. *
  3616. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3617. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3618. * ```
  3619. * @param {String} `input` String to test.
  3620. * @param {RegExp} `regex`
  3621. * @return {Object} Returns an object with matching info.
  3622. * @api public
  3623. */
  3624. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  3625. if (typeof input !== 'string') {
  3626. throw new TypeError('Expected input to be a string');
  3627. }
  3628. if (input === '') {
  3629. return { isMatch: false, output: '' };
  3630. }
  3631. const opts = options || {};
  3632. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3633. let match = input === glob;
  3634. let output = (match && format) ? format(input) : input;
  3635. if (match === false) {
  3636. output = format ? format(input) : input;
  3637. match = output === glob;
  3638. }
  3639. if (match === false || opts.capture === true) {
  3640. if (opts.matchBase === true || opts.basename === true) {
  3641. match = picomatch.matchBase(input, regex, options, posix);
  3642. } else {
  3643. match = regex.exec(output);
  3644. }
  3645. }
  3646. return { isMatch: Boolean(match), match, output };
  3647. };
  3648. /**
  3649. * Match the basename of a filepath.
  3650. *
  3651. * ```js
  3652. * const picomatch = require('picomatch');
  3653. * // picomatch.matchBase(input, glob[, options]);
  3654. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3655. * ```
  3656. * @param {String} `input` String to test.
  3657. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3658. * @return {Boolean}
  3659. * @api public
  3660. */
  3661. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3662. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  3663. return regex.test(path.basename(input));
  3664. };
  3665. /**
  3666. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3667. *
  3668. * ```js
  3669. * const picomatch = require('picomatch');
  3670. * // picomatch.isMatch(string, patterns[, options]);
  3671. *
  3672. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3673. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3674. * ```
  3675. * @param {String|Array} str The string to test.
  3676. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3677. * @param {Object} [options] See available [options](#options).
  3678. * @return {Boolean} Returns true if any patterns match `str`
  3679. * @api public
  3680. */
  3681. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3682. /**
  3683. * Parse a glob pattern to create the source string for a regular
  3684. * expression.
  3685. *
  3686. * ```js
  3687. * const picomatch = require('picomatch');
  3688. * const result = picomatch.parse(pattern[, options]);
  3689. * ```
  3690. * @param {String} `pattern`
  3691. * @param {Object} `options`
  3692. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3693. * @api public
  3694. */
  3695. picomatch.parse = (pattern, options) => {
  3696. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  3697. return parse(pattern, { ...options, fastpaths: false });
  3698. };
  3699. /**
  3700. * Scan a glob pattern to separate the pattern into segments.
  3701. *
  3702. * ```js
  3703. * const picomatch = require('picomatch');
  3704. * // picomatch.scan(input[, options]);
  3705. *
  3706. * const result = picomatch.scan('!./foo/*.js');
  3707. * console.log(result);
  3708. * { prefix: '!./',
  3709. * input: '!./foo/*.js',
  3710. * start: 3,
  3711. * base: 'foo',
  3712. * glob: '*.js',
  3713. * isBrace: false,
  3714. * isBracket: false,
  3715. * isGlob: true,
  3716. * isExtglob: false,
  3717. * isGlobstar: false,
  3718. * negated: true }
  3719. * ```
  3720. * @param {String} `input` Glob pattern to scan.
  3721. * @param {Object} `options`
  3722. * @return {Object} Returns an object with
  3723. * @api public
  3724. */
  3725. picomatch.scan = (input, options) => scan(input, options);
  3726. /**
  3727. * Compile a regular expression from the `state` object returned by the
  3728. * [parse()](#parse) method.
  3729. *
  3730. * @param {Object} `state`
  3731. * @param {Object} `options`
  3732. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3733. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3734. * @return {RegExp}
  3735. * @api public
  3736. */
  3737. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3738. if (returnOutput === true) {
  3739. return state.output;
  3740. }
  3741. const opts = options || {};
  3742. const prepend = opts.contains ? '' : '^';
  3743. const append = opts.contains ? '' : '$';
  3744. let source = `${prepend}(?:${state.output})${append}`;
  3745. if (state && state.negated === true) {
  3746. source = `^(?!${source}).*$`;
  3747. }
  3748. const regex = picomatch.toRegex(source, options);
  3749. if (returnState === true) {
  3750. regex.state = state;
  3751. }
  3752. return regex;
  3753. };
  3754. /**
  3755. * Create a regular expression from a parsed glob pattern.
  3756. *
  3757. * ```js
  3758. * const picomatch = require('picomatch');
  3759. * const state = picomatch.parse('*.js');
  3760. * // picomatch.compileRe(state[, options]);
  3761. *
  3762. * console.log(picomatch.compileRe(state));
  3763. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3764. * ```
  3765. * @param {String} `state` The object returned from the `.parse` method.
  3766. * @param {Object} `options`
  3767. * @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.
  3768. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3769. * @return {RegExp} Returns a regex created from the given pattern.
  3770. * @api public
  3771. */
  3772. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3773. if (!input || typeof input !== 'string') {
  3774. throw new TypeError('Expected a non-empty string');
  3775. }
  3776. let parsed = { negated: false, fastpaths: true };
  3777. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3778. parsed.output = parse.fastpaths(input, options);
  3779. }
  3780. if (!parsed.output) {
  3781. parsed = parse(input, options);
  3782. }
  3783. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  3784. };
  3785. /**
  3786. * Create a regular expression from the given regex source string.
  3787. *
  3788. * ```js
  3789. * const picomatch = require('picomatch');
  3790. * // picomatch.toRegex(source[, options]);
  3791. *
  3792. * const { output } = picomatch.parse('*.js');
  3793. * console.log(picomatch.toRegex(output));
  3794. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3795. * ```
  3796. * @param {String} `source` Regular expression source string.
  3797. * @param {Object} `options`
  3798. * @return {RegExp}
  3799. * @api public
  3800. */
  3801. picomatch.toRegex = (source, options) => {
  3802. try {
  3803. const opts = options || {};
  3804. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3805. } catch (err) {
  3806. if (options && options.debug === true) throw err;
  3807. return /$^/;
  3808. }
  3809. };
  3810. /**
  3811. * Picomatch constants.
  3812. * @return {Object}
  3813. */
  3814. picomatch.constants = constants;
  3815. /**
  3816. * Expose "picomatch"
  3817. */
  3818. var picomatch_1 = picomatch;
  3819. (function (module) {
  3820. module.exports = picomatch_1;
  3821. } (picomatch$1));
  3822. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
  3823. const extractors = {
  3824. ArrayPattern(names, param) {
  3825. for (const element of param.elements) {
  3826. if (element)
  3827. extractors[element.type](names, element);
  3828. }
  3829. },
  3830. AssignmentPattern(names, param) {
  3831. extractors[param.left.type](names, param.left);
  3832. },
  3833. Identifier(names, param) {
  3834. names.push(param.name);
  3835. },
  3836. MemberExpression() { },
  3837. ObjectPattern(names, param) {
  3838. for (const prop of param.properties) {
  3839. // @ts-ignore Typescript reports that this is not a valid type
  3840. if (prop.type === 'RestElement') {
  3841. extractors.RestElement(names, prop);
  3842. }
  3843. else {
  3844. extractors[prop.value.type](names, prop.value);
  3845. }
  3846. }
  3847. },
  3848. RestElement(names, param) {
  3849. extractors[param.argument.type](names, param.argument);
  3850. }
  3851. };
  3852. const extractAssignedNames = function extractAssignedNames(param) {
  3853. const names = [];
  3854. extractors[param.type](names, param);
  3855. return names;
  3856. };
  3857. // Helper since Typescript can't detect readonly arrays with Array.isArray
  3858. function isArray$1(arg) {
  3859. return Array.isArray(arg);
  3860. }
  3861. function ensureArray$1(thing) {
  3862. if (isArray$1(thing))
  3863. return thing;
  3864. if (thing == null)
  3865. return [];
  3866. return [thing];
  3867. }
  3868. const normalizePath = function normalizePath(filename) {
  3869. return filename.split(win32.sep).join(posix.sep);
  3870. };
  3871. function getMatcherString(id, resolutionBase) {
  3872. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
  3873. return normalizePath(id);
  3874. }
  3875. // resolve('') is valid and will default to process.cwd()
  3876. const basePath = normalizePath(resolve(resolutionBase || ''))
  3877. // escape all possible (posix + win) path characters that might interfere with regex
  3878. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  3879. // Note that we use posix.join because:
  3880. // 1. the basePath has been normalized to use /
  3881. // 2. the incoming glob (id) matcher, also uses /
  3882. // otherwise Node will force backslash (\) on windows
  3883. return posix.join(basePath, normalizePath(id));
  3884. }
  3885. const createFilter = function createFilter(include, exclude, options) {
  3886. const resolutionBase = options && options.resolve;
  3887. const getMatcher = (id) => id instanceof RegExp
  3888. ? id
  3889. : {
  3890. test: (what) => {
  3891. // this refactor is a tad overly verbose but makes for easy debugging
  3892. const pattern = getMatcherString(id, resolutionBase);
  3893. const fn = pm(pattern, { dot: true });
  3894. const result = fn(what);
  3895. return result;
  3896. }
  3897. };
  3898. const includeMatchers = ensureArray$1(include).map(getMatcher);
  3899. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  3900. return function result(id) {
  3901. if (typeof id !== 'string')
  3902. return false;
  3903. if (/\0/.test(id))
  3904. return false;
  3905. const pathId = normalizePath(id);
  3906. for (let i = 0; i < excludeMatchers.length; ++i) {
  3907. const matcher = excludeMatchers[i];
  3908. if (matcher.test(pathId))
  3909. return false;
  3910. }
  3911. for (let i = 0; i < includeMatchers.length; ++i) {
  3912. const matcher = includeMatchers[i];
  3913. if (matcher.test(pathId))
  3914. return true;
  3915. }
  3916. return !includeMatchers.length;
  3917. };
  3918. };
  3919. 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';
  3920. const builtins$1 = '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';
  3921. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  3922. forbiddenIdentifiers.add('');
  3923. const BROKEN_FLOW_NONE = 0;
  3924. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  3925. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  3926. function createInclusionContext() {
  3927. return {
  3928. brokenFlow: BROKEN_FLOW_NONE,
  3929. includedCallArguments: new Set(),
  3930. includedLabels: new Set()
  3931. };
  3932. }
  3933. function createHasEffectsContext() {
  3934. return {
  3935. accessed: new PathTracker(),
  3936. assigned: new PathTracker(),
  3937. brokenFlow: BROKEN_FLOW_NONE,
  3938. called: new DiscriminatedPathTracker(),
  3939. ignore: {
  3940. breaks: false,
  3941. continues: false,
  3942. labels: new Set(),
  3943. returnYield: false
  3944. },
  3945. includedLabels: new Set(),
  3946. instantiated: new DiscriminatedPathTracker(),
  3947. replacedVariableInits: new Map()
  3948. };
  3949. }
  3950. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  3951. return Object.create(inheritedDescriptions, memberDescriptions);
  3952. }
  3953. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  3954. getLiteralValueAtPath() {
  3955. return undefined;
  3956. }
  3957. })();
  3958. const returnsUnknown = {
  3959. value: {
  3960. hasEffectsWhenCalled: null,
  3961. returns: UNKNOWN_EXPRESSION
  3962. }
  3963. };
  3964. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  3965. getReturnExpressionWhenCalledAtPath(path) {
  3966. if (path.length === 1) {
  3967. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  3968. }
  3969. return UNKNOWN_EXPRESSION;
  3970. }
  3971. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3972. if (interaction.type === INTERACTION_ACCESSED) {
  3973. return path.length > 1;
  3974. }
  3975. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3976. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  3977. }
  3978. return true;
  3979. }
  3980. })();
  3981. const returnsBoolean = {
  3982. value: {
  3983. hasEffectsWhenCalled: null,
  3984. returns: UNKNOWN_LITERAL_BOOLEAN
  3985. }
  3986. };
  3987. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  3988. getReturnExpressionWhenCalledAtPath(path) {
  3989. if (path.length === 1) {
  3990. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  3991. }
  3992. return UNKNOWN_EXPRESSION;
  3993. }
  3994. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3995. if (interaction.type === INTERACTION_ACCESSED) {
  3996. return path.length > 1;
  3997. }
  3998. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3999. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4000. }
  4001. return true;
  4002. }
  4003. })();
  4004. const returnsNumber = {
  4005. value: {
  4006. hasEffectsWhenCalled: null,
  4007. returns: UNKNOWN_LITERAL_NUMBER
  4008. }
  4009. };
  4010. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4011. getReturnExpressionWhenCalledAtPath(path) {
  4012. if (path.length === 1) {
  4013. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4014. }
  4015. return UNKNOWN_EXPRESSION;
  4016. }
  4017. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4018. if (interaction.type === INTERACTION_ACCESSED) {
  4019. return path.length > 1;
  4020. }
  4021. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4022. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4023. }
  4024. return true;
  4025. }
  4026. })();
  4027. const returnsString = {
  4028. value: {
  4029. hasEffectsWhenCalled: null,
  4030. returns: UNKNOWN_LITERAL_STRING
  4031. }
  4032. };
  4033. const stringReplace = {
  4034. value: {
  4035. hasEffectsWhenCalled({ args }, context) {
  4036. const arg1 = args[1];
  4037. return (args.length < 2 ||
  4038. (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4039. deoptimizeCache() { }
  4040. }) === 'symbol' &&
  4041. arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4042. },
  4043. returns: UNKNOWN_LITERAL_STRING
  4044. }
  4045. };
  4046. const objectMembers = assembleMemberDescriptions({
  4047. hasOwnProperty: returnsBoolean,
  4048. isPrototypeOf: returnsBoolean,
  4049. propertyIsEnumerable: returnsBoolean,
  4050. toLocaleString: returnsString,
  4051. toString: returnsString,
  4052. valueOf: returnsUnknown
  4053. });
  4054. const literalBooleanMembers = assembleMemberDescriptions({
  4055. valueOf: returnsBoolean
  4056. }, objectMembers);
  4057. const literalNumberMembers = assembleMemberDescriptions({
  4058. toExponential: returnsString,
  4059. toFixed: returnsString,
  4060. toLocaleString: returnsString,
  4061. toPrecision: returnsString,
  4062. valueOf: returnsNumber
  4063. }, objectMembers);
  4064. const literalStringMembers = assembleMemberDescriptions({
  4065. anchor: returnsString,
  4066. at: returnsUnknown,
  4067. big: returnsString,
  4068. blink: returnsString,
  4069. bold: returnsString,
  4070. charAt: returnsString,
  4071. charCodeAt: returnsNumber,
  4072. codePointAt: returnsUnknown,
  4073. concat: returnsString,
  4074. endsWith: returnsBoolean,
  4075. fixed: returnsString,
  4076. fontcolor: returnsString,
  4077. fontsize: returnsString,
  4078. includes: returnsBoolean,
  4079. indexOf: returnsNumber,
  4080. italics: returnsString,
  4081. lastIndexOf: returnsNumber,
  4082. link: returnsString,
  4083. localeCompare: returnsNumber,
  4084. match: returnsUnknown,
  4085. matchAll: returnsUnknown,
  4086. normalize: returnsString,
  4087. padEnd: returnsString,
  4088. padStart: returnsString,
  4089. repeat: returnsString,
  4090. replace: stringReplace,
  4091. replaceAll: stringReplace,
  4092. search: returnsNumber,
  4093. slice: returnsString,
  4094. small: returnsString,
  4095. split: returnsUnknown,
  4096. startsWith: returnsBoolean,
  4097. strike: returnsString,
  4098. sub: returnsString,
  4099. substr: returnsString,
  4100. substring: returnsString,
  4101. sup: returnsString,
  4102. toLocaleLowerCase: returnsString,
  4103. toLocaleUpperCase: returnsString,
  4104. toLowerCase: returnsString,
  4105. toString: returnsString,
  4106. toUpperCase: returnsString,
  4107. trim: returnsString,
  4108. trimEnd: returnsString,
  4109. trimLeft: returnsString,
  4110. trimRight: returnsString,
  4111. trimStart: returnsString,
  4112. valueOf: returnsString
  4113. }, objectMembers);
  4114. function getLiteralMembersForValue(value) {
  4115. switch (typeof value) {
  4116. case 'boolean':
  4117. return literalBooleanMembers;
  4118. case 'number':
  4119. return literalNumberMembers;
  4120. case 'string':
  4121. return literalStringMembers;
  4122. }
  4123. return Object.create(null);
  4124. }
  4125. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4126. var _a, _b;
  4127. if (typeof memberName !== 'string' || !members[memberName]) {
  4128. return true;
  4129. }
  4130. return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
  4131. }
  4132. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4133. if (typeof memberName !== 'string' || !members[memberName])
  4134. return UNKNOWN_EXPRESSION;
  4135. return members[memberName].returns;
  4136. }
  4137. // AST walker module for Mozilla Parser API compatible trees
  4138. function skipThrough(node, st, c) { c(node, st); }
  4139. function ignore(_node, _st, _c) {}
  4140. // Node walkers.
  4141. var base$1 = {};
  4142. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  4143. for (var i = 0, list = node.body; i < list.length; i += 1)
  4144. {
  4145. var stmt = list[i];
  4146. c(stmt, st, "Statement");
  4147. }
  4148. };
  4149. base$1.Statement = skipThrough;
  4150. base$1.EmptyStatement = ignore;
  4151. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  4152. function (node, st, c) { return c(node.expression, st, "Expression"); };
  4153. base$1.IfStatement = function (node, st, c) {
  4154. c(node.test, st, "Expression");
  4155. c(node.consequent, st, "Statement");
  4156. if (node.alternate) { c(node.alternate, st, "Statement"); }
  4157. };
  4158. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  4159. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  4160. base$1.WithStatement = function (node, st, c) {
  4161. c(node.object, st, "Expression");
  4162. c(node.body, st, "Statement");
  4163. };
  4164. base$1.SwitchStatement = function (node, st, c) {
  4165. c(node.discriminant, st, "Expression");
  4166. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  4167. var cs = list$1[i$1];
  4168. if (cs.test) { c(cs.test, st, "Expression"); }
  4169. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  4170. {
  4171. var cons = list[i];
  4172. c(cons, st, "Statement");
  4173. }
  4174. }
  4175. };
  4176. base$1.SwitchCase = function (node, st, c) {
  4177. if (node.test) { c(node.test, st, "Expression"); }
  4178. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  4179. {
  4180. var cons = list[i];
  4181. c(cons, st, "Statement");
  4182. }
  4183. };
  4184. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  4185. if (node.argument) { c(node.argument, st, "Expression"); }
  4186. };
  4187. base$1.ThrowStatement = base$1.SpreadElement =
  4188. function (node, st, c) { return c(node.argument, st, "Expression"); };
  4189. base$1.TryStatement = function (node, st, c) {
  4190. c(node.block, st, "Statement");
  4191. if (node.handler) { c(node.handler, st); }
  4192. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  4193. };
  4194. base$1.CatchClause = function (node, st, c) {
  4195. if (node.param) { c(node.param, st, "Pattern"); }
  4196. c(node.body, st, "Statement");
  4197. };
  4198. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  4199. c(node.test, st, "Expression");
  4200. c(node.body, st, "Statement");
  4201. };
  4202. base$1.ForStatement = function (node, st, c) {
  4203. if (node.init) { c(node.init, st, "ForInit"); }
  4204. if (node.test) { c(node.test, st, "Expression"); }
  4205. if (node.update) { c(node.update, st, "Expression"); }
  4206. c(node.body, st, "Statement");
  4207. };
  4208. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  4209. c(node.left, st, "ForInit");
  4210. c(node.right, st, "Expression");
  4211. c(node.body, st, "Statement");
  4212. };
  4213. base$1.ForInit = function (node, st, c) {
  4214. if (node.type === "VariableDeclaration") { c(node, st); }
  4215. else { c(node, st, "Expression"); }
  4216. };
  4217. base$1.DebuggerStatement = ignore;
  4218. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  4219. base$1.VariableDeclaration = function (node, st, c) {
  4220. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  4221. {
  4222. var decl = list[i];
  4223. c(decl, st);
  4224. }
  4225. };
  4226. base$1.VariableDeclarator = function (node, st, c) {
  4227. c(node.id, st, "Pattern");
  4228. if (node.init) { c(node.init, st, "Expression"); }
  4229. };
  4230. base$1.Function = function (node, st, c) {
  4231. if (node.id) { c(node.id, st, "Pattern"); }
  4232. for (var i = 0, list = node.params; i < list.length; i += 1)
  4233. {
  4234. var param = list[i];
  4235. c(param, st, "Pattern");
  4236. }
  4237. c(node.body, st, node.expression ? "Expression" : "Statement");
  4238. };
  4239. base$1.Pattern = function (node, st, c) {
  4240. if (node.type === "Identifier")
  4241. { c(node, st, "VariablePattern"); }
  4242. else if (node.type === "MemberExpression")
  4243. { c(node, st, "MemberPattern"); }
  4244. else
  4245. { c(node, st); }
  4246. };
  4247. base$1.VariablePattern = ignore;
  4248. base$1.MemberPattern = skipThrough;
  4249. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  4250. base$1.ArrayPattern = function (node, st, c) {
  4251. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4252. var elt = list[i];
  4253. if (elt) { c(elt, st, "Pattern"); }
  4254. }
  4255. };
  4256. base$1.ObjectPattern = function (node, st, c) {
  4257. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  4258. var prop = list[i];
  4259. if (prop.type === "Property") {
  4260. if (prop.computed) { c(prop.key, st, "Expression"); }
  4261. c(prop.value, st, "Pattern");
  4262. } else if (prop.type === "RestElement") {
  4263. c(prop.argument, st, "Pattern");
  4264. }
  4265. }
  4266. };
  4267. base$1.Expression = skipThrough;
  4268. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  4269. base$1.ArrayExpression = function (node, st, c) {
  4270. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4271. var elt = list[i];
  4272. if (elt) { c(elt, st, "Expression"); }
  4273. }
  4274. };
  4275. base$1.ObjectExpression = function (node, st, c) {
  4276. for (var i = 0, list = node.properties; i < list.length; i += 1)
  4277. {
  4278. var prop = list[i];
  4279. c(prop, st);
  4280. }
  4281. };
  4282. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  4283. base$1.SequenceExpression = function (node, st, c) {
  4284. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  4285. {
  4286. var expr = list[i];
  4287. c(expr, st, "Expression");
  4288. }
  4289. };
  4290. base$1.TemplateLiteral = function (node, st, c) {
  4291. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  4292. {
  4293. var quasi = list[i];
  4294. c(quasi, st);
  4295. }
  4296. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  4297. {
  4298. var expr = list$1[i$1];
  4299. c(expr, st, "Expression");
  4300. }
  4301. };
  4302. base$1.TemplateElement = ignore;
  4303. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  4304. c(node.argument, st, "Expression");
  4305. };
  4306. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  4307. c(node.left, st, "Expression");
  4308. c(node.right, st, "Expression");
  4309. };
  4310. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  4311. c(node.left, st, "Pattern");
  4312. c(node.right, st, "Expression");
  4313. };
  4314. base$1.ConditionalExpression = function (node, st, c) {
  4315. c(node.test, st, "Expression");
  4316. c(node.consequent, st, "Expression");
  4317. c(node.alternate, st, "Expression");
  4318. };
  4319. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  4320. c(node.callee, st, "Expression");
  4321. if (node.arguments)
  4322. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  4323. {
  4324. var arg = list[i];
  4325. c(arg, st, "Expression");
  4326. } }
  4327. };
  4328. base$1.MemberExpression = function (node, st, c) {
  4329. c(node.object, st, "Expression");
  4330. if (node.computed) { c(node.property, st, "Expression"); }
  4331. };
  4332. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  4333. if (node.declaration)
  4334. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  4335. if (node.source) { c(node.source, st, "Expression"); }
  4336. };
  4337. base$1.ExportAllDeclaration = function (node, st, c) {
  4338. if (node.exported)
  4339. { c(node.exported, st); }
  4340. c(node.source, st, "Expression");
  4341. };
  4342. base$1.ImportDeclaration = function (node, st, c) {
  4343. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  4344. {
  4345. var spec = list[i];
  4346. c(spec, st);
  4347. }
  4348. c(node.source, st, "Expression");
  4349. };
  4350. base$1.ImportExpression = function (node, st, c) {
  4351. c(node.source, st, "Expression");
  4352. };
  4353. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  4354. base$1.TaggedTemplateExpression = function (node, st, c) {
  4355. c(node.tag, st, "Expression");
  4356. c(node.quasi, st, "Expression");
  4357. };
  4358. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  4359. base$1.Class = function (node, st, c) {
  4360. if (node.id) { c(node.id, st, "Pattern"); }
  4361. if (node.superClass) { c(node.superClass, st, "Expression"); }
  4362. c(node.body, st);
  4363. };
  4364. base$1.ClassBody = function (node, st, c) {
  4365. for (var i = 0, list = node.body; i < list.length; i += 1)
  4366. {
  4367. var elt = list[i];
  4368. c(elt, st);
  4369. }
  4370. };
  4371. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  4372. if (node.computed) { c(node.key, st, "Expression"); }
  4373. if (node.value) { c(node.value, st, "Expression"); }
  4374. };
  4375. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  4376. const BinaryExpression$1 = 'BinaryExpression';
  4377. const BlockStatement$1 = 'BlockStatement';
  4378. const CallExpression$1 = 'CallExpression';
  4379. const ChainExpression$1 = 'ChainExpression';
  4380. const ConditionalExpression$1 = 'ConditionalExpression';
  4381. const ExpressionStatement$1 = 'ExpressionStatement';
  4382. const Identifier$1 = 'Identifier';
  4383. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  4384. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  4385. const LogicalExpression$1 = 'LogicalExpression';
  4386. const NewExpression$1 = 'NewExpression';
  4387. const Program$1 = 'Program';
  4388. const Property$1 = 'Property';
  4389. const ReturnStatement$1 = 'ReturnStatement';
  4390. const SequenceExpression$1 = 'SequenceExpression';
  4391. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  4392. // this for an actual sourceMappingURL
  4393. let SOURCEMAPPING_URL = 'sourceMa';
  4394. SOURCEMAPPING_URL += 'ppingURL';
  4395. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  4396. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  4397. const ANNOTATION_KEY = '_rollupAnnotations';
  4398. const INVALID_COMMENT_KEY = '_rollupRemoved';
  4399. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  4400. const { annotations } = state;
  4401. let comment = annotations[state.annotationIndex];
  4402. while (comment && node.start >= comment.end) {
  4403. markPureNode(node, comment, state.code);
  4404. comment = annotations[++state.annotationIndex];
  4405. }
  4406. if (comment && comment.end <= node.end) {
  4407. base$1[type](node, state, handlePureAnnotationsOfNode);
  4408. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  4409. ++state.annotationIndex;
  4410. annotateNode(node, comment, false);
  4411. }
  4412. }
  4413. }
  4414. const neitherWithespaceNorBrackets = /[^\s(]/g;
  4415. const noWhitespace = /\S/g;
  4416. function markPureNode(node, comment, code) {
  4417. const annotatedNodes = [];
  4418. let invalidAnnotation;
  4419. const codeInBetween = code.slice(comment.end, node.start);
  4420. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  4421. const parentStart = node.start;
  4422. while (true) {
  4423. annotatedNodes.push(node);
  4424. switch (node.type) {
  4425. case ExpressionStatement$1:
  4426. case ChainExpression$1:
  4427. node = node.expression;
  4428. continue;
  4429. case SequenceExpression$1:
  4430. // if there are parentheses, the annotation would apply to the entire expression
  4431. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4432. node = node.expressions[0];
  4433. continue;
  4434. }
  4435. invalidAnnotation = true;
  4436. break;
  4437. case ConditionalExpression$1:
  4438. // if there are parentheses, the annotation would apply to the entire expression
  4439. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4440. node = node.test;
  4441. continue;
  4442. }
  4443. invalidAnnotation = true;
  4444. break;
  4445. case LogicalExpression$1:
  4446. case BinaryExpression$1:
  4447. // if there are parentheses, the annotation would apply to the entire expression
  4448. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4449. node = node.left;
  4450. continue;
  4451. }
  4452. invalidAnnotation = true;
  4453. break;
  4454. case CallExpression$1:
  4455. case NewExpression$1:
  4456. break;
  4457. default:
  4458. invalidAnnotation = true;
  4459. }
  4460. break;
  4461. }
  4462. }
  4463. else {
  4464. invalidAnnotation = true;
  4465. }
  4466. if (invalidAnnotation) {
  4467. annotateNode(node, comment, false);
  4468. }
  4469. else {
  4470. for (const node of annotatedNodes) {
  4471. annotateNode(node, comment, true);
  4472. }
  4473. }
  4474. }
  4475. function doesNotMatchOutsideComment(code, forbiddenChars) {
  4476. let nextMatch;
  4477. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  4478. if (nextMatch[0] === '/') {
  4479. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  4480. if (charCodeAfterSlash === 42 /*"*"*/) {
  4481. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  4482. continue;
  4483. }
  4484. else if (charCodeAfterSlash === 47 /*"/"*/) {
  4485. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  4486. continue;
  4487. }
  4488. }
  4489. forbiddenChars.lastIndex = 0;
  4490. return false;
  4491. }
  4492. return true;
  4493. }
  4494. const pureCommentRegex = /[@#]__PURE__/;
  4495. function addAnnotations(comments, esTreeAst, code) {
  4496. const annotations = [];
  4497. const sourceMappingComments = [];
  4498. for (const comment of comments) {
  4499. if (pureCommentRegex.test(comment.value)) {
  4500. annotations.push(comment);
  4501. }
  4502. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  4503. sourceMappingComments.push(comment);
  4504. }
  4505. }
  4506. for (const comment of sourceMappingComments) {
  4507. annotateNode(esTreeAst, comment, false);
  4508. }
  4509. handlePureAnnotationsOfNode(esTreeAst, {
  4510. annotationIndex: 0,
  4511. annotations,
  4512. code
  4513. });
  4514. }
  4515. function annotateNode(node, comment, valid) {
  4516. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  4517. const property = node[key];
  4518. if (property) {
  4519. property.push(comment);
  4520. }
  4521. else {
  4522. node[key] = [comment];
  4523. }
  4524. }
  4525. const keys = {
  4526. Literal: [],
  4527. Program: ['body']
  4528. };
  4529. function getAndCreateKeys(esTreeNode) {
  4530. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4531. return keys[esTreeNode.type];
  4532. }
  4533. const INCLUDE_PARAMETERS = 'variables';
  4534. class NodeBase extends ExpressionEntity {
  4535. constructor(esTreeNode, parent, parentScope) {
  4536. super();
  4537. /**
  4538. * Nodes can apply custom deoptimizations once they become part of the
  4539. * executed code. To do this, they must initialize this as false, implement
  4540. * applyDeoptimizations and call this from include and hasEffects if they have
  4541. * custom handlers
  4542. */
  4543. this.deoptimized = false;
  4544. this.esTreeNode = esTreeNode;
  4545. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  4546. this.parent = parent;
  4547. this.context = parent.context;
  4548. this.createScope(parentScope);
  4549. this.parseNode(esTreeNode);
  4550. this.initialise();
  4551. this.context.magicString.addSourcemapLocation(this.start);
  4552. this.context.magicString.addSourcemapLocation(this.end);
  4553. }
  4554. addExportedVariables(_variables, _exportNamesByVariable) { }
  4555. /**
  4556. * Override this to bind assignments to variables and do any initialisations that
  4557. * require the scopes to be populated with variables.
  4558. */
  4559. bind() {
  4560. for (const key of this.keys) {
  4561. const value = this[key];
  4562. if (value === null)
  4563. continue;
  4564. if (Array.isArray(value)) {
  4565. for (const child of value) {
  4566. child === null || child === void 0 ? void 0 : child.bind();
  4567. }
  4568. }
  4569. else {
  4570. value.bind();
  4571. }
  4572. }
  4573. }
  4574. /**
  4575. * Override if this node should receive a different scope than the parent scope.
  4576. */
  4577. createScope(parentScope) {
  4578. this.scope = parentScope;
  4579. }
  4580. hasEffects(context) {
  4581. if (!this.deoptimized)
  4582. this.applyDeoptimizations();
  4583. for (const key of this.keys) {
  4584. const value = this[key];
  4585. if (value === null)
  4586. continue;
  4587. if (Array.isArray(value)) {
  4588. for (const child of value) {
  4589. if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
  4590. return true;
  4591. }
  4592. }
  4593. else if (value.hasEffects(context))
  4594. return true;
  4595. }
  4596. return false;
  4597. }
  4598. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4599. return (this.hasEffects(context) ||
  4600. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4601. }
  4602. include(context, includeChildrenRecursively, _options) {
  4603. if (!this.deoptimized)
  4604. this.applyDeoptimizations();
  4605. this.included = true;
  4606. for (const key of this.keys) {
  4607. const value = this[key];
  4608. if (value === null)
  4609. continue;
  4610. if (Array.isArray(value)) {
  4611. for (const child of value) {
  4612. child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
  4613. }
  4614. }
  4615. else {
  4616. value.include(context, includeChildrenRecursively);
  4617. }
  4618. }
  4619. }
  4620. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4621. this.include(context, includeChildrenRecursively);
  4622. }
  4623. /**
  4624. * Override to perform special initialisation steps after the scope is initialised
  4625. */
  4626. initialise() { }
  4627. insertSemicolon(code) {
  4628. if (code.original[this.end - 1] !== ';') {
  4629. code.appendLeft(this.end, ';');
  4630. }
  4631. }
  4632. parseNode(esTreeNode) {
  4633. for (const [key, value] of Object.entries(esTreeNode)) {
  4634. // That way, we can override this function to add custom initialisation and then call super.parseNode
  4635. if (this.hasOwnProperty(key))
  4636. continue;
  4637. if (key.charCodeAt(0) === 95 /* _ */) {
  4638. if (key === ANNOTATION_KEY) {
  4639. this.annotations = value;
  4640. }
  4641. else if (key === INVALID_COMMENT_KEY) {
  4642. for (const { start, end } of value)
  4643. this.context.magicString.remove(start, end);
  4644. }
  4645. }
  4646. else if (typeof value !== 'object' || value === null) {
  4647. this[key] = value;
  4648. }
  4649. else if (Array.isArray(value)) {
  4650. this[key] = [];
  4651. for (const child of value) {
  4652. this[key].push(child === null
  4653. ? null
  4654. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
  4655. }
  4656. }
  4657. else {
  4658. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
  4659. }
  4660. }
  4661. }
  4662. render(code, options) {
  4663. for (const key of this.keys) {
  4664. const value = this[key];
  4665. if (value === null)
  4666. continue;
  4667. if (Array.isArray(value)) {
  4668. for (const child of value) {
  4669. child === null || child === void 0 ? void 0 : child.render(code, options);
  4670. }
  4671. }
  4672. else {
  4673. value.render(code, options);
  4674. }
  4675. }
  4676. }
  4677. setAssignedValue(value) {
  4678. this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
  4679. }
  4680. shouldBeIncluded(context) {
  4681. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4682. }
  4683. /**
  4684. * Just deoptimize everything by default so that when e.g. we do not track
  4685. * something properly, it is deoptimized.
  4686. * @protected
  4687. */
  4688. applyDeoptimizations() {
  4689. this.deoptimized = true;
  4690. for (const key of this.keys) {
  4691. const value = this[key];
  4692. if (value === null)
  4693. continue;
  4694. if (Array.isArray(value)) {
  4695. for (const child of value) {
  4696. child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
  4697. }
  4698. }
  4699. else {
  4700. value.deoptimizePath(UNKNOWN_PATH);
  4701. }
  4702. }
  4703. this.context.requestTreeshakingPass();
  4704. }
  4705. }
  4706. class SpreadElement extends NodeBase {
  4707. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4708. if (path.length > 0) {
  4709. this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4710. }
  4711. }
  4712. hasEffects(context) {
  4713. if (!this.deoptimized)
  4714. this.applyDeoptimizations();
  4715. const { propertyReadSideEffects } = this.context.options
  4716. .treeshake;
  4717. return (this.argument.hasEffects(context) ||
  4718. (propertyReadSideEffects &&
  4719. (propertyReadSideEffects === 'always' ||
  4720. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4721. }
  4722. applyDeoptimizations() {
  4723. this.deoptimized = true;
  4724. // Only properties of properties of the argument could become subject to reassignment
  4725. // This will also reassign the return values of iterators
  4726. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4727. this.context.requestTreeshakingPass();
  4728. }
  4729. }
  4730. class Method extends ExpressionEntity {
  4731. constructor(description) {
  4732. super();
  4733. this.description = description;
  4734. }
  4735. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  4736. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4737. thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4738. }
  4739. }
  4740. getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
  4741. if (path.length > 0) {
  4742. return UNKNOWN_EXPRESSION;
  4743. }
  4744. return (this.description.returnsPrimitive ||
  4745. (this.description.returns === 'self'
  4746. ? thisArg || UNKNOWN_EXPRESSION
  4747. : this.description.returns()));
  4748. }
  4749. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4750. var _a, _b;
  4751. const { type } = interaction;
  4752. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4753. return true;
  4754. }
  4755. if (type === INTERACTION_CALLED) {
  4756. if (this.description.mutatesSelfAsArray === true &&
  4757. ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
  4758. return true;
  4759. }
  4760. if (this.description.callsArgs) {
  4761. for (const argIndex of this.description.callsArgs) {
  4762. if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4763. return true;
  4764. }
  4765. }
  4766. }
  4767. }
  4768. return false;
  4769. }
  4770. }
  4771. const METHOD_RETURNS_BOOLEAN = [
  4772. new Method({
  4773. callsArgs: null,
  4774. mutatesSelfAsArray: false,
  4775. returns: null,
  4776. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4777. })
  4778. ];
  4779. const METHOD_RETURNS_STRING = [
  4780. new Method({
  4781. callsArgs: null,
  4782. mutatesSelfAsArray: false,
  4783. returns: null,
  4784. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4785. })
  4786. ];
  4787. const METHOD_RETURNS_NUMBER = [
  4788. new Method({
  4789. callsArgs: null,
  4790. mutatesSelfAsArray: false,
  4791. returns: null,
  4792. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4793. })
  4794. ];
  4795. const METHOD_RETURNS_UNKNOWN = [
  4796. new Method({
  4797. callsArgs: null,
  4798. mutatesSelfAsArray: false,
  4799. returns: null,
  4800. returnsPrimitive: UNKNOWN_EXPRESSION
  4801. })
  4802. ];
  4803. const INTEGER_REG_EXP = /^\d+$/;
  4804. class ObjectEntity extends ExpressionEntity {
  4805. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4806. // and we assume there are no setters or getters
  4807. constructor(properties, prototypeExpression, immutable = false) {
  4808. super();
  4809. this.prototypeExpression = prototypeExpression;
  4810. this.immutable = immutable;
  4811. this.allProperties = [];
  4812. this.deoptimizedPaths = Object.create(null);
  4813. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4814. this.gettersByKey = Object.create(null);
  4815. this.hasLostTrack = false;
  4816. this.hasUnknownDeoptimizedInteger = false;
  4817. this.hasUnknownDeoptimizedProperty = false;
  4818. this.propertiesAndGettersByKey = Object.create(null);
  4819. this.propertiesAndSettersByKey = Object.create(null);
  4820. this.settersByKey = Object.create(null);
  4821. this.thisParametersToBeDeoptimized = new Set();
  4822. this.unknownIntegerProps = [];
  4823. this.unmatchableGetters = [];
  4824. this.unmatchablePropertiesAndGetters = [];
  4825. this.unmatchableSetters = [];
  4826. if (Array.isArray(properties)) {
  4827. this.buildPropertyMaps(properties);
  4828. }
  4829. else {
  4830. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4831. for (const propertiesForKey of Object.values(properties)) {
  4832. this.allProperties.push(...propertiesForKey);
  4833. }
  4834. }
  4835. }
  4836. deoptimizeAllProperties(noAccessors) {
  4837. var _a;
  4838. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4839. if (noAccessors) {
  4840. this.hasUnknownDeoptimizedProperty = true;
  4841. }
  4842. else {
  4843. this.hasLostTrack = true;
  4844. }
  4845. if (isDeoptimized) {
  4846. return;
  4847. }
  4848. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4849. for (const property of properties) {
  4850. property.deoptimizePath(UNKNOWN_PATH);
  4851. }
  4852. }
  4853. // While the prototype itself cannot be mutated, each property can
  4854. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4855. this.deoptimizeCachedEntities();
  4856. }
  4857. deoptimizeIntegerProperties() {
  4858. if (this.hasLostTrack ||
  4859. this.hasUnknownDeoptimizedProperty ||
  4860. this.hasUnknownDeoptimizedInteger) {
  4861. return;
  4862. }
  4863. this.hasUnknownDeoptimizedInteger = true;
  4864. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4865. if (INTEGER_REG_EXP.test(key)) {
  4866. for (const property of propertiesAndGetters) {
  4867. property.deoptimizePath(UNKNOWN_PATH);
  4868. }
  4869. }
  4870. }
  4871. this.deoptimizeCachedIntegerEntities();
  4872. }
  4873. // Assumption: If only a specific path is deoptimized, no accessors are created
  4874. deoptimizePath(path) {
  4875. var _a;
  4876. if (this.hasLostTrack || this.immutable) {
  4877. return;
  4878. }
  4879. const key = path[0];
  4880. if (path.length === 1) {
  4881. if (typeof key !== 'string') {
  4882. if (key === UnknownInteger) {
  4883. return this.deoptimizeIntegerProperties();
  4884. }
  4885. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4886. }
  4887. if (!this.deoptimizedPaths[key]) {
  4888. this.deoptimizedPaths[key] = true;
  4889. // we only deoptimizeCache exact matches as in all other cases,
  4890. // we do not return a literal value or return expression
  4891. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4892. if (expressionsToBeDeoptimized) {
  4893. for (const expression of expressionsToBeDeoptimized) {
  4894. expression.deoptimizeCache();
  4895. }
  4896. }
  4897. }
  4898. }
  4899. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4900. for (const property of typeof key === 'string'
  4901. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  4902. : this.allProperties) {
  4903. property.deoptimizePath(subPath);
  4904. }
  4905. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  4906. }
  4907. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4908. var _a;
  4909. const [key, ...subPath] = path;
  4910. if (this.hasLostTrack ||
  4911. // single paths that are deoptimized will not become getters or setters
  4912. ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
  4913. (this.hasUnknownDeoptimizedProperty ||
  4914. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  4915. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  4916. return;
  4917. }
  4918. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
  4919. ? [
  4920. this.propertiesAndGettersByKey,
  4921. this.propertiesAndGettersByKey,
  4922. this.unmatchablePropertiesAndGetters
  4923. ]
  4924. : interaction.type === INTERACTION_ACCESSED
  4925. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4926. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4927. if (typeof key === 'string') {
  4928. if (propertiesForExactMatchByKey[key]) {
  4929. const properties = relevantPropertiesByKey[key];
  4930. if (properties) {
  4931. for (const property of properties) {
  4932. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4933. }
  4934. }
  4935. if (!this.immutable) {
  4936. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  4937. }
  4938. return;
  4939. }
  4940. for (const property of relevantUnmatchableProperties) {
  4941. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4942. }
  4943. if (INTEGER_REG_EXP.test(key)) {
  4944. for (const property of this.unknownIntegerProps) {
  4945. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4946. }
  4947. }
  4948. }
  4949. else {
  4950. for (const properties of Object.values(relevantPropertiesByKey).concat([
  4951. relevantUnmatchableProperties
  4952. ])) {
  4953. for (const property of properties) {
  4954. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4955. }
  4956. }
  4957. for (const property of this.unknownIntegerProps) {
  4958. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4959. }
  4960. }
  4961. if (!this.immutable) {
  4962. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  4963. }
  4964. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  4965. }
  4966. getLiteralValueAtPath(path, recursionTracker, origin) {
  4967. if (path.length === 0) {
  4968. return UnknownTruthyValue;
  4969. }
  4970. const key = path[0];
  4971. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4972. if (expressionAtPath) {
  4973. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4974. }
  4975. if (this.prototypeExpression) {
  4976. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4977. }
  4978. if (path.length === 1) {
  4979. return undefined;
  4980. }
  4981. return UnknownValue;
  4982. }
  4983. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4984. if (path.length === 0) {
  4985. return UNKNOWN_EXPRESSION;
  4986. }
  4987. const [key, ...subPath] = path;
  4988. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4989. if (expressionAtPath) {
  4990. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  4991. }
  4992. if (this.prototypeExpression) {
  4993. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4994. }
  4995. return UNKNOWN_EXPRESSION;
  4996. }
  4997. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4998. const [key, ...subPath] = path;
  4999. if (subPath.length || interaction.type === INTERACTION_CALLED) {
  5000. const expressionAtPath = this.getMemberExpression(key);
  5001. if (expressionAtPath) {
  5002. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5003. }
  5004. if (this.prototypeExpression) {
  5005. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5006. }
  5007. return true;
  5008. }
  5009. if (key === UnknownNonAccessorKey)
  5010. return false;
  5011. if (this.hasLostTrack)
  5012. return true;
  5013. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5014. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5015. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5016. if (typeof key === 'string') {
  5017. if (propertiesAndAccessorsByKey[key]) {
  5018. const accessors = accessorsByKey[key];
  5019. if (accessors) {
  5020. for (const accessor of accessors) {
  5021. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5022. return true;
  5023. }
  5024. }
  5025. return false;
  5026. }
  5027. for (const accessor of unmatchableAccessors) {
  5028. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5029. return true;
  5030. }
  5031. }
  5032. }
  5033. else {
  5034. for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
  5035. for (const accessor of accessors) {
  5036. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5037. return true;
  5038. }
  5039. }
  5040. }
  5041. if (this.prototypeExpression) {
  5042. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5043. }
  5044. return false;
  5045. }
  5046. buildPropertyMaps(properties) {
  5047. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5048. const unmatchablePropertiesAndSetters = [];
  5049. for (let index = properties.length - 1; index >= 0; index--) {
  5050. const { key, kind, property } = properties[index];
  5051. allProperties.push(property);
  5052. if (typeof key !== 'string') {
  5053. if (key === UnknownInteger) {
  5054. unknownIntegerProps.push(property);
  5055. continue;
  5056. }
  5057. if (kind === 'set')
  5058. unmatchableSetters.push(property);
  5059. if (kind === 'get')
  5060. unmatchableGetters.push(property);
  5061. if (kind !== 'get')
  5062. unmatchablePropertiesAndSetters.push(property);
  5063. if (kind !== 'set')
  5064. unmatchablePropertiesAndGetters.push(property);
  5065. }
  5066. else {
  5067. if (kind === 'set') {
  5068. if (!propertiesAndSettersByKey[key]) {
  5069. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5070. settersByKey[key] = [property, ...unmatchableSetters];
  5071. }
  5072. }
  5073. else if (kind === 'get') {
  5074. if (!propertiesAndGettersByKey[key]) {
  5075. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5076. gettersByKey[key] = [property, ...unmatchableGetters];
  5077. }
  5078. }
  5079. else {
  5080. if (!propertiesAndSettersByKey[key]) {
  5081. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5082. }
  5083. if (!propertiesAndGettersByKey[key]) {
  5084. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5085. }
  5086. }
  5087. }
  5088. }
  5089. }
  5090. deoptimizeCachedEntities() {
  5091. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  5092. for (const expression of expressionsToBeDeoptimized) {
  5093. expression.deoptimizeCache();
  5094. }
  5095. }
  5096. for (const expression of this.thisParametersToBeDeoptimized) {
  5097. expression.deoptimizePath(UNKNOWN_PATH);
  5098. }
  5099. }
  5100. deoptimizeCachedIntegerEntities() {
  5101. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  5102. if (INTEGER_REG_EXP.test(key)) {
  5103. for (const expression of expressionsToBeDeoptimized) {
  5104. expression.deoptimizeCache();
  5105. }
  5106. }
  5107. }
  5108. for (const expression of this.thisParametersToBeDeoptimized) {
  5109. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5110. }
  5111. }
  5112. getMemberExpression(key) {
  5113. if (this.hasLostTrack ||
  5114. this.hasUnknownDeoptimizedProperty ||
  5115. typeof key !== 'string' ||
  5116. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  5117. this.deoptimizedPaths[key]) {
  5118. return UNKNOWN_EXPRESSION;
  5119. }
  5120. const properties = this.propertiesAndGettersByKey[key];
  5121. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  5122. return properties[0];
  5123. }
  5124. if (properties ||
  5125. this.unmatchablePropertiesAndGetters.length > 0 ||
  5126. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  5127. return UNKNOWN_EXPRESSION;
  5128. }
  5129. return null;
  5130. }
  5131. getMemberExpressionAndTrackDeopt(key, origin) {
  5132. if (typeof key !== 'string') {
  5133. return UNKNOWN_EXPRESSION;
  5134. }
  5135. const expression = this.getMemberExpression(key);
  5136. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  5137. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  5138. this.expressionsToBeDeoptimizedByKey[key] || []);
  5139. expressionsToBeDeoptimized.push(origin);
  5140. }
  5141. return expression;
  5142. }
  5143. }
  5144. const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
  5145. // This makes sure unknown properties are not handled as "undefined" but as
  5146. // "unknown" but without access side effects. An exception is done for numeric
  5147. // properties as we do not expect new builtin properties to be numbers, this
  5148. // will improve tree-shaking for out-of-bounds array properties
  5149. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  5150. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  5151. if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  5152. thisArg.deoptimizePath(UNKNOWN_PATH);
  5153. }
  5154. }
  5155. getLiteralValueAtPath(path) {
  5156. // We ignore number properties as we do not expect new properties to be
  5157. // numbers and also want to keep handling out-of-bound array elements as
  5158. // "undefined"
  5159. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  5160. }
  5161. hasEffectsOnInteractionAtPath(path, { type }) {
  5162. return path.length > 1 || type === INTERACTION_CALLED;
  5163. }
  5164. })();
  5165. const OBJECT_PROTOTYPE = new ObjectEntity({
  5166. __proto__: null,
  5167. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  5168. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  5169. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  5170. toLocaleString: METHOD_RETURNS_STRING,
  5171. toString: METHOD_RETURNS_STRING,
  5172. valueOf: METHOD_RETURNS_UNKNOWN
  5173. }, OBJECT_PROTOTYPE_FALLBACK, true);
  5174. const NEW_ARRAY_PROPERTIES = [
  5175. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5176. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5177. ];
  5178. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5179. new Method({
  5180. callsArgs: [0],
  5181. mutatesSelfAsArray: 'deopt-only',
  5182. returns: null,
  5183. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5184. })
  5185. ];
  5186. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5187. new Method({
  5188. callsArgs: [0],
  5189. mutatesSelfAsArray: 'deopt-only',
  5190. returns: null,
  5191. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5192. })
  5193. ];
  5194. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5195. new Method({
  5196. callsArgs: null,
  5197. mutatesSelfAsArray: true,
  5198. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5199. returnsPrimitive: null
  5200. })
  5201. ];
  5202. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5203. new Method({
  5204. callsArgs: null,
  5205. mutatesSelfAsArray: 'deopt-only',
  5206. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5207. returnsPrimitive: null
  5208. })
  5209. ];
  5210. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5211. new Method({
  5212. callsArgs: [0],
  5213. mutatesSelfAsArray: 'deopt-only',
  5214. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5215. returnsPrimitive: null
  5216. })
  5217. ];
  5218. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5219. new Method({
  5220. callsArgs: null,
  5221. mutatesSelfAsArray: true,
  5222. returns: null,
  5223. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5224. })
  5225. ];
  5226. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5227. new Method({
  5228. callsArgs: null,
  5229. mutatesSelfAsArray: true,
  5230. returns: null,
  5231. returnsPrimitive: UNKNOWN_EXPRESSION
  5232. })
  5233. ];
  5234. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5235. new Method({
  5236. callsArgs: null,
  5237. mutatesSelfAsArray: 'deopt-only',
  5238. returns: null,
  5239. returnsPrimitive: UNKNOWN_EXPRESSION
  5240. })
  5241. ];
  5242. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5243. new Method({
  5244. callsArgs: [0],
  5245. mutatesSelfAsArray: 'deopt-only',
  5246. returns: null,
  5247. returnsPrimitive: UNKNOWN_EXPRESSION
  5248. })
  5249. ];
  5250. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5251. new Method({
  5252. callsArgs: null,
  5253. mutatesSelfAsArray: true,
  5254. returns: 'self',
  5255. returnsPrimitive: null
  5256. })
  5257. ];
  5258. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5259. new Method({
  5260. callsArgs: [0],
  5261. mutatesSelfAsArray: true,
  5262. returns: 'self',
  5263. returnsPrimitive: null
  5264. })
  5265. ];
  5266. const ARRAY_PROTOTYPE = new ObjectEntity({
  5267. __proto__: null,
  5268. // We assume that accessors have effects as we do not track the accessed value afterwards
  5269. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5270. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5271. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5272. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5273. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5274. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5275. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5276. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5277. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5278. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5279. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5280. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5281. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5282. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5283. group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5284. groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5285. includes: METHOD_RETURNS_BOOLEAN,
  5286. indexOf: METHOD_RETURNS_NUMBER,
  5287. join: METHOD_RETURNS_STRING,
  5288. keys: METHOD_RETURNS_UNKNOWN,
  5289. lastIndexOf: METHOD_RETURNS_NUMBER,
  5290. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5291. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5292. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5293. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5294. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5295. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5296. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5297. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5298. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5299. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5300. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5301. toLocaleString: METHOD_RETURNS_STRING,
  5302. toString: METHOD_RETURNS_STRING,
  5303. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5304. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5305. }, OBJECT_PROTOTYPE, true);
  5306. class ArrayExpression extends NodeBase {
  5307. constructor() {
  5308. super(...arguments);
  5309. this.objectEntity = null;
  5310. }
  5311. deoptimizePath(path) {
  5312. this.getObjectEntity().deoptimizePath(path);
  5313. }
  5314. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5315. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5316. }
  5317. getLiteralValueAtPath(path, recursionTracker, origin) {
  5318. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5319. }
  5320. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5321. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5322. }
  5323. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5324. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5325. }
  5326. applyDeoptimizations() {
  5327. this.deoptimized = true;
  5328. let hasSpread = false;
  5329. for (let index = 0; index < this.elements.length; index++) {
  5330. const element = this.elements[index];
  5331. if (element) {
  5332. if (hasSpread || element instanceof SpreadElement) {
  5333. hasSpread = true;
  5334. element.deoptimizePath(UNKNOWN_PATH);
  5335. }
  5336. }
  5337. }
  5338. this.context.requestTreeshakingPass();
  5339. }
  5340. getObjectEntity() {
  5341. if (this.objectEntity !== null) {
  5342. return this.objectEntity;
  5343. }
  5344. const properties = [
  5345. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5346. ];
  5347. let hasSpread = false;
  5348. for (let index = 0; index < this.elements.length; index++) {
  5349. const element = this.elements[index];
  5350. if (hasSpread || element instanceof SpreadElement) {
  5351. if (element) {
  5352. hasSpread = true;
  5353. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5354. }
  5355. }
  5356. else if (!element) {
  5357. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5358. }
  5359. else {
  5360. properties.push({ key: String(index), kind: 'init', property: element });
  5361. }
  5362. }
  5363. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5364. }
  5365. }
  5366. class ArrayPattern extends NodeBase {
  5367. addExportedVariables(variables, exportNamesByVariable) {
  5368. for (const element of this.elements) {
  5369. element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
  5370. }
  5371. }
  5372. declare(kind) {
  5373. const variables = [];
  5374. for (const element of this.elements) {
  5375. if (element !== null) {
  5376. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5377. }
  5378. }
  5379. return variables;
  5380. }
  5381. // Patterns can only be deoptimized at the empty path at the moment
  5382. deoptimizePath() {
  5383. for (const element of this.elements) {
  5384. element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
  5385. }
  5386. }
  5387. // Patterns are only checked at the emtpy path at the moment
  5388. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  5389. for (const element of this.elements) {
  5390. if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  5391. return true;
  5392. }
  5393. return false;
  5394. }
  5395. markDeclarationReached() {
  5396. for (const element of this.elements) {
  5397. element === null || element === void 0 ? void 0 : element.markDeclarationReached();
  5398. }
  5399. }
  5400. }
  5401. class LocalVariable extends Variable {
  5402. constructor(name, declarator, init, context) {
  5403. super(name);
  5404. this.calledFromTryStatement = false;
  5405. this.additionalInitializers = null;
  5406. this.expressionsToBeDeoptimized = [];
  5407. this.declarations = declarator ? [declarator] : [];
  5408. this.init = init;
  5409. this.deoptimizationTracker = context.deoptimizationTracker;
  5410. this.module = context.module;
  5411. }
  5412. addDeclaration(identifier, init) {
  5413. this.declarations.push(identifier);
  5414. const additionalInitializers = this.markInitializersForDeoptimization();
  5415. if (init !== null) {
  5416. additionalInitializers.push(init);
  5417. }
  5418. }
  5419. consolidateInitializers() {
  5420. if (this.additionalInitializers !== null) {
  5421. for (const initializer of this.additionalInitializers) {
  5422. initializer.deoptimizePath(UNKNOWN_PATH);
  5423. }
  5424. this.additionalInitializers = null;
  5425. }
  5426. }
  5427. deoptimizePath(path) {
  5428. var _a, _b;
  5429. if (this.isReassigned ||
  5430. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5431. return;
  5432. }
  5433. if (path.length === 0) {
  5434. if (!this.isReassigned) {
  5435. this.isReassigned = true;
  5436. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  5437. this.expressionsToBeDeoptimized = [];
  5438. for (const expression of expressionsToBeDeoptimized) {
  5439. expression.deoptimizeCache();
  5440. }
  5441. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  5442. }
  5443. }
  5444. else {
  5445. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  5446. }
  5447. }
  5448. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5449. if (this.isReassigned || !this.init) {
  5450. return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5451. }
  5452. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  5453. }
  5454. getLiteralValueAtPath(path, recursionTracker, origin) {
  5455. if (this.isReassigned || !this.init) {
  5456. return UnknownValue;
  5457. }
  5458. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5459. this.expressionsToBeDeoptimized.push(origin);
  5460. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5461. }, UnknownValue);
  5462. }
  5463. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5464. if (this.isReassigned || !this.init) {
  5465. return UNKNOWN_EXPRESSION;
  5466. }
  5467. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5468. this.expressionsToBeDeoptimized.push(origin);
  5469. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5470. }, UNKNOWN_EXPRESSION);
  5471. }
  5472. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5473. switch (interaction.type) {
  5474. case INTERACTION_ACCESSED:
  5475. if (this.isReassigned)
  5476. return true;
  5477. return (this.init &&
  5478. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5479. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5480. case INTERACTION_ASSIGNED:
  5481. if (this.included)
  5482. return true;
  5483. if (path.length === 0)
  5484. return false;
  5485. if (this.isReassigned)
  5486. return true;
  5487. return (this.init &&
  5488. !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5489. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5490. case INTERACTION_CALLED:
  5491. if (this.isReassigned)
  5492. return true;
  5493. return (this.init &&
  5494. !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5495. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5496. }
  5497. }
  5498. include() {
  5499. if (!this.included) {
  5500. this.included = true;
  5501. for (const declaration of this.declarations) {
  5502. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5503. if (!declaration.included)
  5504. declaration.include(createInclusionContext(), false);
  5505. let node = declaration.parent;
  5506. while (!node.included) {
  5507. // We do not want to properly include parents in case they are part of a dead branch
  5508. // in which case .include() might pull in more dead code
  5509. node.included = true;
  5510. if (node.type === Program$1)
  5511. break;
  5512. node = node.parent;
  5513. }
  5514. }
  5515. }
  5516. }
  5517. includeCallArguments(context, args) {
  5518. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  5519. for (const arg of args) {
  5520. arg.include(context, false);
  5521. }
  5522. }
  5523. else if (this.init) {
  5524. context.includedCallArguments.add(this.init);
  5525. this.init.includeCallArguments(context, args);
  5526. context.includedCallArguments.delete(this.init);
  5527. }
  5528. }
  5529. markCalledFromTryStatement() {
  5530. this.calledFromTryStatement = true;
  5531. }
  5532. markInitializersForDeoptimization() {
  5533. if (this.additionalInitializers === null) {
  5534. this.additionalInitializers = this.init === null ? [] : [this.init];
  5535. this.init = UNKNOWN_EXPRESSION;
  5536. this.isReassigned = true;
  5537. }
  5538. return this.additionalInitializers;
  5539. }
  5540. }
  5541. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5542. const base = 64;
  5543. function toBase64(num) {
  5544. let outStr = '';
  5545. do {
  5546. const curDigit = num % base;
  5547. num = Math.floor(num / base);
  5548. outStr = chars[curDigit] + outStr;
  5549. } while (num !== 0);
  5550. return outStr;
  5551. }
  5552. function getSafeName(baseName, usedNames) {
  5553. let safeName = baseName;
  5554. let count = 1;
  5555. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
  5556. safeName = `${baseName}$${toBase64(count++)}`;
  5557. }
  5558. usedNames.add(safeName);
  5559. return safeName;
  5560. }
  5561. class Scope$1 {
  5562. constructor() {
  5563. this.children = [];
  5564. this.variables = new Map();
  5565. }
  5566. addDeclaration(identifier, context, init, _isHoisted) {
  5567. const name = identifier.name;
  5568. let variable = this.variables.get(name);
  5569. if (variable) {
  5570. variable.addDeclaration(identifier, init);
  5571. }
  5572. else {
  5573. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  5574. this.variables.set(name, variable);
  5575. }
  5576. return variable;
  5577. }
  5578. contains(name) {
  5579. return this.variables.has(name);
  5580. }
  5581. findVariable(_name) {
  5582. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5583. }
  5584. }
  5585. class ChildScope extends Scope$1 {
  5586. constructor(parent) {
  5587. super();
  5588. this.accessedOutsideVariables = new Map();
  5589. this.parent = parent;
  5590. parent.children.push(this);
  5591. }
  5592. addAccessedDynamicImport(importExpression) {
  5593. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5594. if (this.parent instanceof ChildScope) {
  5595. this.parent.addAccessedDynamicImport(importExpression);
  5596. }
  5597. }
  5598. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5599. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5600. for (const name of globals) {
  5601. accessedGlobals.add(name);
  5602. }
  5603. accessedGlobalsByScope.set(this, accessedGlobals);
  5604. if (this.parent instanceof ChildScope) {
  5605. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5606. }
  5607. }
  5608. addNamespaceMemberAccess(name, variable) {
  5609. this.accessedOutsideVariables.set(name, variable);
  5610. this.parent.addNamespaceMemberAccess(name, variable);
  5611. }
  5612. addReturnExpression(expression) {
  5613. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  5614. }
  5615. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5616. for (const variable of this.accessedOutsideVariables.values()) {
  5617. if (variable.included) {
  5618. usedNames.add(variable.getBaseVariableName());
  5619. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5620. usedNames.add('exports');
  5621. }
  5622. }
  5623. }
  5624. const accessedGlobals = accessedGlobalsByScope.get(this);
  5625. if (accessedGlobals) {
  5626. for (const name of accessedGlobals) {
  5627. usedNames.add(name);
  5628. }
  5629. }
  5630. }
  5631. contains(name) {
  5632. return this.variables.has(name) || this.parent.contains(name);
  5633. }
  5634. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5635. const usedNames = new Set();
  5636. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5637. if (this.accessedDynamicImports) {
  5638. for (const importExpression of this.accessedDynamicImports) {
  5639. if (importExpression.inlineNamespace) {
  5640. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5641. }
  5642. }
  5643. }
  5644. for (const [name, variable] of this.variables) {
  5645. if (variable.included || variable.alwaysRendered) {
  5646. variable.setRenderNames(null, getSafeName(name, usedNames));
  5647. }
  5648. }
  5649. for (const scope of this.children) {
  5650. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5651. }
  5652. }
  5653. findLexicalBoundary() {
  5654. return this.parent.findLexicalBoundary();
  5655. }
  5656. findVariable(name) {
  5657. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5658. if (knownVariable) {
  5659. return knownVariable;
  5660. }
  5661. const variable = this.parent.findVariable(name);
  5662. this.accessedOutsideVariables.set(name, variable);
  5663. return variable;
  5664. }
  5665. }
  5666. class ParameterScope extends ChildScope {
  5667. constructor(parent, context) {
  5668. super(parent);
  5669. this.parameters = [];
  5670. this.hasRest = false;
  5671. this.context = context;
  5672. this.hoistedBodyVarScope = new ChildScope(this);
  5673. }
  5674. /**
  5675. * Adds a parameter to this scope. Parameters must be added in the correct
  5676. * order, e.g. from left to right.
  5677. */
  5678. addParameterDeclaration(identifier) {
  5679. const name = identifier.name;
  5680. let variable = this.hoistedBodyVarScope.variables.get(name);
  5681. if (variable) {
  5682. variable.addDeclaration(identifier, null);
  5683. }
  5684. else {
  5685. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  5686. }
  5687. this.variables.set(name, variable);
  5688. return variable;
  5689. }
  5690. addParameterVariables(parameters, hasRest) {
  5691. this.parameters = parameters;
  5692. for (const parameterList of parameters) {
  5693. for (const parameter of parameterList) {
  5694. parameter.alwaysRendered = true;
  5695. }
  5696. }
  5697. this.hasRest = hasRest;
  5698. }
  5699. includeCallArguments(context, args) {
  5700. let calledFromTryStatement = false;
  5701. let argIncluded = false;
  5702. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  5703. for (const checkedArg of args) {
  5704. if (checkedArg instanceof SpreadElement) {
  5705. for (const arg of args) {
  5706. arg.include(context, false);
  5707. }
  5708. break;
  5709. }
  5710. }
  5711. for (let index = args.length - 1; index >= 0; index--) {
  5712. const paramVars = this.parameters[index] || restParam;
  5713. const arg = args[index];
  5714. if (paramVars) {
  5715. calledFromTryStatement = false;
  5716. if (paramVars.length === 0) {
  5717. // handle empty destructuring
  5718. argIncluded = true;
  5719. }
  5720. else {
  5721. for (const variable of paramVars) {
  5722. if (variable.included) {
  5723. argIncluded = true;
  5724. }
  5725. if (variable.calledFromTryStatement) {
  5726. calledFromTryStatement = true;
  5727. }
  5728. }
  5729. }
  5730. }
  5731. if (!argIncluded && arg.shouldBeIncluded(context)) {
  5732. argIncluded = true;
  5733. }
  5734. if (argIncluded) {
  5735. arg.include(context, calledFromTryStatement);
  5736. }
  5737. }
  5738. }
  5739. }
  5740. class ReturnValueScope extends ParameterScope {
  5741. constructor() {
  5742. super(...arguments);
  5743. this.returnExpression = null;
  5744. this.returnExpressions = [];
  5745. }
  5746. addReturnExpression(expression) {
  5747. this.returnExpressions.push(expression);
  5748. }
  5749. getReturnExpression() {
  5750. if (this.returnExpression === null)
  5751. this.updateReturnExpression();
  5752. return this.returnExpression;
  5753. }
  5754. updateReturnExpression() {
  5755. if (this.returnExpressions.length === 1) {
  5756. this.returnExpression = this.returnExpressions[0];
  5757. }
  5758. else {
  5759. this.returnExpression = UNKNOWN_EXPRESSION;
  5760. for (const expression of this.returnExpressions) {
  5761. expression.deoptimizePath(UNKNOWN_PATH);
  5762. }
  5763. }
  5764. }
  5765. }
  5766. //@ts-check
  5767. /** @typedef { import('estree').Node} Node */
  5768. /** @typedef {Node | {
  5769. * type: 'PropertyDefinition';
  5770. * computed: boolean;
  5771. * value: Node
  5772. * }} NodeWithPropertyDefinition */
  5773. /**
  5774. *
  5775. * @param {NodeWithPropertyDefinition} node
  5776. * @param {NodeWithPropertyDefinition} parent
  5777. * @returns boolean
  5778. */
  5779. function is_reference (node, parent) {
  5780. if (node.type === 'MemberExpression') {
  5781. return !node.computed && is_reference(node.object, node);
  5782. }
  5783. if (node.type === 'Identifier') {
  5784. if (!parent) return true;
  5785. switch (parent.type) {
  5786. // disregard `bar` in `foo.bar`
  5787. case 'MemberExpression': return parent.computed || node === parent.object;
  5788. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5789. case 'MethodDefinition': return parent.computed;
  5790. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5791. case 'PropertyDefinition': return parent.computed || node === parent.value;
  5792. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5793. case 'Property': return parent.computed || node === parent.value;
  5794. // disregard the `bar` in `export { foo as bar }` or
  5795. // the foo in `import { foo as bar }`
  5796. case 'ExportSpecifier':
  5797. case 'ImportSpecifier': return node === parent.local;
  5798. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5799. case 'LabeledStatement':
  5800. case 'BreakStatement':
  5801. case 'ContinueStatement': return false;
  5802. default: return true;
  5803. }
  5804. }
  5805. return false;
  5806. }
  5807. /* eslint sort-keys: "off" */
  5808. const ValueProperties = Symbol('Value Properties');
  5809. const PURE = {
  5810. hasEffectsWhenCalled() {
  5811. return false;
  5812. }
  5813. };
  5814. const IMPURE = {
  5815. hasEffectsWhenCalled() {
  5816. return true;
  5817. }
  5818. };
  5819. // We use shortened variables to reduce file size here
  5820. /* OBJECT */
  5821. const O = {
  5822. __proto__: null,
  5823. [ValueProperties]: IMPURE
  5824. };
  5825. /* PURE FUNCTION */
  5826. const PF = {
  5827. __proto__: null,
  5828. [ValueProperties]: PURE
  5829. };
  5830. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5831. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5832. __proto__: null,
  5833. [ValueProperties]: {
  5834. hasEffectsWhenCalled({ args }, context) {
  5835. return (!args.length ||
  5836. args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5837. }
  5838. }
  5839. };
  5840. /* CONSTRUCTOR */
  5841. const C = {
  5842. __proto__: null,
  5843. [ValueProperties]: IMPURE,
  5844. prototype: O
  5845. };
  5846. /* PURE CONSTRUCTOR */
  5847. const PC = {
  5848. __proto__: null,
  5849. [ValueProperties]: PURE,
  5850. prototype: O
  5851. };
  5852. const ARRAY_TYPE = {
  5853. __proto__: null,
  5854. [ValueProperties]: PURE,
  5855. from: PF,
  5856. of: PF,
  5857. prototype: O
  5858. };
  5859. const INTL_MEMBER = {
  5860. __proto__: null,
  5861. [ValueProperties]: PURE,
  5862. supportedLocalesOf: PC
  5863. };
  5864. const knownGlobals = {
  5865. // Placeholders for global objects to avoid shape mutations
  5866. global: O,
  5867. globalThis: O,
  5868. self: O,
  5869. window: O,
  5870. // Common globals
  5871. __proto__: null,
  5872. [ValueProperties]: IMPURE,
  5873. Array: {
  5874. __proto__: null,
  5875. [ValueProperties]: IMPURE,
  5876. from: O,
  5877. isArray: PF,
  5878. of: PF,
  5879. prototype: O
  5880. },
  5881. ArrayBuffer: {
  5882. __proto__: null,
  5883. [ValueProperties]: PURE,
  5884. isView: PF,
  5885. prototype: O
  5886. },
  5887. Atomics: O,
  5888. BigInt: C,
  5889. BigInt64Array: C,
  5890. BigUint64Array: C,
  5891. Boolean: PC,
  5892. constructor: C,
  5893. DataView: PC,
  5894. Date: {
  5895. __proto__: null,
  5896. [ValueProperties]: PURE,
  5897. now: PF,
  5898. parse: PF,
  5899. prototype: O,
  5900. UTC: PF
  5901. },
  5902. decodeURI: PF,
  5903. decodeURIComponent: PF,
  5904. encodeURI: PF,
  5905. encodeURIComponent: PF,
  5906. Error: PC,
  5907. escape: PF,
  5908. eval: O,
  5909. EvalError: PC,
  5910. Float32Array: ARRAY_TYPE,
  5911. Float64Array: ARRAY_TYPE,
  5912. Function: C,
  5913. hasOwnProperty: O,
  5914. Infinity: O,
  5915. Int16Array: ARRAY_TYPE,
  5916. Int32Array: ARRAY_TYPE,
  5917. Int8Array: ARRAY_TYPE,
  5918. isFinite: PF,
  5919. isNaN: PF,
  5920. isPrototypeOf: O,
  5921. JSON: O,
  5922. Map: PC,
  5923. Math: {
  5924. __proto__: null,
  5925. [ValueProperties]: IMPURE,
  5926. abs: PF,
  5927. acos: PF,
  5928. acosh: PF,
  5929. asin: PF,
  5930. asinh: PF,
  5931. atan: PF,
  5932. atan2: PF,
  5933. atanh: PF,
  5934. cbrt: PF,
  5935. ceil: PF,
  5936. clz32: PF,
  5937. cos: PF,
  5938. cosh: PF,
  5939. exp: PF,
  5940. expm1: PF,
  5941. floor: PF,
  5942. fround: PF,
  5943. hypot: PF,
  5944. imul: PF,
  5945. log: PF,
  5946. log10: PF,
  5947. log1p: PF,
  5948. log2: PF,
  5949. max: PF,
  5950. min: PF,
  5951. pow: PF,
  5952. random: PF,
  5953. round: PF,
  5954. sign: PF,
  5955. sin: PF,
  5956. sinh: PF,
  5957. sqrt: PF,
  5958. tan: PF,
  5959. tanh: PF,
  5960. trunc: PF
  5961. },
  5962. NaN: O,
  5963. Number: {
  5964. __proto__: null,
  5965. [ValueProperties]: PURE,
  5966. isFinite: PF,
  5967. isInteger: PF,
  5968. isNaN: PF,
  5969. isSafeInteger: PF,
  5970. parseFloat: PF,
  5971. parseInt: PF,
  5972. prototype: O
  5973. },
  5974. Object: {
  5975. __proto__: null,
  5976. [ValueProperties]: PURE,
  5977. create: PF,
  5978. // Technically those can throw in certain situations, but we ignore this as
  5979. // code that relies on this will hopefully wrap this in a try-catch, which
  5980. // deoptimizes everything anyway
  5981. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  5982. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  5983. getOwnPropertyDescriptor: PF,
  5984. getOwnPropertyNames: PF,
  5985. getOwnPropertySymbols: PF,
  5986. getPrototypeOf: PF,
  5987. hasOwn: PF,
  5988. is: PF,
  5989. isExtensible: PF,
  5990. isFrozen: PF,
  5991. isSealed: PF,
  5992. keys: PF,
  5993. fromEntries: PF,
  5994. entries: PF,
  5995. prototype: O
  5996. },
  5997. parseFloat: PF,
  5998. parseInt: PF,
  5999. Promise: {
  6000. __proto__: null,
  6001. [ValueProperties]: IMPURE,
  6002. all: O,
  6003. prototype: O,
  6004. race: O,
  6005. reject: O,
  6006. resolve: O
  6007. },
  6008. propertyIsEnumerable: O,
  6009. Proxy: O,
  6010. RangeError: PC,
  6011. ReferenceError: PC,
  6012. Reflect: O,
  6013. RegExp: PC,
  6014. Set: PC,
  6015. SharedArrayBuffer: C,
  6016. String: {
  6017. __proto__: null,
  6018. [ValueProperties]: PURE,
  6019. fromCharCode: PF,
  6020. fromCodePoint: PF,
  6021. prototype: O,
  6022. raw: PF
  6023. },
  6024. Symbol: {
  6025. __proto__: null,
  6026. [ValueProperties]: PURE,
  6027. for: PF,
  6028. keyFor: PF,
  6029. prototype: O
  6030. },
  6031. SyntaxError: PC,
  6032. toLocaleString: O,
  6033. toString: O,
  6034. TypeError: PC,
  6035. Uint16Array: ARRAY_TYPE,
  6036. Uint32Array: ARRAY_TYPE,
  6037. Uint8Array: ARRAY_TYPE,
  6038. Uint8ClampedArray: ARRAY_TYPE,
  6039. // Technically, this is a global, but it needs special handling
  6040. // undefined: ?,
  6041. unescape: PF,
  6042. URIError: PC,
  6043. valueOf: O,
  6044. WeakMap: PC,
  6045. WeakSet: PC,
  6046. // Additional globals shared by Node and Browser that are not strictly part of the language
  6047. clearInterval: C,
  6048. clearTimeout: C,
  6049. console: O,
  6050. Intl: {
  6051. __proto__: null,
  6052. [ValueProperties]: IMPURE,
  6053. Collator: INTL_MEMBER,
  6054. DateTimeFormat: INTL_MEMBER,
  6055. ListFormat: INTL_MEMBER,
  6056. NumberFormat: INTL_MEMBER,
  6057. PluralRules: INTL_MEMBER,
  6058. RelativeTimeFormat: INTL_MEMBER
  6059. },
  6060. setInterval: C,
  6061. setTimeout: C,
  6062. TextDecoder: C,
  6063. TextEncoder: C,
  6064. URL: C,
  6065. URLSearchParams: C,
  6066. // Browser specific globals
  6067. AbortController: C,
  6068. AbortSignal: C,
  6069. addEventListener: O,
  6070. alert: O,
  6071. AnalyserNode: C,
  6072. Animation: C,
  6073. AnimationEvent: C,
  6074. applicationCache: O,
  6075. ApplicationCache: C,
  6076. ApplicationCacheErrorEvent: C,
  6077. atob: O,
  6078. Attr: C,
  6079. Audio: C,
  6080. AudioBuffer: C,
  6081. AudioBufferSourceNode: C,
  6082. AudioContext: C,
  6083. AudioDestinationNode: C,
  6084. AudioListener: C,
  6085. AudioNode: C,
  6086. AudioParam: C,
  6087. AudioProcessingEvent: C,
  6088. AudioScheduledSourceNode: C,
  6089. AudioWorkletNode: C,
  6090. BarProp: C,
  6091. BaseAudioContext: C,
  6092. BatteryManager: C,
  6093. BeforeUnloadEvent: C,
  6094. BiquadFilterNode: C,
  6095. Blob: C,
  6096. BlobEvent: C,
  6097. blur: O,
  6098. BroadcastChannel: C,
  6099. btoa: O,
  6100. ByteLengthQueuingStrategy: C,
  6101. Cache: C,
  6102. caches: O,
  6103. CacheStorage: C,
  6104. cancelAnimationFrame: O,
  6105. cancelIdleCallback: O,
  6106. CanvasCaptureMediaStreamTrack: C,
  6107. CanvasGradient: C,
  6108. CanvasPattern: C,
  6109. CanvasRenderingContext2D: C,
  6110. ChannelMergerNode: C,
  6111. ChannelSplitterNode: C,
  6112. CharacterData: C,
  6113. clientInformation: O,
  6114. ClipboardEvent: C,
  6115. close: O,
  6116. closed: O,
  6117. CloseEvent: C,
  6118. Comment: C,
  6119. CompositionEvent: C,
  6120. confirm: O,
  6121. ConstantSourceNode: C,
  6122. ConvolverNode: C,
  6123. CountQueuingStrategy: C,
  6124. createImageBitmap: O,
  6125. Credential: C,
  6126. CredentialsContainer: C,
  6127. crypto: O,
  6128. Crypto: C,
  6129. CryptoKey: C,
  6130. CSS: C,
  6131. CSSConditionRule: C,
  6132. CSSFontFaceRule: C,
  6133. CSSGroupingRule: C,
  6134. CSSImportRule: C,
  6135. CSSKeyframeRule: C,
  6136. CSSKeyframesRule: C,
  6137. CSSMediaRule: C,
  6138. CSSNamespaceRule: C,
  6139. CSSPageRule: C,
  6140. CSSRule: C,
  6141. CSSRuleList: C,
  6142. CSSStyleDeclaration: C,
  6143. CSSStyleRule: C,
  6144. CSSStyleSheet: C,
  6145. CSSSupportsRule: C,
  6146. CustomElementRegistry: C,
  6147. customElements: O,
  6148. CustomEvent: C,
  6149. DataTransfer: C,
  6150. DataTransferItem: C,
  6151. DataTransferItemList: C,
  6152. defaultstatus: O,
  6153. defaultStatus: O,
  6154. DelayNode: C,
  6155. DeviceMotionEvent: C,
  6156. DeviceOrientationEvent: C,
  6157. devicePixelRatio: O,
  6158. dispatchEvent: O,
  6159. document: O,
  6160. Document: C,
  6161. DocumentFragment: C,
  6162. DocumentType: C,
  6163. DOMError: C,
  6164. DOMException: C,
  6165. DOMImplementation: C,
  6166. DOMMatrix: C,
  6167. DOMMatrixReadOnly: C,
  6168. DOMParser: C,
  6169. DOMPoint: C,
  6170. DOMPointReadOnly: C,
  6171. DOMQuad: C,
  6172. DOMRect: C,
  6173. DOMRectReadOnly: C,
  6174. DOMStringList: C,
  6175. DOMStringMap: C,
  6176. DOMTokenList: C,
  6177. DragEvent: C,
  6178. DynamicsCompressorNode: C,
  6179. Element: C,
  6180. ErrorEvent: C,
  6181. Event: C,
  6182. EventSource: C,
  6183. EventTarget: C,
  6184. external: O,
  6185. fetch: O,
  6186. File: C,
  6187. FileList: C,
  6188. FileReader: C,
  6189. find: O,
  6190. focus: O,
  6191. FocusEvent: C,
  6192. FontFace: C,
  6193. FontFaceSetLoadEvent: C,
  6194. FormData: C,
  6195. frames: O,
  6196. GainNode: C,
  6197. Gamepad: C,
  6198. GamepadButton: C,
  6199. GamepadEvent: C,
  6200. getComputedStyle: O,
  6201. getSelection: O,
  6202. HashChangeEvent: C,
  6203. Headers: C,
  6204. history: O,
  6205. History: C,
  6206. HTMLAllCollection: C,
  6207. HTMLAnchorElement: C,
  6208. HTMLAreaElement: C,
  6209. HTMLAudioElement: C,
  6210. HTMLBaseElement: C,
  6211. HTMLBodyElement: C,
  6212. HTMLBRElement: C,
  6213. HTMLButtonElement: C,
  6214. HTMLCanvasElement: C,
  6215. HTMLCollection: C,
  6216. HTMLContentElement: C,
  6217. HTMLDataElement: C,
  6218. HTMLDataListElement: C,
  6219. HTMLDetailsElement: C,
  6220. HTMLDialogElement: C,
  6221. HTMLDirectoryElement: C,
  6222. HTMLDivElement: C,
  6223. HTMLDListElement: C,
  6224. HTMLDocument: C,
  6225. HTMLElement: C,
  6226. HTMLEmbedElement: C,
  6227. HTMLFieldSetElement: C,
  6228. HTMLFontElement: C,
  6229. HTMLFormControlsCollection: C,
  6230. HTMLFormElement: C,
  6231. HTMLFrameElement: C,
  6232. HTMLFrameSetElement: C,
  6233. HTMLHeadElement: C,
  6234. HTMLHeadingElement: C,
  6235. HTMLHRElement: C,
  6236. HTMLHtmlElement: C,
  6237. HTMLIFrameElement: C,
  6238. HTMLImageElement: C,
  6239. HTMLInputElement: C,
  6240. HTMLLabelElement: C,
  6241. HTMLLegendElement: C,
  6242. HTMLLIElement: C,
  6243. HTMLLinkElement: C,
  6244. HTMLMapElement: C,
  6245. HTMLMarqueeElement: C,
  6246. HTMLMediaElement: C,
  6247. HTMLMenuElement: C,
  6248. HTMLMetaElement: C,
  6249. HTMLMeterElement: C,
  6250. HTMLModElement: C,
  6251. HTMLObjectElement: C,
  6252. HTMLOListElement: C,
  6253. HTMLOptGroupElement: C,
  6254. HTMLOptionElement: C,
  6255. HTMLOptionsCollection: C,
  6256. HTMLOutputElement: C,
  6257. HTMLParagraphElement: C,
  6258. HTMLParamElement: C,
  6259. HTMLPictureElement: C,
  6260. HTMLPreElement: C,
  6261. HTMLProgressElement: C,
  6262. HTMLQuoteElement: C,
  6263. HTMLScriptElement: C,
  6264. HTMLSelectElement: C,
  6265. HTMLShadowElement: C,
  6266. HTMLSlotElement: C,
  6267. HTMLSourceElement: C,
  6268. HTMLSpanElement: C,
  6269. HTMLStyleElement: C,
  6270. HTMLTableCaptionElement: C,
  6271. HTMLTableCellElement: C,
  6272. HTMLTableColElement: C,
  6273. HTMLTableElement: C,
  6274. HTMLTableRowElement: C,
  6275. HTMLTableSectionElement: C,
  6276. HTMLTemplateElement: C,
  6277. HTMLTextAreaElement: C,
  6278. HTMLTimeElement: C,
  6279. HTMLTitleElement: C,
  6280. HTMLTrackElement: C,
  6281. HTMLUListElement: C,
  6282. HTMLUnknownElement: C,
  6283. HTMLVideoElement: C,
  6284. IDBCursor: C,
  6285. IDBCursorWithValue: C,
  6286. IDBDatabase: C,
  6287. IDBFactory: C,
  6288. IDBIndex: C,
  6289. IDBKeyRange: C,
  6290. IDBObjectStore: C,
  6291. IDBOpenDBRequest: C,
  6292. IDBRequest: C,
  6293. IDBTransaction: C,
  6294. IDBVersionChangeEvent: C,
  6295. IdleDeadline: C,
  6296. IIRFilterNode: C,
  6297. Image: C,
  6298. ImageBitmap: C,
  6299. ImageBitmapRenderingContext: C,
  6300. ImageCapture: C,
  6301. ImageData: C,
  6302. indexedDB: O,
  6303. innerHeight: O,
  6304. innerWidth: O,
  6305. InputEvent: C,
  6306. IntersectionObserver: C,
  6307. IntersectionObserverEntry: C,
  6308. isSecureContext: O,
  6309. KeyboardEvent: C,
  6310. KeyframeEffect: C,
  6311. length: O,
  6312. localStorage: O,
  6313. location: O,
  6314. Location: C,
  6315. locationbar: O,
  6316. matchMedia: O,
  6317. MediaDeviceInfo: C,
  6318. MediaDevices: C,
  6319. MediaElementAudioSourceNode: C,
  6320. MediaEncryptedEvent: C,
  6321. MediaError: C,
  6322. MediaKeyMessageEvent: C,
  6323. MediaKeySession: C,
  6324. MediaKeyStatusMap: C,
  6325. MediaKeySystemAccess: C,
  6326. MediaList: C,
  6327. MediaQueryList: C,
  6328. MediaQueryListEvent: C,
  6329. MediaRecorder: C,
  6330. MediaSettingsRange: C,
  6331. MediaSource: C,
  6332. MediaStream: C,
  6333. MediaStreamAudioDestinationNode: C,
  6334. MediaStreamAudioSourceNode: C,
  6335. MediaStreamEvent: C,
  6336. MediaStreamTrack: C,
  6337. MediaStreamTrackEvent: C,
  6338. menubar: O,
  6339. MessageChannel: C,
  6340. MessageEvent: C,
  6341. MessagePort: C,
  6342. MIDIAccess: C,
  6343. MIDIConnectionEvent: C,
  6344. MIDIInput: C,
  6345. MIDIInputMap: C,
  6346. MIDIMessageEvent: C,
  6347. MIDIOutput: C,
  6348. MIDIOutputMap: C,
  6349. MIDIPort: C,
  6350. MimeType: C,
  6351. MimeTypeArray: C,
  6352. MouseEvent: C,
  6353. moveBy: O,
  6354. moveTo: O,
  6355. MutationEvent: C,
  6356. MutationObserver: C,
  6357. MutationRecord: C,
  6358. name: O,
  6359. NamedNodeMap: C,
  6360. NavigationPreloadManager: C,
  6361. navigator: O,
  6362. Navigator: C,
  6363. NetworkInformation: C,
  6364. Node: C,
  6365. NodeFilter: O,
  6366. NodeIterator: C,
  6367. NodeList: C,
  6368. Notification: C,
  6369. OfflineAudioCompletionEvent: C,
  6370. OfflineAudioContext: C,
  6371. offscreenBuffering: O,
  6372. OffscreenCanvas: C,
  6373. open: O,
  6374. openDatabase: O,
  6375. Option: C,
  6376. origin: O,
  6377. OscillatorNode: C,
  6378. outerHeight: O,
  6379. outerWidth: O,
  6380. PageTransitionEvent: C,
  6381. pageXOffset: O,
  6382. pageYOffset: O,
  6383. PannerNode: C,
  6384. parent: O,
  6385. Path2D: C,
  6386. PaymentAddress: C,
  6387. PaymentRequest: C,
  6388. PaymentRequestUpdateEvent: C,
  6389. PaymentResponse: C,
  6390. performance: O,
  6391. Performance: C,
  6392. PerformanceEntry: C,
  6393. PerformanceLongTaskTiming: C,
  6394. PerformanceMark: C,
  6395. PerformanceMeasure: C,
  6396. PerformanceNavigation: C,
  6397. PerformanceNavigationTiming: C,
  6398. PerformanceObserver: C,
  6399. PerformanceObserverEntryList: C,
  6400. PerformancePaintTiming: C,
  6401. PerformanceResourceTiming: C,
  6402. PerformanceTiming: C,
  6403. PeriodicWave: C,
  6404. Permissions: C,
  6405. PermissionStatus: C,
  6406. personalbar: O,
  6407. PhotoCapabilities: C,
  6408. Plugin: C,
  6409. PluginArray: C,
  6410. PointerEvent: C,
  6411. PopStateEvent: C,
  6412. postMessage: O,
  6413. Presentation: C,
  6414. PresentationAvailability: C,
  6415. PresentationConnection: C,
  6416. PresentationConnectionAvailableEvent: C,
  6417. PresentationConnectionCloseEvent: C,
  6418. PresentationConnectionList: C,
  6419. PresentationReceiver: C,
  6420. PresentationRequest: C,
  6421. print: O,
  6422. ProcessingInstruction: C,
  6423. ProgressEvent: C,
  6424. PromiseRejectionEvent: C,
  6425. prompt: O,
  6426. PushManager: C,
  6427. PushSubscription: C,
  6428. PushSubscriptionOptions: C,
  6429. queueMicrotask: O,
  6430. RadioNodeList: C,
  6431. Range: C,
  6432. ReadableStream: C,
  6433. RemotePlayback: C,
  6434. removeEventListener: O,
  6435. Request: C,
  6436. requestAnimationFrame: O,
  6437. requestIdleCallback: O,
  6438. resizeBy: O,
  6439. ResizeObserver: C,
  6440. ResizeObserverEntry: C,
  6441. resizeTo: O,
  6442. Response: C,
  6443. RTCCertificate: C,
  6444. RTCDataChannel: C,
  6445. RTCDataChannelEvent: C,
  6446. RTCDtlsTransport: C,
  6447. RTCIceCandidate: C,
  6448. RTCIceTransport: C,
  6449. RTCPeerConnection: C,
  6450. RTCPeerConnectionIceEvent: C,
  6451. RTCRtpReceiver: C,
  6452. RTCRtpSender: C,
  6453. RTCSctpTransport: C,
  6454. RTCSessionDescription: C,
  6455. RTCStatsReport: C,
  6456. RTCTrackEvent: C,
  6457. screen: O,
  6458. Screen: C,
  6459. screenLeft: O,
  6460. ScreenOrientation: C,
  6461. screenTop: O,
  6462. screenX: O,
  6463. screenY: O,
  6464. ScriptProcessorNode: C,
  6465. scroll: O,
  6466. scrollbars: O,
  6467. scrollBy: O,
  6468. scrollTo: O,
  6469. scrollX: O,
  6470. scrollY: O,
  6471. SecurityPolicyViolationEvent: C,
  6472. Selection: C,
  6473. ServiceWorker: C,
  6474. ServiceWorkerContainer: C,
  6475. ServiceWorkerRegistration: C,
  6476. sessionStorage: O,
  6477. ShadowRoot: C,
  6478. SharedWorker: C,
  6479. SourceBuffer: C,
  6480. SourceBufferList: C,
  6481. speechSynthesis: O,
  6482. SpeechSynthesisEvent: C,
  6483. SpeechSynthesisUtterance: C,
  6484. StaticRange: C,
  6485. status: O,
  6486. statusbar: O,
  6487. StereoPannerNode: C,
  6488. stop: O,
  6489. Storage: C,
  6490. StorageEvent: C,
  6491. StorageManager: C,
  6492. styleMedia: O,
  6493. StyleSheet: C,
  6494. StyleSheetList: C,
  6495. SubtleCrypto: C,
  6496. SVGAElement: C,
  6497. SVGAngle: C,
  6498. SVGAnimatedAngle: C,
  6499. SVGAnimatedBoolean: C,
  6500. SVGAnimatedEnumeration: C,
  6501. SVGAnimatedInteger: C,
  6502. SVGAnimatedLength: C,
  6503. SVGAnimatedLengthList: C,
  6504. SVGAnimatedNumber: C,
  6505. SVGAnimatedNumberList: C,
  6506. SVGAnimatedPreserveAspectRatio: C,
  6507. SVGAnimatedRect: C,
  6508. SVGAnimatedString: C,
  6509. SVGAnimatedTransformList: C,
  6510. SVGAnimateElement: C,
  6511. SVGAnimateMotionElement: C,
  6512. SVGAnimateTransformElement: C,
  6513. SVGAnimationElement: C,
  6514. SVGCircleElement: C,
  6515. SVGClipPathElement: C,
  6516. SVGComponentTransferFunctionElement: C,
  6517. SVGDefsElement: C,
  6518. SVGDescElement: C,
  6519. SVGDiscardElement: C,
  6520. SVGElement: C,
  6521. SVGEllipseElement: C,
  6522. SVGFEBlendElement: C,
  6523. SVGFEColorMatrixElement: C,
  6524. SVGFEComponentTransferElement: C,
  6525. SVGFECompositeElement: C,
  6526. SVGFEConvolveMatrixElement: C,
  6527. SVGFEDiffuseLightingElement: C,
  6528. SVGFEDisplacementMapElement: C,
  6529. SVGFEDistantLightElement: C,
  6530. SVGFEDropShadowElement: C,
  6531. SVGFEFloodElement: C,
  6532. SVGFEFuncAElement: C,
  6533. SVGFEFuncBElement: C,
  6534. SVGFEFuncGElement: C,
  6535. SVGFEFuncRElement: C,
  6536. SVGFEGaussianBlurElement: C,
  6537. SVGFEImageElement: C,
  6538. SVGFEMergeElement: C,
  6539. SVGFEMergeNodeElement: C,
  6540. SVGFEMorphologyElement: C,
  6541. SVGFEOffsetElement: C,
  6542. SVGFEPointLightElement: C,
  6543. SVGFESpecularLightingElement: C,
  6544. SVGFESpotLightElement: C,
  6545. SVGFETileElement: C,
  6546. SVGFETurbulenceElement: C,
  6547. SVGFilterElement: C,
  6548. SVGForeignObjectElement: C,
  6549. SVGGElement: C,
  6550. SVGGeometryElement: C,
  6551. SVGGradientElement: C,
  6552. SVGGraphicsElement: C,
  6553. SVGImageElement: C,
  6554. SVGLength: C,
  6555. SVGLengthList: C,
  6556. SVGLinearGradientElement: C,
  6557. SVGLineElement: C,
  6558. SVGMarkerElement: C,
  6559. SVGMaskElement: C,
  6560. SVGMatrix: C,
  6561. SVGMetadataElement: C,
  6562. SVGMPathElement: C,
  6563. SVGNumber: C,
  6564. SVGNumberList: C,
  6565. SVGPathElement: C,
  6566. SVGPatternElement: C,
  6567. SVGPoint: C,
  6568. SVGPointList: C,
  6569. SVGPolygonElement: C,
  6570. SVGPolylineElement: C,
  6571. SVGPreserveAspectRatio: C,
  6572. SVGRadialGradientElement: C,
  6573. SVGRect: C,
  6574. SVGRectElement: C,
  6575. SVGScriptElement: C,
  6576. SVGSetElement: C,
  6577. SVGStopElement: C,
  6578. SVGStringList: C,
  6579. SVGStyleElement: C,
  6580. SVGSVGElement: C,
  6581. SVGSwitchElement: C,
  6582. SVGSymbolElement: C,
  6583. SVGTextContentElement: C,
  6584. SVGTextElement: C,
  6585. SVGTextPathElement: C,
  6586. SVGTextPositioningElement: C,
  6587. SVGTitleElement: C,
  6588. SVGTransform: C,
  6589. SVGTransformList: C,
  6590. SVGTSpanElement: C,
  6591. SVGUnitTypes: C,
  6592. SVGUseElement: C,
  6593. SVGViewElement: C,
  6594. TaskAttributionTiming: C,
  6595. Text: C,
  6596. TextEvent: C,
  6597. TextMetrics: C,
  6598. TextTrack: C,
  6599. TextTrackCue: C,
  6600. TextTrackCueList: C,
  6601. TextTrackList: C,
  6602. TimeRanges: C,
  6603. toolbar: O,
  6604. top: O,
  6605. Touch: C,
  6606. TouchEvent: C,
  6607. TouchList: C,
  6608. TrackEvent: C,
  6609. TransitionEvent: C,
  6610. TreeWalker: C,
  6611. UIEvent: C,
  6612. ValidityState: C,
  6613. visualViewport: O,
  6614. VisualViewport: C,
  6615. VTTCue: C,
  6616. WaveShaperNode: C,
  6617. WebAssembly: O,
  6618. WebGL2RenderingContext: C,
  6619. WebGLActiveInfo: C,
  6620. WebGLBuffer: C,
  6621. WebGLContextEvent: C,
  6622. WebGLFramebuffer: C,
  6623. WebGLProgram: C,
  6624. WebGLQuery: C,
  6625. WebGLRenderbuffer: C,
  6626. WebGLRenderingContext: C,
  6627. WebGLSampler: C,
  6628. WebGLShader: C,
  6629. WebGLShaderPrecisionFormat: C,
  6630. WebGLSync: C,
  6631. WebGLTexture: C,
  6632. WebGLTransformFeedback: C,
  6633. WebGLUniformLocation: C,
  6634. WebGLVertexArrayObject: C,
  6635. WebSocket: C,
  6636. WheelEvent: C,
  6637. Window: C,
  6638. Worker: C,
  6639. WritableStream: C,
  6640. XMLDocument: C,
  6641. XMLHttpRequest: C,
  6642. XMLHttpRequestEventTarget: C,
  6643. XMLHttpRequestUpload: C,
  6644. XMLSerializer: C,
  6645. XPathEvaluator: C,
  6646. XPathExpression: C,
  6647. XPathResult: C,
  6648. XSLTProcessor: C
  6649. };
  6650. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6651. knownGlobals[global] = knownGlobals;
  6652. }
  6653. function getGlobalAtPath(path) {
  6654. let currentGlobal = knownGlobals;
  6655. for (const pathSegment of path) {
  6656. if (typeof pathSegment !== 'string') {
  6657. return null;
  6658. }
  6659. currentGlobal = currentGlobal[pathSegment];
  6660. if (!currentGlobal) {
  6661. return null;
  6662. }
  6663. }
  6664. return currentGlobal[ValueProperties];
  6665. }
  6666. class GlobalVariable extends Variable {
  6667. constructor() {
  6668. super(...arguments);
  6669. // Ensure we use live-bindings for globals as we do not know if they have
  6670. // been reassigned
  6671. this.isReassigned = true;
  6672. }
  6673. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6674. return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
  6675. }
  6676. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6677. switch (interaction.type) {
  6678. case INTERACTION_ACCESSED:
  6679. if (path.length === 0) {
  6680. // Technically, "undefined" is a global variable of sorts
  6681. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6682. }
  6683. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6684. case INTERACTION_ASSIGNED:
  6685. return true;
  6686. case INTERACTION_CALLED: {
  6687. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6688. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6689. }
  6690. }
  6691. }
  6692. }
  6693. const tdzVariableKinds = {
  6694. __proto__: null,
  6695. class: true,
  6696. const: true,
  6697. let: true,
  6698. var: true
  6699. };
  6700. class Identifier extends NodeBase {
  6701. constructor() {
  6702. super(...arguments);
  6703. this.variable = null;
  6704. this.isTDZAccess = null;
  6705. }
  6706. addExportedVariables(variables, exportNamesByVariable) {
  6707. if (exportNamesByVariable.has(this.variable)) {
  6708. variables.push(this.variable);
  6709. }
  6710. }
  6711. bind() {
  6712. if (!this.variable && is_reference(this, this.parent)) {
  6713. this.variable = this.scope.findVariable(this.name);
  6714. this.variable.addReference(this);
  6715. }
  6716. }
  6717. declare(kind, init) {
  6718. let variable;
  6719. const { treeshake } = this.context.options;
  6720. switch (kind) {
  6721. case 'var':
  6722. variable = this.scope.addDeclaration(this, this.context, init, true);
  6723. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6724. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6725. variable.markInitializersForDeoptimization();
  6726. }
  6727. break;
  6728. case 'function':
  6729. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6730. variable = this.scope.addDeclaration(this, this.context, init, false);
  6731. break;
  6732. case 'let':
  6733. case 'const':
  6734. case 'class':
  6735. variable = this.scope.addDeclaration(this, this.context, init, false);
  6736. break;
  6737. case 'parameter':
  6738. variable = this.scope.addParameterDeclaration(this);
  6739. break;
  6740. /* istanbul ignore next */
  6741. default:
  6742. /* istanbul ignore next */
  6743. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6744. }
  6745. variable.kind = kind;
  6746. return [(this.variable = variable)];
  6747. }
  6748. deoptimizePath(path) {
  6749. var _a;
  6750. if (path.length === 0 && !this.scope.contains(this.name)) {
  6751. this.disallowImportReassignment();
  6752. }
  6753. // We keep conditional chaining because an unknown Node could have an
  6754. // Identifier as property that might be deoptimized by default
  6755. (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  6756. }
  6757. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6758. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  6759. }
  6760. getLiteralValueAtPath(path, recursionTracker, origin) {
  6761. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6762. }
  6763. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6764. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6765. }
  6766. hasEffects(context) {
  6767. if (!this.deoptimized)
  6768. this.applyDeoptimizations();
  6769. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6770. return true;
  6771. }
  6772. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  6773. this.variable instanceof GlobalVariable &&
  6774. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6775. }
  6776. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6777. switch (interaction.type) {
  6778. case INTERACTION_ACCESSED:
  6779. return (this.variable !== null &&
  6780. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6781. case INTERACTION_ASSIGNED:
  6782. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6783. case INTERACTION_CALLED:
  6784. return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
  6785. }
  6786. }
  6787. include() {
  6788. if (!this.deoptimized)
  6789. this.applyDeoptimizations();
  6790. if (!this.included) {
  6791. this.included = true;
  6792. if (this.variable !== null) {
  6793. this.context.includeVariableInModule(this.variable);
  6794. }
  6795. }
  6796. }
  6797. includeCallArguments(context, args) {
  6798. this.variable.includeCallArguments(context, args);
  6799. }
  6800. isPossibleTDZ() {
  6801. // return cached value to avoid issues with the next tree-shaking pass
  6802. if (this.isTDZAccess !== null)
  6803. return this.isTDZAccess;
  6804. if (!(this.variable instanceof LocalVariable) ||
  6805. !this.variable.kind ||
  6806. !(this.variable.kind in tdzVariableKinds)) {
  6807. return (this.isTDZAccess = false);
  6808. }
  6809. let decl_id;
  6810. if (this.variable.declarations &&
  6811. this.variable.declarations.length === 1 &&
  6812. (decl_id = this.variable.declarations[0]) &&
  6813. this.start < decl_id.start &&
  6814. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6815. // a variable accessed before its declaration
  6816. // in the same function or at top level of module
  6817. return (this.isTDZAccess = true);
  6818. }
  6819. if (!this.variable.initReached) {
  6820. // Either a const/let TDZ violation or
  6821. // var use before declaration was encountered.
  6822. return (this.isTDZAccess = true);
  6823. }
  6824. return (this.isTDZAccess = false);
  6825. }
  6826. markDeclarationReached() {
  6827. this.variable.initReached = true;
  6828. }
  6829. render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  6830. if (this.variable) {
  6831. const name = this.variable.getName(getPropertyAccess);
  6832. if (name !== this.name) {
  6833. code.overwrite(this.start, this.end, name, {
  6834. contentOnly: true,
  6835. storeName: true
  6836. });
  6837. if (isShorthandProperty) {
  6838. code.prependRight(this.start, `${this.name}: `);
  6839. }
  6840. }
  6841. // In strict mode, any variable named "eval" must be the actual "eval" function
  6842. if (name === 'eval' &&
  6843. renderedParentType === CallExpression$1 &&
  6844. isCalleeOfRenderedParent) {
  6845. code.appendRight(this.start, '0, ');
  6846. }
  6847. }
  6848. }
  6849. applyDeoptimizations() {
  6850. this.deoptimized = true;
  6851. if (this.variable instanceof LocalVariable) {
  6852. this.variable.consolidateInitializers();
  6853. this.context.requestTreeshakingPass();
  6854. }
  6855. }
  6856. disallowImportReassignment() {
  6857. return this.context.error({
  6858. code: 'ILLEGAL_REASSIGNMENT',
  6859. message: `Illegal reassignment to import '${this.name}'`
  6860. }, this.start);
  6861. }
  6862. getVariableRespectingTDZ() {
  6863. if (this.isPossibleTDZ()) {
  6864. return UNKNOWN_EXPRESSION;
  6865. }
  6866. return this.variable;
  6867. }
  6868. }
  6869. function closestParentFunctionOrProgram(node) {
  6870. while (node && !/^Program|Function/.test(node.type)) {
  6871. node = node.parent;
  6872. }
  6873. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6874. return node;
  6875. }
  6876. function treeshakeNode(node, code, start, end) {
  6877. code.remove(start, end);
  6878. if (node.annotations) {
  6879. for (const annotation of node.annotations) {
  6880. if (annotation.start < start) {
  6881. code.remove(annotation.start, annotation.end);
  6882. }
  6883. else {
  6884. return;
  6885. }
  6886. }
  6887. }
  6888. }
  6889. function removeAnnotations(node, code) {
  6890. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  6891. node = node.parent;
  6892. }
  6893. if (node.annotations) {
  6894. for (const annotation of node.annotations) {
  6895. code.remove(annotation.start, annotation.end);
  6896. }
  6897. }
  6898. }
  6899. const NO_SEMICOLON = { isNoStatement: true };
  6900. // This assumes there are only white-space and comments between start and the string we are looking for
  6901. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  6902. let searchPos, charCodeAfterSlash;
  6903. searchPos = code.indexOf(searchString, start);
  6904. while (true) {
  6905. start = code.indexOf('/', start);
  6906. if (start === -1 || start >= searchPos)
  6907. return searchPos;
  6908. charCodeAfterSlash = code.charCodeAt(++start);
  6909. ++start;
  6910. // With our assumption, '/' always starts a comment. Determine comment type:
  6911. start =
  6912. charCodeAfterSlash === 47 /*"/"*/
  6913. ? code.indexOf('\n', start) + 1
  6914. : code.indexOf('*/', start) + 2;
  6915. if (start > searchPos) {
  6916. searchPos = code.indexOf(searchString, start);
  6917. }
  6918. }
  6919. }
  6920. const NON_WHITESPACE = /\S/g;
  6921. function findNonWhiteSpace(code, index) {
  6922. NON_WHITESPACE.lastIndex = index;
  6923. const result = NON_WHITESPACE.exec(code);
  6924. return result.index;
  6925. }
  6926. // This assumes "code" only contains white-space and comments
  6927. // Returns position of line-comment if applicable
  6928. function findFirstLineBreakOutsideComment(code) {
  6929. let lineBreakPos, charCodeAfterSlash, start = 0;
  6930. lineBreakPos = code.indexOf('\n', start);
  6931. while (true) {
  6932. start = code.indexOf('/', start);
  6933. if (start === -1 || start > lineBreakPos)
  6934. return [lineBreakPos, lineBreakPos + 1];
  6935. // With our assumption, '/' always starts a comment. Determine comment type:
  6936. charCodeAfterSlash = code.charCodeAt(start + 1);
  6937. if (charCodeAfterSlash === 47 /*"/"*/)
  6938. return [start, lineBreakPos + 1];
  6939. start = code.indexOf('*/', start + 3) + 2;
  6940. if (start > lineBreakPos) {
  6941. lineBreakPos = code.indexOf('\n', start);
  6942. }
  6943. }
  6944. }
  6945. function renderStatementList(statements, code, start, end, options) {
  6946. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  6947. let nextNode = statements[0];
  6948. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  6949. if (nextNodeNeedsBoundaries) {
  6950. nextNodeStart =
  6951. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  6952. }
  6953. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  6954. currentNode = nextNode;
  6955. currentNodeStart = nextNodeStart;
  6956. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  6957. nextNode = statements[nextIndex];
  6958. nextNodeNeedsBoundaries =
  6959. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  6960. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  6961. nextNodeStart =
  6962. currentNode.end +
  6963. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  6964. if (currentNode.included) {
  6965. currentNodeNeedsBoundaries
  6966. ? currentNode.render(code, options, {
  6967. end: nextNodeStart,
  6968. start: currentNodeStart
  6969. })
  6970. : currentNode.render(code, options);
  6971. }
  6972. else {
  6973. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  6974. }
  6975. }
  6976. else {
  6977. currentNode.render(code, options);
  6978. }
  6979. }
  6980. }
  6981. // This assumes that the first character is not part of the first node
  6982. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  6983. const splitUpNodes = [];
  6984. let node, nextNode, nextNodeStart, contentEnd, char;
  6985. let separator = start - 1;
  6986. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  6987. nextNode = nodes[nextIndex];
  6988. if (node !== undefined) {
  6989. separator =
  6990. node.end +
  6991. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  6992. }
  6993. nextNodeStart = contentEnd =
  6994. separator +
  6995. 1 +
  6996. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  6997. while (((char = code.original.charCodeAt(nextNodeStart)),
  6998. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  6999. nextNodeStart++;
  7000. if (node !== undefined) {
  7001. splitUpNodes.push({
  7002. contentEnd,
  7003. end: nextNodeStart,
  7004. node,
  7005. separator,
  7006. start
  7007. });
  7008. }
  7009. node = nextNode;
  7010. start = nextNodeStart;
  7011. }
  7012. splitUpNodes.push({
  7013. contentEnd: end,
  7014. end,
  7015. node: node,
  7016. separator: null,
  7017. start
  7018. });
  7019. return splitUpNodes;
  7020. }
  7021. // This assumes there are only white-space and comments between start and end
  7022. function removeLineBreaks(code, start, end) {
  7023. while (true) {
  7024. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  7025. if (removeStart === -1) {
  7026. break;
  7027. }
  7028. code.remove(start + removeStart, (start += removeEnd));
  7029. }
  7030. }
  7031. class BlockScope extends ChildScope {
  7032. addDeclaration(identifier, context, init, isHoisted) {
  7033. if (isHoisted) {
  7034. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  7035. // Necessary to make sure the init is deoptimized for conditional declarations.
  7036. // We cannot call deoptimizePath here.
  7037. variable.markInitializersForDeoptimization();
  7038. return variable;
  7039. }
  7040. else {
  7041. return super.addDeclaration(identifier, context, init, false);
  7042. }
  7043. }
  7044. }
  7045. class ExpressionStatement extends NodeBase {
  7046. initialise() {
  7047. if (this.directive &&
  7048. this.directive !== 'use strict' &&
  7049. this.parent.type === Program$1) {
  7050. this.context.warn(
  7051. // This is necessary, because either way (deleting or not) can lead to errors.
  7052. {
  7053. code: 'MODULE_LEVEL_DIRECTIVE',
  7054. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  7055. }, this.start);
  7056. }
  7057. }
  7058. render(code, options) {
  7059. super.render(code, options);
  7060. if (this.included)
  7061. this.insertSemicolon(code);
  7062. }
  7063. shouldBeIncluded(context) {
  7064. if (this.directive && this.directive !== 'use strict')
  7065. return this.parent.type !== Program$1;
  7066. return super.shouldBeIncluded(context);
  7067. }
  7068. applyDeoptimizations() { }
  7069. }
  7070. class BlockStatement extends NodeBase {
  7071. constructor() {
  7072. super(...arguments);
  7073. this.directlyIncluded = false;
  7074. }
  7075. addImplicitReturnExpressionToScope() {
  7076. const lastStatement = this.body[this.body.length - 1];
  7077. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  7078. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7079. }
  7080. }
  7081. createScope(parentScope) {
  7082. this.scope = this.parent.preventChildBlockScope
  7083. ? parentScope
  7084. : new BlockScope(parentScope);
  7085. }
  7086. hasEffects(context) {
  7087. if (this.deoptimizeBody)
  7088. return true;
  7089. for (const node of this.body) {
  7090. if (context.brokenFlow)
  7091. break;
  7092. if (node.hasEffects(context))
  7093. return true;
  7094. }
  7095. return false;
  7096. }
  7097. include(context, includeChildrenRecursively) {
  7098. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7099. this.included = true;
  7100. this.directlyIncluded = true;
  7101. if (this.deoptimizeBody)
  7102. includeChildrenRecursively = true;
  7103. for (const node of this.body) {
  7104. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7105. node.include(context, includeChildrenRecursively);
  7106. }
  7107. }
  7108. }
  7109. initialise() {
  7110. const firstBodyStatement = this.body[0];
  7111. this.deoptimizeBody =
  7112. firstBodyStatement instanceof ExpressionStatement &&
  7113. firstBodyStatement.directive === 'use asm';
  7114. }
  7115. render(code, options) {
  7116. if (this.body.length) {
  7117. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7118. }
  7119. else {
  7120. super.render(code, options);
  7121. }
  7122. }
  7123. }
  7124. class RestElement extends NodeBase {
  7125. constructor() {
  7126. super(...arguments);
  7127. this.declarationInit = null;
  7128. }
  7129. addExportedVariables(variables, exportNamesByVariable) {
  7130. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7131. }
  7132. declare(kind, init) {
  7133. this.declarationInit = init;
  7134. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7135. }
  7136. deoptimizePath(path) {
  7137. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  7138. }
  7139. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7140. return (path.length > 0 ||
  7141. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7142. }
  7143. markDeclarationReached() {
  7144. this.argument.markDeclarationReached();
  7145. }
  7146. applyDeoptimizations() {
  7147. this.deoptimized = true;
  7148. if (this.declarationInit !== null) {
  7149. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7150. this.context.requestTreeshakingPass();
  7151. }
  7152. }
  7153. }
  7154. class FunctionBase extends NodeBase {
  7155. constructor() {
  7156. super(...arguments);
  7157. this.objectEntity = null;
  7158. this.deoptimizedReturn = false;
  7159. }
  7160. deoptimizePath(path) {
  7161. this.getObjectEntity().deoptimizePath(path);
  7162. if (path.length === 1 && path[0] === UnknownKey) {
  7163. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7164. // which means the return expression needs to be reassigned
  7165. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7166. }
  7167. }
  7168. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7169. if (path.length > 0) {
  7170. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7171. }
  7172. }
  7173. getLiteralValueAtPath(path, recursionTracker, origin) {
  7174. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7175. }
  7176. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7177. if (path.length > 0) {
  7178. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7179. }
  7180. if (this.async) {
  7181. if (!this.deoptimizedReturn) {
  7182. this.deoptimizedReturn = true;
  7183. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7184. this.context.requestTreeshakingPass();
  7185. }
  7186. return UNKNOWN_EXPRESSION;
  7187. }
  7188. return this.scope.getReturnExpression();
  7189. }
  7190. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7191. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7192. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7193. }
  7194. if (this.async) {
  7195. const { propertyReadSideEffects } = this.context.options
  7196. .treeshake;
  7197. const returnExpression = this.scope.getReturnExpression();
  7198. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7199. (propertyReadSideEffects &&
  7200. (propertyReadSideEffects === 'always' ||
  7201. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7202. return true;
  7203. }
  7204. }
  7205. for (const param of this.params) {
  7206. if (param.hasEffects(context))
  7207. return true;
  7208. }
  7209. return false;
  7210. }
  7211. include(context, includeChildrenRecursively) {
  7212. if (!this.deoptimized)
  7213. this.applyDeoptimizations();
  7214. this.included = true;
  7215. const { brokenFlow } = context;
  7216. context.brokenFlow = BROKEN_FLOW_NONE;
  7217. this.body.include(context, includeChildrenRecursively);
  7218. context.brokenFlow = brokenFlow;
  7219. }
  7220. includeCallArguments(context, args) {
  7221. this.scope.includeCallArguments(context, args);
  7222. }
  7223. initialise() {
  7224. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  7225. if (this.body instanceof BlockStatement) {
  7226. this.body.addImplicitReturnExpressionToScope();
  7227. }
  7228. else {
  7229. this.scope.addReturnExpression(this.body);
  7230. }
  7231. }
  7232. parseNode(esTreeNode) {
  7233. if (esTreeNode.body.type === BlockStatement$1) {
  7234. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  7235. }
  7236. super.parseNode(esTreeNode);
  7237. }
  7238. applyDeoptimizations() { }
  7239. }
  7240. FunctionBase.prototype.preventChildBlockScope = true;
  7241. class ArrowFunctionExpression extends FunctionBase {
  7242. constructor() {
  7243. super(...arguments);
  7244. this.objectEntity = null;
  7245. }
  7246. createScope(parentScope) {
  7247. this.scope = new ReturnValueScope(parentScope, this.context);
  7248. }
  7249. hasEffects() {
  7250. if (!this.deoptimized)
  7251. this.applyDeoptimizations();
  7252. return false;
  7253. }
  7254. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7255. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7256. return true;
  7257. if (interaction.type === INTERACTION_CALLED) {
  7258. const { ignore, brokenFlow } = context;
  7259. context.ignore = {
  7260. breaks: false,
  7261. continues: false,
  7262. labels: new Set(),
  7263. returnYield: true
  7264. };
  7265. if (this.body.hasEffects(context))
  7266. return true;
  7267. context.ignore = ignore;
  7268. context.brokenFlow = brokenFlow;
  7269. }
  7270. return false;
  7271. }
  7272. include(context, includeChildrenRecursively) {
  7273. super.include(context, includeChildrenRecursively);
  7274. for (const param of this.params) {
  7275. if (!(param instanceof Identifier)) {
  7276. param.include(context, includeChildrenRecursively);
  7277. }
  7278. }
  7279. }
  7280. getObjectEntity() {
  7281. if (this.objectEntity !== null) {
  7282. return this.objectEntity;
  7283. }
  7284. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  7285. }
  7286. }
  7287. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  7288. if (exportedVariables.length === 1 &&
  7289. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  7290. const variable = exportedVariables[0];
  7291. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  7292. }
  7293. else {
  7294. const fields = [];
  7295. for (const variable of exportedVariables) {
  7296. for (const exportName of exportNamesByVariable.get(variable)) {
  7297. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  7298. }
  7299. }
  7300. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  7301. }
  7302. }
  7303. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  7304. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  7305. code.appendLeft(expressionEnd, ')');
  7306. }
  7307. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  7308. const { _, getDirectReturnIifeLeft } = options.snippets;
  7309. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  7310. code.appendLeft(expressionEnd, ')');
  7311. }
  7312. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  7313. const { _, getPropertyAccess } = options.snippets;
  7314. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  7315. if (needsParens) {
  7316. code.prependRight(expressionStart, '(');
  7317. code.appendLeft(expressionEnd, ')');
  7318. }
  7319. }
  7320. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  7321. const { _ } = options.snippets;
  7322. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  7323. if (needsParens) {
  7324. code.prependRight(expressionStart, '(');
  7325. code.appendLeft(expressionEnd, ')');
  7326. }
  7327. }
  7328. class ObjectPattern extends NodeBase {
  7329. addExportedVariables(variables, exportNamesByVariable) {
  7330. for (const property of this.properties) {
  7331. if (property.type === Property$1) {
  7332. property.value.addExportedVariables(variables, exportNamesByVariable);
  7333. }
  7334. else {
  7335. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7336. }
  7337. }
  7338. }
  7339. declare(kind, init) {
  7340. const variables = [];
  7341. for (const property of this.properties) {
  7342. variables.push(...property.declare(kind, init));
  7343. }
  7344. return variables;
  7345. }
  7346. deoptimizePath(path) {
  7347. if (path.length === 0) {
  7348. for (const property of this.properties) {
  7349. property.deoptimizePath(path);
  7350. }
  7351. }
  7352. }
  7353. hasEffectsOnInteractionAtPath(
  7354. // At the moment, this is only triggered for assignment left-hand sides,
  7355. // where the path is empty
  7356. _path, interaction, context) {
  7357. for (const property of this.properties) {
  7358. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7359. return true;
  7360. }
  7361. return false;
  7362. }
  7363. markDeclarationReached() {
  7364. for (const property of this.properties) {
  7365. property.markDeclarationReached();
  7366. }
  7367. }
  7368. }
  7369. class AssignmentExpression extends NodeBase {
  7370. hasEffects(context) {
  7371. const { deoptimized, left, right } = this;
  7372. if (!deoptimized)
  7373. this.applyDeoptimizations();
  7374. // MemberExpressions do not access the property before assignments if the
  7375. // operator is '='.
  7376. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
  7377. }
  7378. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7379. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  7380. }
  7381. include(context, includeChildrenRecursively) {
  7382. const { deoptimized, left, right, operator } = this;
  7383. if (!deoptimized)
  7384. this.applyDeoptimizations();
  7385. this.included = true;
  7386. if (includeChildrenRecursively ||
  7387. operator !== '=' ||
  7388. left.included ||
  7389. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  7390. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  7391. }
  7392. right.include(context, includeChildrenRecursively);
  7393. }
  7394. initialise() {
  7395. this.left.setAssignedValue(this.right);
  7396. }
  7397. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7398. const { left, right, start, end, parent } = this;
  7399. if (left.included) {
  7400. left.render(code, options);
  7401. right.render(code, options);
  7402. }
  7403. else {
  7404. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  7405. code.remove(start, inclusionStart);
  7406. if (preventASI) {
  7407. removeLineBreaks(code, inclusionStart, right.start);
  7408. }
  7409. right.render(code, options, {
  7410. renderedParentType: renderedParentType || parent.type,
  7411. renderedSurroundingElement: renderedSurroundingElement || parent.type
  7412. });
  7413. }
  7414. if (options.format === 'system') {
  7415. if (left instanceof Identifier) {
  7416. const variable = left.variable;
  7417. const exportNames = options.exportNamesByVariable.get(variable);
  7418. if (exportNames) {
  7419. if (exportNames.length === 1) {
  7420. renderSystemExportExpression(variable, start, end, code, options);
  7421. }
  7422. else {
  7423. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  7424. }
  7425. return;
  7426. }
  7427. }
  7428. else {
  7429. const systemPatternExports = [];
  7430. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  7431. if (systemPatternExports.length > 0) {
  7432. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  7433. return;
  7434. }
  7435. }
  7436. }
  7437. if (left.included &&
  7438. left instanceof ObjectPattern &&
  7439. (renderedSurroundingElement === ExpressionStatement$1 ||
  7440. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  7441. code.appendRight(start, '(');
  7442. code.prependLeft(end, ')');
  7443. }
  7444. }
  7445. applyDeoptimizations() {
  7446. this.deoptimized = true;
  7447. this.left.deoptimizePath(EMPTY_PATH);
  7448. this.right.deoptimizePath(UNKNOWN_PATH);
  7449. this.context.requestTreeshakingPass();
  7450. }
  7451. }
  7452. class AssignmentPattern extends NodeBase {
  7453. addExportedVariables(variables, exportNamesByVariable) {
  7454. this.left.addExportedVariables(variables, exportNamesByVariable);
  7455. }
  7456. declare(kind, init) {
  7457. return this.left.declare(kind, init);
  7458. }
  7459. deoptimizePath(path) {
  7460. path.length === 0 && this.left.deoptimizePath(path);
  7461. }
  7462. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7463. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7464. }
  7465. markDeclarationReached() {
  7466. this.left.markDeclarationReached();
  7467. }
  7468. render(code, options, { isShorthandProperty } = BLANK) {
  7469. this.left.render(code, options, { isShorthandProperty });
  7470. this.right.render(code, options);
  7471. }
  7472. applyDeoptimizations() {
  7473. this.deoptimized = true;
  7474. this.left.deoptimizePath(EMPTY_PATH);
  7475. this.right.deoptimizePath(UNKNOWN_PATH);
  7476. this.context.requestTreeshakingPass();
  7477. }
  7478. }
  7479. class ArgumentsVariable extends LocalVariable {
  7480. constructor(context) {
  7481. super('arguments', null, UNKNOWN_EXPRESSION, context);
  7482. }
  7483. hasEffectsOnInteractionAtPath(path, { type }) {
  7484. return type !== INTERACTION_ACCESSED || path.length > 1;
  7485. }
  7486. }
  7487. class ThisVariable extends LocalVariable {
  7488. constructor(context) {
  7489. super('this', null, null, context);
  7490. this.deoptimizedPaths = [];
  7491. this.entitiesToBeDeoptimized = new Set();
  7492. this.thisDeoptimizationList = [];
  7493. this.thisDeoptimizations = new DiscriminatedPathTracker();
  7494. }
  7495. addEntityToBeDeoptimized(entity) {
  7496. for (const path of this.deoptimizedPaths) {
  7497. entity.deoptimizePath(path);
  7498. }
  7499. for (const { interaction, path } of this.thisDeoptimizationList) {
  7500. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7501. }
  7502. this.entitiesToBeDeoptimized.add(entity);
  7503. }
  7504. deoptimizePath(path) {
  7505. if (path.length === 0 ||
  7506. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7507. return;
  7508. }
  7509. this.deoptimizedPaths.push(path);
  7510. for (const entity of this.entitiesToBeDeoptimized) {
  7511. entity.deoptimizePath(path);
  7512. }
  7513. }
  7514. deoptimizeThisOnInteractionAtPath(interaction, path) {
  7515. const thisDeoptimization = {
  7516. interaction,
  7517. path
  7518. };
  7519. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
  7520. for (const entity of this.entitiesToBeDeoptimized) {
  7521. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7522. }
  7523. this.thisDeoptimizationList.push(thisDeoptimization);
  7524. }
  7525. }
  7526. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7527. return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
  7528. super.hasEffectsOnInteractionAtPath(path, interaction, context));
  7529. }
  7530. getInit(context) {
  7531. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  7532. }
  7533. }
  7534. class FunctionScope extends ReturnValueScope {
  7535. constructor(parent, context) {
  7536. super(parent, context);
  7537. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7538. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7539. }
  7540. findLexicalBoundary() {
  7541. return this;
  7542. }
  7543. includeCallArguments(context, args) {
  7544. super.includeCallArguments(context, args);
  7545. if (this.argumentsVariable.included) {
  7546. for (const arg of args) {
  7547. if (!arg.included) {
  7548. arg.include(context, false);
  7549. }
  7550. }
  7551. }
  7552. }
  7553. }
  7554. class FunctionNode extends FunctionBase {
  7555. constructor() {
  7556. super(...arguments);
  7557. this.objectEntity = null;
  7558. }
  7559. createScope(parentScope) {
  7560. this.scope = new FunctionScope(parentScope, this.context);
  7561. }
  7562. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7563. super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7564. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  7565. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
  7566. }
  7567. }
  7568. hasEffects(context) {
  7569. var _a;
  7570. if (!this.deoptimized)
  7571. this.applyDeoptimizations();
  7572. return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  7573. }
  7574. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7575. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7576. return true;
  7577. if (interaction.type === INTERACTION_CALLED) {
  7578. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7579. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
  7580. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  7581. : UNKNOWN_EXPRESSION);
  7582. const { brokenFlow, ignore } = context;
  7583. context.ignore = {
  7584. breaks: false,
  7585. continues: false,
  7586. labels: new Set(),
  7587. returnYield: true
  7588. };
  7589. if (this.body.hasEffects(context))
  7590. return true;
  7591. context.brokenFlow = brokenFlow;
  7592. if (thisInit) {
  7593. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7594. }
  7595. else {
  7596. context.replacedVariableInits.delete(this.scope.thisVariable);
  7597. }
  7598. context.ignore = ignore;
  7599. }
  7600. return false;
  7601. }
  7602. include(context, includeChildrenRecursively) {
  7603. var _a;
  7604. super.include(context, includeChildrenRecursively);
  7605. (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
  7606. const hasArguments = this.scope.argumentsVariable.included;
  7607. for (const param of this.params) {
  7608. if (!(param instanceof Identifier) || hasArguments) {
  7609. param.include(context, includeChildrenRecursively);
  7610. }
  7611. }
  7612. }
  7613. initialise() {
  7614. var _a;
  7615. super.initialise();
  7616. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
  7617. }
  7618. getObjectEntity() {
  7619. if (this.objectEntity !== null) {
  7620. return this.objectEntity;
  7621. }
  7622. return (this.objectEntity = new ObjectEntity([
  7623. {
  7624. key: 'prototype',
  7625. kind: 'init',
  7626. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7627. }
  7628. ], OBJECT_PROTOTYPE));
  7629. }
  7630. }
  7631. class AwaitExpression extends NodeBase {
  7632. hasEffects() {
  7633. if (!this.deoptimized)
  7634. this.applyDeoptimizations();
  7635. return true;
  7636. }
  7637. include(context, includeChildrenRecursively) {
  7638. if (!this.deoptimized)
  7639. this.applyDeoptimizations();
  7640. if (!this.included) {
  7641. this.included = true;
  7642. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  7643. let parent = this.parent;
  7644. do {
  7645. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  7646. break checkTopLevelAwait;
  7647. } while ((parent = parent.parent));
  7648. this.context.usesTopLevelAwait = true;
  7649. }
  7650. }
  7651. this.argument.include(context, includeChildrenRecursively);
  7652. }
  7653. }
  7654. const binaryOperators = {
  7655. '!=': (left, right) => left != right,
  7656. '!==': (left, right) => left !== right,
  7657. '%': (left, right) => left % right,
  7658. '&': (left, right) => left & right,
  7659. '*': (left, right) => left * right,
  7660. // At the moment, "**" will be transpiled to Math.pow
  7661. '**': (left, right) => left ** right,
  7662. '+': (left, right) => left + right,
  7663. '-': (left, right) => left - right,
  7664. '/': (left, right) => left / right,
  7665. '<': (left, right) => left < right,
  7666. '<<': (left, right) => left << right,
  7667. '<=': (left, right) => left <= right,
  7668. '==': (left, right) => left == right,
  7669. '===': (left, right) => left === right,
  7670. '>': (left, right) => left > right,
  7671. '>=': (left, right) => left >= right,
  7672. '>>': (left, right) => left >> right,
  7673. '>>>': (left, right) => left >>> right,
  7674. '^': (left, right) => left ^ right,
  7675. '|': (left, right) => left | right
  7676. // We use the fallback for cases where we return something unknown
  7677. // in: () => UnknownValue,
  7678. // instanceof: () => UnknownValue,
  7679. };
  7680. class BinaryExpression extends NodeBase {
  7681. deoptimizeCache() { }
  7682. getLiteralValueAtPath(path, recursionTracker, origin) {
  7683. if (path.length > 0)
  7684. return UnknownValue;
  7685. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7686. if (typeof leftValue === 'symbol')
  7687. return UnknownValue;
  7688. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7689. if (typeof rightValue === 'symbol')
  7690. return UnknownValue;
  7691. const operatorFn = binaryOperators[this.operator];
  7692. if (!operatorFn)
  7693. return UnknownValue;
  7694. return operatorFn(leftValue, rightValue);
  7695. }
  7696. hasEffects(context) {
  7697. // support some implicit type coercion runtime errors
  7698. if (this.operator === '+' &&
  7699. this.parent instanceof ExpressionStatement &&
  7700. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  7701. return true;
  7702. }
  7703. return super.hasEffects(context);
  7704. }
  7705. hasEffectsOnInteractionAtPath(path, { type }) {
  7706. return type !== INTERACTION_ACCESSED || path.length > 1;
  7707. }
  7708. render(code, options, { renderedSurroundingElement } = BLANK) {
  7709. this.left.render(code, options, { renderedSurroundingElement });
  7710. this.right.render(code, options);
  7711. }
  7712. }
  7713. class BreakStatement extends NodeBase {
  7714. hasEffects(context) {
  7715. if (this.label) {
  7716. if (!context.ignore.labels.has(this.label.name))
  7717. return true;
  7718. context.includedLabels.add(this.label.name);
  7719. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7720. }
  7721. else {
  7722. if (!context.ignore.breaks)
  7723. return true;
  7724. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7725. }
  7726. return false;
  7727. }
  7728. include(context) {
  7729. this.included = true;
  7730. if (this.label) {
  7731. this.label.include();
  7732. context.includedLabels.add(this.label.name);
  7733. }
  7734. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7735. }
  7736. }
  7737. function renderCallArguments(code, options, node) {
  7738. if (node.arguments.length > 0) {
  7739. if (node.arguments[node.arguments.length - 1].included) {
  7740. for (const arg of node.arguments) {
  7741. arg.render(code, options);
  7742. }
  7743. }
  7744. else {
  7745. let lastIncludedIndex = node.arguments.length - 2;
  7746. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  7747. lastIncludedIndex--;
  7748. }
  7749. if (lastIncludedIndex >= 0) {
  7750. for (let index = 0; index <= lastIncludedIndex; index++) {
  7751. node.arguments[index].render(code, options);
  7752. }
  7753. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  7754. }
  7755. else {
  7756. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  7757. }
  7758. }
  7759. }
  7760. }
  7761. class Literal extends NodeBase {
  7762. deoptimizeThisOnInteractionAtPath() { }
  7763. getLiteralValueAtPath(path) {
  7764. if (path.length > 0 ||
  7765. // unknown literals can also be null but do not start with an "n"
  7766. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  7767. typeof this.value === 'bigint' ||
  7768. // to support shims for regular expressions
  7769. this.context.code.charCodeAt(this.start) === 47) {
  7770. return UnknownValue;
  7771. }
  7772. return this.value;
  7773. }
  7774. getReturnExpressionWhenCalledAtPath(path) {
  7775. if (path.length !== 1)
  7776. return UNKNOWN_EXPRESSION;
  7777. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7778. }
  7779. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7780. switch (interaction.type) {
  7781. case INTERACTION_ACCESSED:
  7782. return path.length > (this.value === null ? 0 : 1);
  7783. case INTERACTION_ASSIGNED:
  7784. return true;
  7785. case INTERACTION_CALLED:
  7786. return (path.length !== 1 ||
  7787. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7788. }
  7789. }
  7790. initialise() {
  7791. this.members = getLiteralMembersForValue(this.value);
  7792. }
  7793. parseNode(esTreeNode) {
  7794. this.value = esTreeNode.value;
  7795. this.regex = esTreeNode.regex;
  7796. super.parseNode(esTreeNode);
  7797. }
  7798. render(code) {
  7799. if (typeof this.value === 'string') {
  7800. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7801. }
  7802. }
  7803. }
  7804. // To avoid infinite recursions
  7805. const MAX_PATH_DEPTH = 7;
  7806. function getResolvablePropertyKey(memberExpression) {
  7807. return memberExpression.computed
  7808. ? getResolvableComputedPropertyKey(memberExpression.property)
  7809. : memberExpression.property.name;
  7810. }
  7811. function getResolvableComputedPropertyKey(propertyKey) {
  7812. if (propertyKey instanceof Literal) {
  7813. return String(propertyKey.value);
  7814. }
  7815. return null;
  7816. }
  7817. function getPathIfNotComputed(memberExpression) {
  7818. const nextPathKey = memberExpression.propertyKey;
  7819. const object = memberExpression.object;
  7820. if (typeof nextPathKey === 'string') {
  7821. if (object instanceof Identifier) {
  7822. return [
  7823. { key: object.name, pos: object.start },
  7824. { key: nextPathKey, pos: memberExpression.property.start }
  7825. ];
  7826. }
  7827. if (object instanceof MemberExpression) {
  7828. const parentPath = getPathIfNotComputed(object);
  7829. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7830. }
  7831. }
  7832. return null;
  7833. }
  7834. function getStringFromPath(path) {
  7835. let pathString = path[0].key;
  7836. for (let index = 1; index < path.length; index++) {
  7837. pathString += '.' + path[index].key;
  7838. }
  7839. return pathString;
  7840. }
  7841. class MemberExpression extends NodeBase {
  7842. constructor() {
  7843. super(...arguments);
  7844. this.variable = null;
  7845. this.assignmentDeoptimized = false;
  7846. this.bound = false;
  7847. this.expressionsToBeDeoptimized = [];
  7848. this.replacement = null;
  7849. }
  7850. bind() {
  7851. this.bound = true;
  7852. const path = getPathIfNotComputed(this);
  7853. const baseVariable = path && this.scope.findVariable(path[0].key);
  7854. if (baseVariable && baseVariable.isNamespace) {
  7855. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  7856. if (!resolvedVariable) {
  7857. super.bind();
  7858. }
  7859. else if (typeof resolvedVariable === 'string') {
  7860. this.replacement = resolvedVariable;
  7861. }
  7862. else {
  7863. this.variable = resolvedVariable;
  7864. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7865. }
  7866. }
  7867. else {
  7868. super.bind();
  7869. }
  7870. }
  7871. deoptimizeCache() {
  7872. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7873. this.expressionsToBeDeoptimized = [];
  7874. this.propertyKey = UnknownKey;
  7875. this.object.deoptimizePath(UNKNOWN_PATH);
  7876. for (const expression of expressionsToBeDeoptimized) {
  7877. expression.deoptimizeCache();
  7878. }
  7879. }
  7880. deoptimizePath(path) {
  7881. if (path.length === 0)
  7882. this.disallowNamespaceReassignment();
  7883. if (this.variable) {
  7884. this.variable.deoptimizePath(path);
  7885. }
  7886. else if (!this.replacement) {
  7887. if (path.length < MAX_PATH_DEPTH) {
  7888. const propertyKey = this.getPropertyKey();
  7889. this.object.deoptimizePath([
  7890. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7891. ...path
  7892. ]);
  7893. }
  7894. }
  7895. }
  7896. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7897. if (this.variable) {
  7898. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7899. }
  7900. else if (!this.replacement) {
  7901. if (path.length < MAX_PATH_DEPTH) {
  7902. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  7903. }
  7904. else {
  7905. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  7906. }
  7907. }
  7908. }
  7909. getLiteralValueAtPath(path, recursionTracker, origin) {
  7910. if (this.variable) {
  7911. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7912. }
  7913. if (this.replacement) {
  7914. return UnknownValue;
  7915. }
  7916. this.expressionsToBeDeoptimized.push(origin);
  7917. if (path.length < MAX_PATH_DEPTH) {
  7918. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  7919. }
  7920. return UnknownValue;
  7921. }
  7922. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7923. if (this.variable) {
  7924. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7925. }
  7926. if (this.replacement) {
  7927. return UNKNOWN_EXPRESSION;
  7928. }
  7929. this.expressionsToBeDeoptimized.push(origin);
  7930. if (path.length < MAX_PATH_DEPTH) {
  7931. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  7932. }
  7933. return UNKNOWN_EXPRESSION;
  7934. }
  7935. hasEffects(context) {
  7936. if (!this.deoptimized)
  7937. this.applyDeoptimizations();
  7938. return (this.property.hasEffects(context) ||
  7939. this.object.hasEffects(context) ||
  7940. this.hasAccessEffect(context));
  7941. }
  7942. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7943. if (checkAccess && !this.deoptimized)
  7944. this.applyDeoptimizations();
  7945. if (!this.assignmentDeoptimized)
  7946. this.applyAssignmentDeoptimization();
  7947. return (this.property.hasEffects(context) ||
  7948. this.object.hasEffects(context) ||
  7949. (checkAccess && this.hasAccessEffect(context)) ||
  7950. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7951. }
  7952. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7953. if (this.variable) {
  7954. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7955. }
  7956. if (this.replacement) {
  7957. return true;
  7958. }
  7959. if (path.length < MAX_PATH_DEPTH) {
  7960. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  7961. }
  7962. return true;
  7963. }
  7964. include(context, includeChildrenRecursively) {
  7965. if (!this.deoptimized)
  7966. this.applyDeoptimizations();
  7967. this.includeProperties(context, includeChildrenRecursively);
  7968. }
  7969. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7970. if (!this.assignmentDeoptimized)
  7971. this.applyAssignmentDeoptimization();
  7972. if (deoptimizeAccess) {
  7973. this.include(context, includeChildrenRecursively);
  7974. }
  7975. else {
  7976. this.includeProperties(context, includeChildrenRecursively);
  7977. }
  7978. }
  7979. includeCallArguments(context, args) {
  7980. if (this.variable) {
  7981. this.variable.includeCallArguments(context, args);
  7982. }
  7983. else {
  7984. super.includeCallArguments(context, args);
  7985. }
  7986. }
  7987. initialise() {
  7988. this.propertyKey = getResolvablePropertyKey(this);
  7989. this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
  7990. }
  7991. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7992. if (this.variable || this.replacement) {
  7993. const { snippets: { getPropertyAccess } } = options;
  7994. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
  7995. if (renderedParentType && isCalleeOfRenderedParent)
  7996. replacement = '0, ' + replacement;
  7997. code.overwrite(this.start, this.end, replacement, {
  7998. contentOnly: true,
  7999. storeName: true
  8000. });
  8001. }
  8002. else {
  8003. if (renderedParentType && isCalleeOfRenderedParent) {
  8004. code.appendRight(this.start, '0, ');
  8005. }
  8006. this.object.render(code, options, { renderedSurroundingElement });
  8007. this.property.render(code, options);
  8008. }
  8009. }
  8010. setAssignedValue(value) {
  8011. this.assignmentInteraction = {
  8012. args: [value],
  8013. thisArg: this.object,
  8014. type: INTERACTION_ASSIGNED
  8015. };
  8016. }
  8017. applyDeoptimizations() {
  8018. this.deoptimized = true;
  8019. const { propertyReadSideEffects } = this.context.options
  8020. .treeshake;
  8021. if (
  8022. // Namespaces are not bound and should not be deoptimized
  8023. this.bound &&
  8024. propertyReadSideEffects &&
  8025. !(this.variable || this.replacement)) {
  8026. const propertyKey = this.getPropertyKey();
  8027. this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8028. this.context.requestTreeshakingPass();
  8029. }
  8030. }
  8031. applyAssignmentDeoptimization() {
  8032. this.assignmentDeoptimized = true;
  8033. const { propertyReadSideEffects } = this.context.options
  8034. .treeshake;
  8035. if (
  8036. // Namespaces are not bound and should not be deoptimized
  8037. this.bound &&
  8038. propertyReadSideEffects &&
  8039. !(this.variable || this.replacement)) {
  8040. this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8041. this.context.requestTreeshakingPass();
  8042. }
  8043. }
  8044. disallowNamespaceReassignment() {
  8045. if (this.object instanceof Identifier) {
  8046. const variable = this.scope.findVariable(this.object.name);
  8047. if (variable.isNamespace) {
  8048. if (this.variable) {
  8049. this.context.includeVariableInModule(this.variable);
  8050. }
  8051. this.context.warn({
  8052. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  8053. message: `Illegal reassignment to import '${this.object.name}'`
  8054. }, this.start);
  8055. }
  8056. }
  8057. }
  8058. getPropertyKey() {
  8059. if (this.propertyKey === null) {
  8060. this.propertyKey = UnknownKey;
  8061. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8062. return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
  8063. }
  8064. return this.propertyKey;
  8065. }
  8066. hasAccessEffect(context) {
  8067. const { propertyReadSideEffects } = this.context.options
  8068. .treeshake;
  8069. return (!(this.variable || this.replacement) &&
  8070. propertyReadSideEffects &&
  8071. (propertyReadSideEffects === 'always' ||
  8072. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8073. }
  8074. includeProperties(context, includeChildrenRecursively) {
  8075. if (!this.included) {
  8076. this.included = true;
  8077. if (this.variable) {
  8078. this.context.includeVariableInModule(this.variable);
  8079. }
  8080. }
  8081. this.object.include(context, includeChildrenRecursively);
  8082. this.property.include(context, includeChildrenRecursively);
  8083. }
  8084. }
  8085. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8086. if (path.length === 0)
  8087. return baseVariable;
  8088. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8089. return null;
  8090. const exportName = path[0].key;
  8091. const variable = baseVariable.context.traceExport(exportName);
  8092. if (!variable) {
  8093. const fileName = baseVariable.context.fileName;
  8094. astContext.warn({
  8095. code: 'MISSING_EXPORT',
  8096. exporter: relativeId(fileName),
  8097. importer: relativeId(astContext.fileName),
  8098. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  8099. missing: exportName,
  8100. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  8101. }, path[0].pos);
  8102. return 'undefined';
  8103. }
  8104. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8105. }
  8106. class CallExpressionBase extends NodeBase {
  8107. constructor() {
  8108. super(...arguments);
  8109. this.returnExpression = null;
  8110. this.deoptimizableDependentExpressions = [];
  8111. this.expressionsToBeDeoptimized = new Set();
  8112. }
  8113. deoptimizeCache() {
  8114. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  8115. this.returnExpression = UNKNOWN_EXPRESSION;
  8116. for (const expression of this.deoptimizableDependentExpressions) {
  8117. expression.deoptimizeCache();
  8118. }
  8119. for (const expression of this.expressionsToBeDeoptimized) {
  8120. expression.deoptimizePath(UNKNOWN_PATH);
  8121. }
  8122. }
  8123. }
  8124. deoptimizePath(path) {
  8125. if (path.length === 0 ||
  8126. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8127. return;
  8128. }
  8129. const returnExpression = this.getReturnExpression();
  8130. if (returnExpression !== UNKNOWN_EXPRESSION) {
  8131. returnExpression.deoptimizePath(path);
  8132. }
  8133. }
  8134. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8135. const returnExpression = this.getReturnExpression(recursionTracker);
  8136. if (returnExpression === UNKNOWN_EXPRESSION) {
  8137. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8138. }
  8139. else {
  8140. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8141. this.expressionsToBeDeoptimized.add(interaction.thisArg);
  8142. returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8143. }, undefined);
  8144. }
  8145. }
  8146. getLiteralValueAtPath(path, recursionTracker, origin) {
  8147. const returnExpression = this.getReturnExpression(recursionTracker);
  8148. if (returnExpression === UNKNOWN_EXPRESSION) {
  8149. return UnknownValue;
  8150. }
  8151. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8152. this.deoptimizableDependentExpressions.push(origin);
  8153. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  8154. }, UnknownValue);
  8155. }
  8156. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8157. const returnExpression = this.getReturnExpression(recursionTracker);
  8158. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  8159. return UNKNOWN_EXPRESSION;
  8160. }
  8161. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8162. this.deoptimizableDependentExpressions.push(origin);
  8163. return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8164. }, UNKNOWN_EXPRESSION);
  8165. }
  8166. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8167. const { type } = interaction;
  8168. if (type === INTERACTION_CALLED) {
  8169. if ((interaction.withNew
  8170. ? context.instantiated
  8171. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
  8172. return false;
  8173. }
  8174. }
  8175. else if ((type === INTERACTION_ASSIGNED
  8176. ? context.assigned
  8177. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  8178. return false;
  8179. }
  8180. return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
  8181. }
  8182. }
  8183. class CallExpression extends CallExpressionBase {
  8184. bind() {
  8185. super.bind();
  8186. if (this.callee instanceof Identifier) {
  8187. const variable = this.scope.findVariable(this.callee.name);
  8188. if (variable.isNamespace) {
  8189. this.context.warn({
  8190. code: 'CANNOT_CALL_NAMESPACE',
  8191. message: `Cannot call a namespace ('${this.callee.name}')`
  8192. }, this.start);
  8193. }
  8194. if (this.callee.name === 'eval') {
  8195. this.context.warn({
  8196. code: 'EVAL',
  8197. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8198. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  8199. }, this.start);
  8200. }
  8201. }
  8202. this.interaction = {
  8203. args: this.arguments,
  8204. thisArg: this.callee instanceof MemberExpression && !this.callee.variable
  8205. ? this.callee.object
  8206. : null,
  8207. type: INTERACTION_CALLED,
  8208. withNew: false
  8209. };
  8210. }
  8211. hasEffects(context) {
  8212. try {
  8213. for (const argument of this.arguments) {
  8214. if (argument.hasEffects(context))
  8215. return true;
  8216. }
  8217. if (this.context.options.treeshake.annotations &&
  8218. this.annotations)
  8219. return false;
  8220. return (this.callee.hasEffects(context) ||
  8221. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  8222. }
  8223. finally {
  8224. if (!this.deoptimized)
  8225. this.applyDeoptimizations();
  8226. }
  8227. }
  8228. include(context, includeChildrenRecursively) {
  8229. if (!this.deoptimized)
  8230. this.applyDeoptimizations();
  8231. if (includeChildrenRecursively) {
  8232. super.include(context, includeChildrenRecursively);
  8233. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  8234. this.callee instanceof Identifier &&
  8235. this.callee.variable) {
  8236. this.callee.variable.markCalledFromTryStatement();
  8237. }
  8238. }
  8239. else {
  8240. this.included = true;
  8241. this.callee.include(context, false);
  8242. }
  8243. this.callee.includeCallArguments(context, this.arguments);
  8244. }
  8245. render(code, options, { renderedSurroundingElement } = BLANK) {
  8246. this.callee.render(code, options, {
  8247. isCalleeOfRenderedParent: true,
  8248. renderedSurroundingElement
  8249. });
  8250. renderCallArguments(code, options, this);
  8251. }
  8252. applyDeoptimizations() {
  8253. this.deoptimized = true;
  8254. if (this.interaction.thisArg) {
  8255. this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  8256. }
  8257. for (const argument of this.arguments) {
  8258. // This will make sure all properties of parameters behave as "unknown"
  8259. argument.deoptimizePath(UNKNOWN_PATH);
  8260. }
  8261. this.context.requestTreeshakingPass();
  8262. }
  8263. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  8264. if (this.returnExpression === null) {
  8265. this.returnExpression = UNKNOWN_EXPRESSION;
  8266. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  8267. }
  8268. return this.returnExpression;
  8269. }
  8270. }
  8271. class CatchScope extends ParameterScope {
  8272. addDeclaration(identifier, context, init, isHoisted) {
  8273. const existingParameter = this.variables.get(identifier.name);
  8274. if (existingParameter) {
  8275. // While we still create a hoisted declaration, the initializer goes to
  8276. // the parameter. Note that technically, the declaration now belongs to
  8277. // two variables, which is not correct but should not cause issues.
  8278. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  8279. existingParameter.addDeclaration(identifier, init);
  8280. return existingParameter;
  8281. }
  8282. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  8283. }
  8284. }
  8285. class CatchClause extends NodeBase {
  8286. createScope(parentScope) {
  8287. this.scope = new CatchScope(parentScope, this.context);
  8288. }
  8289. parseNode(esTreeNode) {
  8290. // Parameters need to be declared first as the logic is that initializers
  8291. // of hoisted body variables are associated with parameters of the same
  8292. // name instead of the variable
  8293. const { param } = esTreeNode;
  8294. if (param) {
  8295. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  8296. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  8297. }
  8298. super.parseNode(esTreeNode);
  8299. }
  8300. }
  8301. class ChainExpression extends NodeBase {
  8302. }
  8303. class ClassBodyScope extends ChildScope {
  8304. constructor(parent, classNode, context) {
  8305. super(parent);
  8306. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  8307. this.instanceScope = new ChildScope(this);
  8308. this.instanceScope.variables.set('this', new ThisVariable(context));
  8309. }
  8310. findLexicalBoundary() {
  8311. return this;
  8312. }
  8313. }
  8314. class ClassBody extends NodeBase {
  8315. createScope(parentScope) {
  8316. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  8317. }
  8318. include(context, includeChildrenRecursively) {
  8319. this.included = true;
  8320. this.context.includeVariableInModule(this.scope.thisVariable);
  8321. for (const definition of this.body) {
  8322. definition.include(context, includeChildrenRecursively);
  8323. }
  8324. }
  8325. parseNode(esTreeNode) {
  8326. const body = (this.body = []);
  8327. for (const definition of esTreeNode.body) {
  8328. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  8329. }
  8330. super.parseNode(esTreeNode);
  8331. }
  8332. applyDeoptimizations() { }
  8333. }
  8334. class MethodBase extends NodeBase {
  8335. constructor() {
  8336. super(...arguments);
  8337. this.accessedValue = null;
  8338. }
  8339. // As getter properties directly receive their values from fixed function
  8340. // expressions, there is no known situation where a getter is deoptimized.
  8341. deoptimizeCache() { }
  8342. deoptimizePath(path) {
  8343. this.getAccessedValue().deoptimizePath(path);
  8344. }
  8345. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8346. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8347. return this.value.deoptimizeThisOnInteractionAtPath({
  8348. args: NO_ARGS,
  8349. thisArg: interaction.thisArg,
  8350. type: INTERACTION_CALLED,
  8351. withNew: false
  8352. }, EMPTY_PATH, recursionTracker);
  8353. }
  8354. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8355. return this.value.deoptimizeThisOnInteractionAtPath({
  8356. args: interaction.args,
  8357. thisArg: interaction.thisArg,
  8358. type: INTERACTION_CALLED,
  8359. withNew: false
  8360. }, EMPTY_PATH, recursionTracker);
  8361. }
  8362. this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8363. }
  8364. getLiteralValueAtPath(path, recursionTracker, origin) {
  8365. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  8366. }
  8367. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8368. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8369. }
  8370. hasEffects(context) {
  8371. return this.key.hasEffects(context);
  8372. }
  8373. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8374. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8375. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8376. args: NO_ARGS,
  8377. thisArg: interaction.thisArg,
  8378. type: INTERACTION_CALLED,
  8379. withNew: false
  8380. }, context);
  8381. }
  8382. // setters are only called for empty paths
  8383. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8384. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8385. args: interaction.args,
  8386. thisArg: interaction.thisArg,
  8387. type: INTERACTION_CALLED,
  8388. withNew: false
  8389. }, context);
  8390. }
  8391. return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
  8392. }
  8393. applyDeoptimizations() { }
  8394. getAccessedValue() {
  8395. if (this.accessedValue === null) {
  8396. if (this.kind === 'get') {
  8397. this.accessedValue = UNKNOWN_EXPRESSION;
  8398. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8399. }
  8400. else {
  8401. return (this.accessedValue = this.value);
  8402. }
  8403. }
  8404. return this.accessedValue;
  8405. }
  8406. }
  8407. class MethodDefinition extends MethodBase {
  8408. applyDeoptimizations() { }
  8409. }
  8410. class ObjectMember extends ExpressionEntity {
  8411. constructor(object, key) {
  8412. super();
  8413. this.object = object;
  8414. this.key = key;
  8415. }
  8416. deoptimizePath(path) {
  8417. this.object.deoptimizePath([this.key, ...path]);
  8418. }
  8419. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8420. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  8421. }
  8422. getLiteralValueAtPath(path, recursionTracker, origin) {
  8423. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  8424. }
  8425. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8426. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  8427. }
  8428. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8429. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  8430. }
  8431. }
  8432. class ClassNode extends NodeBase {
  8433. constructor() {
  8434. super(...arguments);
  8435. this.objectEntity = null;
  8436. }
  8437. createScope(parentScope) {
  8438. this.scope = new ChildScope(parentScope);
  8439. }
  8440. deoptimizeCache() {
  8441. this.getObjectEntity().deoptimizeAllProperties();
  8442. }
  8443. deoptimizePath(path) {
  8444. this.getObjectEntity().deoptimizePath(path);
  8445. }
  8446. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8447. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8448. }
  8449. getLiteralValueAtPath(path, recursionTracker, origin) {
  8450. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8451. }
  8452. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8453. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8454. }
  8455. hasEffects(context) {
  8456. var _a, _b;
  8457. if (!this.deoptimized)
  8458. this.applyDeoptimizations();
  8459. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  8460. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  8461. return initEffect || super.hasEffects(context);
  8462. }
  8463. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8464. var _a;
  8465. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  8466. return (!interaction.withNew ||
  8467. (this.classConstructor !== null
  8468. ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
  8469. : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8470. false);
  8471. }
  8472. else {
  8473. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8474. }
  8475. }
  8476. include(context, includeChildrenRecursively) {
  8477. var _a;
  8478. if (!this.deoptimized)
  8479. this.applyDeoptimizations();
  8480. this.included = true;
  8481. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  8482. this.body.include(context, includeChildrenRecursively);
  8483. if (this.id) {
  8484. this.id.markDeclarationReached();
  8485. this.id.include();
  8486. }
  8487. }
  8488. initialise() {
  8489. var _a;
  8490. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  8491. for (const method of this.body.body) {
  8492. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8493. this.classConstructor = method;
  8494. return;
  8495. }
  8496. }
  8497. this.classConstructor = null;
  8498. }
  8499. applyDeoptimizations() {
  8500. this.deoptimized = true;
  8501. for (const definition of this.body.body) {
  8502. if (!(definition.static ||
  8503. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8504. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8505. definition.deoptimizePath(UNKNOWN_PATH);
  8506. }
  8507. }
  8508. this.context.requestTreeshakingPass();
  8509. }
  8510. getObjectEntity() {
  8511. if (this.objectEntity !== null) {
  8512. return this.objectEntity;
  8513. }
  8514. const staticProperties = [];
  8515. const dynamicMethods = [];
  8516. for (const definition of this.body.body) {
  8517. const properties = definition.static ? staticProperties : dynamicMethods;
  8518. const definitionKind = definition.kind;
  8519. // Note that class fields do not end up on the prototype
  8520. if (properties === dynamicMethods && !definitionKind)
  8521. continue;
  8522. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8523. let key;
  8524. if (definition.computed) {
  8525. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8526. if (typeof keyValue === 'symbol') {
  8527. properties.push({ key: UnknownKey, kind, property: definition });
  8528. continue;
  8529. }
  8530. else {
  8531. key = String(keyValue);
  8532. }
  8533. }
  8534. else {
  8535. key =
  8536. definition.key instanceof Identifier
  8537. ? definition.key.name
  8538. : String(definition.key.value);
  8539. }
  8540. properties.push({ key, kind, property: definition });
  8541. }
  8542. staticProperties.unshift({
  8543. key: 'prototype',
  8544. kind: 'init',
  8545. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  8546. });
  8547. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8548. }
  8549. }
  8550. class ClassDeclaration extends ClassNode {
  8551. initialise() {
  8552. super.initialise();
  8553. if (this.id !== null) {
  8554. this.id.variable.isId = true;
  8555. }
  8556. }
  8557. parseNode(esTreeNode) {
  8558. if (esTreeNode.id !== null) {
  8559. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8560. }
  8561. super.parseNode(esTreeNode);
  8562. }
  8563. render(code, options) {
  8564. const { exportNamesByVariable, format, snippets: { _ } } = options;
  8565. if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
  8566. code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
  8567. }
  8568. super.render(code, options);
  8569. }
  8570. }
  8571. class ClassExpression extends ClassNode {
  8572. render(code, options, { renderedSurroundingElement } = BLANK) {
  8573. super.render(code, options);
  8574. if (renderedSurroundingElement === ExpressionStatement$1) {
  8575. code.appendRight(this.start, '(');
  8576. code.prependLeft(this.end, ')');
  8577. }
  8578. }
  8579. }
  8580. class MultiExpression extends ExpressionEntity {
  8581. constructor(expressions) {
  8582. super();
  8583. this.expressions = expressions;
  8584. this.included = false;
  8585. }
  8586. deoptimizePath(path) {
  8587. for (const expression of this.expressions) {
  8588. expression.deoptimizePath(path);
  8589. }
  8590. }
  8591. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8592. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
  8593. }
  8594. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8595. for (const expression of this.expressions) {
  8596. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  8597. return true;
  8598. }
  8599. return false;
  8600. }
  8601. }
  8602. class ConditionalExpression extends NodeBase {
  8603. constructor() {
  8604. super(...arguments);
  8605. this.expressionsToBeDeoptimized = [];
  8606. this.isBranchResolutionAnalysed = false;
  8607. this.usedBranch = null;
  8608. }
  8609. deoptimizeCache() {
  8610. if (this.usedBranch !== null) {
  8611. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  8612. this.usedBranch = null;
  8613. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  8614. for (const expression of this.expressionsToBeDeoptimized) {
  8615. expression.deoptimizeCache();
  8616. }
  8617. }
  8618. }
  8619. deoptimizePath(path) {
  8620. const usedBranch = this.getUsedBranch();
  8621. if (!usedBranch) {
  8622. this.consequent.deoptimizePath(path);
  8623. this.alternate.deoptimizePath(path);
  8624. }
  8625. else {
  8626. usedBranch.deoptimizePath(path);
  8627. }
  8628. }
  8629. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8630. this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8631. this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8632. }
  8633. getLiteralValueAtPath(path, recursionTracker, origin) {
  8634. const usedBranch = this.getUsedBranch();
  8635. if (!usedBranch)
  8636. return UnknownValue;
  8637. this.expressionsToBeDeoptimized.push(origin);
  8638. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  8639. }
  8640. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8641. const usedBranch = this.getUsedBranch();
  8642. if (!usedBranch)
  8643. return new MultiExpression([
  8644. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  8645. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  8646. ]);
  8647. this.expressionsToBeDeoptimized.push(origin);
  8648. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8649. }
  8650. hasEffects(context) {
  8651. if (this.test.hasEffects(context))
  8652. return true;
  8653. const usedBranch = this.getUsedBranch();
  8654. if (!usedBranch) {
  8655. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  8656. }
  8657. return usedBranch.hasEffects(context);
  8658. }
  8659. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8660. const usedBranch = this.getUsedBranch();
  8661. if (!usedBranch) {
  8662. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8663. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  8664. }
  8665. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  8666. }
  8667. include(context, includeChildrenRecursively) {
  8668. this.included = true;
  8669. const usedBranch = this.getUsedBranch();
  8670. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  8671. this.test.include(context, includeChildrenRecursively);
  8672. this.consequent.include(context, includeChildrenRecursively);
  8673. this.alternate.include(context, includeChildrenRecursively);
  8674. }
  8675. else {
  8676. usedBranch.include(context, includeChildrenRecursively);
  8677. }
  8678. }
  8679. includeCallArguments(context, args) {
  8680. const usedBranch = this.getUsedBranch();
  8681. if (!usedBranch) {
  8682. this.consequent.includeCallArguments(context, args);
  8683. this.alternate.includeCallArguments(context, args);
  8684. }
  8685. else {
  8686. usedBranch.includeCallArguments(context, args);
  8687. }
  8688. }
  8689. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8690. const usedBranch = this.getUsedBranch();
  8691. if (!this.test.included) {
  8692. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  8693. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  8694. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  8695. : colonPos) + 1);
  8696. if (preventASI) {
  8697. removeLineBreaks(code, inclusionStart, usedBranch.start);
  8698. }
  8699. code.remove(this.start, inclusionStart);
  8700. if (this.consequent.included) {
  8701. code.remove(colonPos, this.end);
  8702. }
  8703. removeAnnotations(this, code);
  8704. usedBranch.render(code, options, {
  8705. isCalleeOfRenderedParent,
  8706. preventASI: true,
  8707. renderedParentType: renderedParentType || this.parent.type,
  8708. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8709. });
  8710. }
  8711. else {
  8712. this.test.render(code, options, { renderedSurroundingElement });
  8713. this.consequent.render(code, options);
  8714. this.alternate.render(code, options);
  8715. }
  8716. }
  8717. getUsedBranch() {
  8718. if (this.isBranchResolutionAnalysed) {
  8719. return this.usedBranch;
  8720. }
  8721. this.isBranchResolutionAnalysed = true;
  8722. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8723. return typeof testValue === 'symbol'
  8724. ? null
  8725. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  8726. }
  8727. }
  8728. class ContinueStatement extends NodeBase {
  8729. hasEffects(context) {
  8730. if (this.label) {
  8731. if (!context.ignore.labels.has(this.label.name))
  8732. return true;
  8733. context.includedLabels.add(this.label.name);
  8734. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8735. }
  8736. else {
  8737. if (!context.ignore.continues)
  8738. return true;
  8739. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  8740. }
  8741. return false;
  8742. }
  8743. include(context) {
  8744. this.included = true;
  8745. if (this.label) {
  8746. this.label.include();
  8747. context.includedLabels.add(this.label.name);
  8748. }
  8749. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  8750. }
  8751. }
  8752. class DoWhileStatement extends NodeBase {
  8753. hasEffects(context) {
  8754. if (this.test.hasEffects(context))
  8755. return true;
  8756. const { brokenFlow, ignore: { breaks, continues } } = context;
  8757. context.ignore.breaks = true;
  8758. context.ignore.continues = true;
  8759. if (this.body.hasEffects(context))
  8760. return true;
  8761. context.ignore.breaks = breaks;
  8762. context.ignore.continues = continues;
  8763. context.brokenFlow = brokenFlow;
  8764. return false;
  8765. }
  8766. include(context, includeChildrenRecursively) {
  8767. this.included = true;
  8768. this.test.include(context, includeChildrenRecursively);
  8769. const { brokenFlow } = context;
  8770. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8771. context.brokenFlow = brokenFlow;
  8772. }
  8773. }
  8774. class EmptyStatement extends NodeBase {
  8775. hasEffects() {
  8776. return false;
  8777. }
  8778. }
  8779. class ExportAllDeclaration extends NodeBase {
  8780. hasEffects() {
  8781. return false;
  8782. }
  8783. initialise() {
  8784. this.context.addExport(this);
  8785. }
  8786. render(code, _options, nodeRenderOptions) {
  8787. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  8788. }
  8789. applyDeoptimizations() { }
  8790. }
  8791. ExportAllDeclaration.prototype.needsBoundaries = true;
  8792. class FunctionDeclaration extends FunctionNode {
  8793. initialise() {
  8794. super.initialise();
  8795. if (this.id !== null) {
  8796. this.id.variable.isId = true;
  8797. }
  8798. }
  8799. parseNode(esTreeNode) {
  8800. if (esTreeNode.id !== null) {
  8801. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8802. }
  8803. super.parseNode(esTreeNode);
  8804. }
  8805. }
  8806. // The header ends at the first non-white-space after "default"
  8807. function getDeclarationStart(code, start) {
  8808. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  8809. }
  8810. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  8811. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  8812. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  8813. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  8814. if (generatorStarPos === -1) {
  8815. return declarationEnd;
  8816. }
  8817. return declarationEnd + generatorStarPos + 1;
  8818. }
  8819. class ExportDefaultDeclaration extends NodeBase {
  8820. include(context, includeChildrenRecursively) {
  8821. super.include(context, includeChildrenRecursively);
  8822. if (includeChildrenRecursively) {
  8823. this.context.includeVariableInModule(this.variable);
  8824. }
  8825. }
  8826. initialise() {
  8827. const declaration = this.declaration;
  8828. this.declarationName =
  8829. (declaration.id && declaration.id.name) || this.declaration.name;
  8830. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  8831. this.context.addExport(this);
  8832. }
  8833. render(code, options, nodeRenderOptions) {
  8834. const { start, end } = nodeRenderOptions;
  8835. const declarationStart = getDeclarationStart(code.original, this.start);
  8836. if (this.declaration instanceof FunctionDeclaration) {
  8837. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  8838. }
  8839. else if (this.declaration instanceof ClassDeclaration) {
  8840. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  8841. }
  8842. else if (this.variable.getOriginalVariable() !== this.variable) {
  8843. // Remove altogether to prevent re-declaring the same variable
  8844. treeshakeNode(this, code, start, end);
  8845. return;
  8846. }
  8847. else if (this.variable.included) {
  8848. this.renderVariableDeclaration(code, declarationStart, options);
  8849. }
  8850. else {
  8851. code.remove(this.start, declarationStart);
  8852. this.declaration.render(code, options, {
  8853. renderedSurroundingElement: ExpressionStatement$1
  8854. });
  8855. if (code.original[this.end - 1] !== ';') {
  8856. code.appendLeft(this.end, ';');
  8857. }
  8858. return;
  8859. }
  8860. this.declaration.render(code, options);
  8861. }
  8862. applyDeoptimizations() { }
  8863. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  8864. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  8865. const name = this.variable.getName(getPropertyAccess);
  8866. // Remove `export default`
  8867. code.remove(this.start, declarationStart);
  8868. if (needsId) {
  8869. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  8870. }
  8871. if (format === 'system' &&
  8872. this.declaration instanceof ClassDeclaration &&
  8873. exportNamesByVariable.has(this.variable)) {
  8874. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  8875. }
  8876. }
  8877. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  8878. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  8879. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  8880. if (systemExportNames) {
  8881. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  8882. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  8883. }
  8884. else {
  8885. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  8886. if (!hasTrailingSemicolon) {
  8887. code.appendLeft(this.end, ';');
  8888. }
  8889. }
  8890. }
  8891. }
  8892. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  8893. class ExportNamedDeclaration extends NodeBase {
  8894. bind() {
  8895. var _a;
  8896. // Do not bind specifiers
  8897. (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
  8898. }
  8899. hasEffects(context) {
  8900. var _a;
  8901. return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  8902. }
  8903. initialise() {
  8904. this.context.addExport(this);
  8905. }
  8906. render(code, options, nodeRenderOptions) {
  8907. const { start, end } = nodeRenderOptions;
  8908. if (this.declaration === null) {
  8909. code.remove(start, end);
  8910. }
  8911. else {
  8912. code.remove(this.start, this.declaration.start);
  8913. this.declaration.render(code, options, { end, start });
  8914. }
  8915. }
  8916. applyDeoptimizations() { }
  8917. }
  8918. ExportNamedDeclaration.prototype.needsBoundaries = true;
  8919. class ExportSpecifier extends NodeBase {
  8920. applyDeoptimizations() { }
  8921. }
  8922. class ForInStatement extends NodeBase {
  8923. createScope(parentScope) {
  8924. this.scope = new BlockScope(parentScope);
  8925. }
  8926. hasEffects(context) {
  8927. const { deoptimized, left, right } = this;
  8928. if (!deoptimized)
  8929. this.applyDeoptimizations();
  8930. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  8931. return true;
  8932. const { brokenFlow, ignore: { breaks, continues } } = context;
  8933. context.ignore.breaks = true;
  8934. context.ignore.continues = true;
  8935. if (this.body.hasEffects(context))
  8936. return true;
  8937. context.ignore.breaks = breaks;
  8938. context.ignore.continues = continues;
  8939. context.brokenFlow = brokenFlow;
  8940. return false;
  8941. }
  8942. include(context, includeChildrenRecursively) {
  8943. const { body, deoptimized, left, right } = this;
  8944. if (!deoptimized)
  8945. this.applyDeoptimizations();
  8946. this.included = true;
  8947. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  8948. right.include(context, includeChildrenRecursively);
  8949. const { brokenFlow } = context;
  8950. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8951. context.brokenFlow = brokenFlow;
  8952. }
  8953. initialise() {
  8954. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  8955. }
  8956. render(code, options) {
  8957. this.left.render(code, options, NO_SEMICOLON);
  8958. this.right.render(code, options, NO_SEMICOLON);
  8959. // handle no space between "in" and the right side
  8960. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  8961. code.prependLeft(this.right.start, ' ');
  8962. }
  8963. this.body.render(code, options);
  8964. }
  8965. applyDeoptimizations() {
  8966. this.deoptimized = true;
  8967. this.left.deoptimizePath(EMPTY_PATH);
  8968. this.context.requestTreeshakingPass();
  8969. }
  8970. }
  8971. class ForOfStatement extends NodeBase {
  8972. createScope(parentScope) {
  8973. this.scope = new BlockScope(parentScope);
  8974. }
  8975. hasEffects() {
  8976. if (!this.deoptimized)
  8977. this.applyDeoptimizations();
  8978. // Placeholder until proper Symbol.Iterator support
  8979. return true;
  8980. }
  8981. include(context, includeChildrenRecursively) {
  8982. const { body, deoptimized, left, right } = this;
  8983. if (!deoptimized)
  8984. this.applyDeoptimizations();
  8985. this.included = true;
  8986. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  8987. right.include(context, includeChildrenRecursively);
  8988. const { brokenFlow } = context;
  8989. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8990. context.brokenFlow = brokenFlow;
  8991. }
  8992. initialise() {
  8993. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  8994. }
  8995. render(code, options) {
  8996. this.left.render(code, options, NO_SEMICOLON);
  8997. this.right.render(code, options, NO_SEMICOLON);
  8998. // handle no space between "of" and the right side
  8999. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  9000. code.prependLeft(this.right.start, ' ');
  9001. }
  9002. this.body.render(code, options);
  9003. }
  9004. applyDeoptimizations() {
  9005. this.deoptimized = true;
  9006. this.left.deoptimizePath(EMPTY_PATH);
  9007. this.context.requestTreeshakingPass();
  9008. }
  9009. }
  9010. class ForStatement extends NodeBase {
  9011. createScope(parentScope) {
  9012. this.scope = new BlockScope(parentScope);
  9013. }
  9014. hasEffects(context) {
  9015. var _a, _b, _c;
  9016. if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
  9017. ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
  9018. ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
  9019. return true;
  9020. const { brokenFlow, ignore: { breaks, continues } } = context;
  9021. context.ignore.breaks = true;
  9022. context.ignore.continues = true;
  9023. if (this.body.hasEffects(context))
  9024. return true;
  9025. context.ignore.breaks = breaks;
  9026. context.ignore.continues = continues;
  9027. context.brokenFlow = brokenFlow;
  9028. return false;
  9029. }
  9030. include(context, includeChildrenRecursively) {
  9031. var _a, _b, _c;
  9032. this.included = true;
  9033. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9034. (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  9035. const { brokenFlow } = context;
  9036. (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
  9037. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9038. context.brokenFlow = brokenFlow;
  9039. }
  9040. render(code, options) {
  9041. var _a, _b, _c;
  9042. (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
  9043. (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
  9044. (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
  9045. this.body.render(code, options);
  9046. }
  9047. }
  9048. class FunctionExpression extends FunctionNode {
  9049. render(code, options, { renderedSurroundingElement } = BLANK) {
  9050. super.render(code, options);
  9051. if (renderedSurroundingElement === ExpressionStatement$1) {
  9052. code.appendRight(this.start, '(');
  9053. code.prependLeft(this.end, ')');
  9054. }
  9055. }
  9056. }
  9057. class TrackingScope extends BlockScope {
  9058. constructor() {
  9059. super(...arguments);
  9060. this.hoistedDeclarations = [];
  9061. }
  9062. addDeclaration(identifier, context, init, isHoisted) {
  9063. this.hoistedDeclarations.push(identifier);
  9064. return super.addDeclaration(identifier, context, init, isHoisted);
  9065. }
  9066. }
  9067. const unset = Symbol('unset');
  9068. class IfStatement extends NodeBase {
  9069. constructor() {
  9070. super(...arguments);
  9071. this.testValue = unset;
  9072. }
  9073. deoptimizeCache() {
  9074. this.testValue = UnknownValue;
  9075. }
  9076. hasEffects(context) {
  9077. var _a;
  9078. if (this.test.hasEffects(context)) {
  9079. return true;
  9080. }
  9081. const testValue = this.getTestValue();
  9082. if (typeof testValue === 'symbol') {
  9083. const { brokenFlow } = context;
  9084. if (this.consequent.hasEffects(context))
  9085. return true;
  9086. const consequentBrokenFlow = context.brokenFlow;
  9087. context.brokenFlow = brokenFlow;
  9088. if (this.alternate === null)
  9089. return false;
  9090. if (this.alternate.hasEffects(context))
  9091. return true;
  9092. context.brokenFlow =
  9093. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9094. return false;
  9095. }
  9096. return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9097. }
  9098. include(context, includeChildrenRecursively) {
  9099. this.included = true;
  9100. if (includeChildrenRecursively) {
  9101. this.includeRecursively(includeChildrenRecursively, context);
  9102. }
  9103. else {
  9104. const testValue = this.getTestValue();
  9105. if (typeof testValue === 'symbol') {
  9106. this.includeUnknownTest(context);
  9107. }
  9108. else {
  9109. this.includeKnownTest(context, testValue);
  9110. }
  9111. }
  9112. }
  9113. parseNode(esTreeNode) {
  9114. this.consequentScope = new TrackingScope(this.scope);
  9115. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  9116. if (esTreeNode.alternate) {
  9117. this.alternateScope = new TrackingScope(this.scope);
  9118. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  9119. }
  9120. super.parseNode(esTreeNode);
  9121. }
  9122. render(code, options) {
  9123. const { snippets: { getPropertyAccess } } = options;
  9124. // Note that unknown test values are always included
  9125. const testValue = this.getTestValue();
  9126. const hoistedDeclarations = [];
  9127. const includesIfElse = this.test.included;
  9128. const noTreeshake = !this.context.options.treeshake;
  9129. if (includesIfElse) {
  9130. this.test.render(code, options);
  9131. }
  9132. else {
  9133. code.remove(this.start, this.consequent.start);
  9134. }
  9135. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  9136. this.consequent.render(code, options);
  9137. }
  9138. else {
  9139. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  9140. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  9141. }
  9142. if (this.alternate) {
  9143. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  9144. if (includesIfElse) {
  9145. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  9146. code.prependLeft(this.alternate.start, ' ');
  9147. }
  9148. }
  9149. else {
  9150. code.remove(this.consequent.end, this.alternate.start);
  9151. }
  9152. this.alternate.render(code, options);
  9153. }
  9154. else {
  9155. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  9156. code.overwrite(this.alternate.start, this.end, ';');
  9157. }
  9158. else {
  9159. code.remove(this.consequent.end, this.end);
  9160. }
  9161. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  9162. }
  9163. }
  9164. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  9165. }
  9166. applyDeoptimizations() { }
  9167. getTestValue() {
  9168. if (this.testValue === unset) {
  9169. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  9170. }
  9171. return this.testValue;
  9172. }
  9173. includeKnownTest(context, testValue) {
  9174. var _a;
  9175. if (this.test.shouldBeIncluded(context)) {
  9176. this.test.include(context, false);
  9177. }
  9178. if (testValue && this.consequent.shouldBeIncluded(context)) {
  9179. this.consequent.include(context, false, { asSingleStatement: true });
  9180. }
  9181. if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
  9182. this.alternate.include(context, false, { asSingleStatement: true });
  9183. }
  9184. }
  9185. includeRecursively(includeChildrenRecursively, context) {
  9186. var _a;
  9187. this.test.include(context, includeChildrenRecursively);
  9188. this.consequent.include(context, includeChildrenRecursively);
  9189. (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  9190. }
  9191. includeUnknownTest(context) {
  9192. var _a;
  9193. this.test.include(context, false);
  9194. const { brokenFlow } = context;
  9195. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  9196. if (this.consequent.shouldBeIncluded(context)) {
  9197. this.consequent.include(context, false, { asSingleStatement: true });
  9198. consequentBrokenFlow = context.brokenFlow;
  9199. context.brokenFlow = brokenFlow;
  9200. }
  9201. if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
  9202. this.alternate.include(context, false, { asSingleStatement: true });
  9203. context.brokenFlow =
  9204. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9205. }
  9206. }
  9207. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  9208. const hoistedVars = [
  9209. ...new Set(hoistedDeclarations.map(identifier => {
  9210. const variable = identifier.variable;
  9211. return variable.included ? variable.getName(getPropertyAccess) : '';
  9212. }))
  9213. ]
  9214. .filter(Boolean)
  9215. .join(', ');
  9216. if (hoistedVars) {
  9217. const parentType = this.parent.type;
  9218. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  9219. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  9220. if (needsBraces) {
  9221. code.appendLeft(this.end, ` }`);
  9222. }
  9223. }
  9224. }
  9225. shouldKeepAlternateBranch() {
  9226. let currentParent = this.parent;
  9227. do {
  9228. if (currentParent instanceof IfStatement && currentParent.alternate) {
  9229. return true;
  9230. }
  9231. if (currentParent instanceof BlockStatement) {
  9232. return false;
  9233. }
  9234. currentParent = currentParent.parent;
  9235. } while (currentParent);
  9236. return false;
  9237. }
  9238. }
  9239. class ImportDeclaration extends NodeBase {
  9240. // Do not bind specifiers
  9241. bind() { }
  9242. hasEffects() {
  9243. return false;
  9244. }
  9245. initialise() {
  9246. this.context.addImport(this);
  9247. }
  9248. render(code, _options, nodeRenderOptions) {
  9249. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9250. }
  9251. applyDeoptimizations() { }
  9252. }
  9253. ImportDeclaration.prototype.needsBoundaries = true;
  9254. class ImportDefaultSpecifier extends NodeBase {
  9255. applyDeoptimizations() { }
  9256. }
  9257. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9258. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  9259. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9260. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9261. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9262. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9263. const defaultInteropHelpersByInteropType = {
  9264. auto: INTEROP_DEFAULT_VARIABLE,
  9265. default: null,
  9266. defaultOnly: null,
  9267. esModule: null,
  9268. false: null,
  9269. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  9270. };
  9271. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9272. (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
  9273. const namespaceInteropHelpersByInteropType = {
  9274. auto: INTEROP_NAMESPACE_VARIABLE,
  9275. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9276. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9277. esModule: null,
  9278. false: null,
  9279. true: INTEROP_NAMESPACE_VARIABLE
  9280. };
  9281. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
  9282. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
  9283. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9284. const usedHelpers = new Set(additionalHelpers);
  9285. for (const variable of HELPER_NAMES) {
  9286. if (accessedGlobals.has(variable)) {
  9287. usedHelpers.add(variable);
  9288. }
  9289. }
  9290. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9291. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  9292. : '').join('');
  9293. };
  9294. const HELPER_GENERATORS = {
  9295. [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
  9296. const { _, getDirectReturnFunction, n } = snippets;
  9297. const [left, right] = getDirectReturnFunction(['e'], {
  9298. functionReturn: true,
  9299. lineBreakIndent: null,
  9300. name: INTEROP_DEFAULT_LEGACY_VARIABLE
  9301. });
  9302. return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  9303. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9304. },
  9305. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9306. const { _, getDirectReturnFunction, n } = snippets;
  9307. const [left, right] = getDirectReturnFunction(['e'], {
  9308. functionReturn: true,
  9309. lineBreakIndent: null,
  9310. name: INTEROP_DEFAULT_VARIABLE
  9311. });
  9312. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9313. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9314. },
  9315. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  9316. const { getDirectReturnFunction, getObject, n } = snippets;
  9317. const [left, right] = getDirectReturnFunction(['e'], {
  9318. functionReturn: true,
  9319. lineBreakIndent: null,
  9320. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9321. });
  9322. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  9323. ['__proto__', 'null'],
  9324. ['default', 'e']
  9325. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  9326. },
  9327. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9328. const { _, n } = snippets;
  9329. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  9330. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9331. `}${n}${n}`);
  9332. },
  9333. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  9334. const { _, getDirectReturnFunction, n } = snippets;
  9335. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9336. const [left, right] = getDirectReturnFunction(['e'], {
  9337. functionReturn: true,
  9338. lineBreakIndent: null,
  9339. name: INTEROP_NAMESPACE_VARIABLE
  9340. });
  9341. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9342. }
  9343. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  9344. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  9345. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9346. `}${n}${n}`);
  9347. },
  9348. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9349. const { _, cnst, n } = snippets;
  9350. const useForEach = cnst === 'var' && liveBindings;
  9351. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  9352. `${t}${loopOverNamespaces(`{${n}` +
  9353. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  9354. (liveBindings
  9355. ? useForEach
  9356. ? copyOwnPropertyLiveBinding
  9357. : copyPropertyLiveBinding
  9358. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  9359. `${t}${t}${t}}${n}` +
  9360. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  9361. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  9362. `}${n}${n}`);
  9363. }
  9364. };
  9365. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  9366. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  9367. const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9368. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  9369. const copyProperty = `{${n}` +
  9370. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
  9371. `${i}${t}}`;
  9372. return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  9373. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  9374. : ''});${n}` +
  9375. `${i}if${_}(e)${_}{${n}` +
  9376. `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  9377. `${i}}${n}` +
  9378. `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  9379. `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
  9380. };
  9381. const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
  9382. ? `for${_}(${cnst} k in e)${_}${body}`
  9383. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9384. isAsync: false,
  9385. name: null
  9386. })}${body})${s}`;
  9387. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  9388. if (useForEach) {
  9389. const [left, right] = getDirectReturnFunction(['e'], {
  9390. functionReturn: false,
  9391. lineBreakIndent: { base: t, t },
  9392. name: null
  9393. });
  9394. return (`m.forEach(${left}` +
  9395. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9396. isAsync: false,
  9397. name: null
  9398. })}${body})${right});`);
  9399. }
  9400. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  9401. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  9402. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  9403. };
  9404. const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
  9405. const { _, n } = snippets;
  9406. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  9407. copyOwnPropertyLiveBinding(t, i + t, snippets) +
  9408. `${i}}${n}`);
  9409. };
  9410. const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9411. const [left, right] = getDirectReturnFunction([], {
  9412. functionReturn: true,
  9413. lineBreakIndent: null,
  9414. name: null
  9415. });
  9416. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9417. `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9418. `${i}${t}enumerable:${_}true,${n}` +
  9419. `${i}${t}get:${_}${left}e[k]${right}${n}` +
  9420. `${i}});${n}`);
  9421. };
  9422. const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9423. const [left, right] = getDirectReturnFunction([], {
  9424. functionReturn: true,
  9425. lineBreakIndent: null,
  9426. name: null
  9427. });
  9428. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9429. `${i}if${_}(d)${_}{${n}` +
  9430. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9431. `${i}${t}${t}enumerable:${_}true,${n}` +
  9432. `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
  9433. `${i}${t}});${n}` +
  9434. `${i}}${n}`);
  9435. };
  9436. const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
  9437. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  9438. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  9439. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  9440. : fragment;
  9441. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  9442. function getToStringTagValue(getObject) {
  9443. return getObject([['value', "'Module'"]], {
  9444. lineBreakIndent: null
  9445. });
  9446. }
  9447. class ImportExpression extends NodeBase {
  9448. constructor() {
  9449. super(...arguments);
  9450. this.inlineNamespace = null;
  9451. this.mechanism = null;
  9452. this.resolution = null;
  9453. }
  9454. hasEffects() {
  9455. return true;
  9456. }
  9457. include(context, includeChildrenRecursively) {
  9458. if (!this.included) {
  9459. this.included = true;
  9460. this.context.includeDynamicImport(this);
  9461. this.scope.addAccessedDynamicImport(this);
  9462. }
  9463. this.source.include(context, includeChildrenRecursively);
  9464. }
  9465. initialise() {
  9466. this.context.addDynamicImport(this);
  9467. }
  9468. render(code, options) {
  9469. if (this.inlineNamespace) {
  9470. const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
  9471. const [left, right] = getDirectReturnFunction([], {
  9472. functionReturn: true,
  9473. lineBreakIndent: null,
  9474. name: null
  9475. });
  9476. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
  9477. return;
  9478. }
  9479. if (this.mechanism) {
  9480. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  9481. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  9482. }
  9483. this.source.render(code, options);
  9484. }
  9485. renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
  9486. code.overwrite(this.source.start, this.source.end, resolution);
  9487. if (namespaceExportName) {
  9488. const [left, right] = getDirectReturnFunction(['n'], {
  9489. functionReturn: true,
  9490. lineBreakIndent: null,
  9491. name: null
  9492. });
  9493. code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
  9494. }
  9495. }
  9496. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
  9497. const { format } = options;
  9498. this.inlineNamespace = null;
  9499. this.resolution = resolution;
  9500. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  9501. let helper;
  9502. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  9503. if (helper) {
  9504. accessedGlobals.push(helper);
  9505. }
  9506. if (accessedGlobals.length > 0) {
  9507. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9508. }
  9509. }
  9510. setInternalResolution(inlineNamespace) {
  9511. this.inlineNamespace = inlineNamespace;
  9512. }
  9513. applyDeoptimizations() { }
  9514. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  9515. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  9516. {
  9517. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  9518. format,
  9519. moduleId: this.context.module.id,
  9520. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  9521. }
  9522. ]);
  9523. if (mechanism) {
  9524. return { helper: null, mechanism };
  9525. }
  9526. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  9527. switch (format) {
  9528. case 'cjs': {
  9529. const helper = getInteropHelper(resolution, exportMode, interop);
  9530. let left = `require(`;
  9531. let right = `)`;
  9532. if (helper) {
  9533. left = `/*#__PURE__*/${helper}(${left}`;
  9534. right += ')';
  9535. }
  9536. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  9537. functionReturn: true,
  9538. lineBreakIndent: null,
  9539. name: null
  9540. });
  9541. left = `Promise.resolve().then(${functionLeft}${left}`;
  9542. right += `${functionRight})`;
  9543. if (!arrowFunctions && hasDynamicTarget) {
  9544. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9545. needsArrowReturnParens: false,
  9546. needsWrappedFunction: true
  9547. });
  9548. right = ')';
  9549. }
  9550. return {
  9551. helper,
  9552. mechanism: { left, right }
  9553. };
  9554. }
  9555. case 'amd': {
  9556. const resolve = compact ? 'c' : 'resolve';
  9557. const reject = compact ? 'e' : 'reject';
  9558. const helper = getInteropHelper(resolution, exportMode, interop);
  9559. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  9560. functionReturn: false,
  9561. lineBreakIndent: null,
  9562. name: null
  9563. });
  9564. const resolveNamespace = helper
  9565. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  9566. : resolve;
  9567. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  9568. functionReturn: false,
  9569. lineBreakIndent: null,
  9570. name: null
  9571. });
  9572. let left = `new Promise(${handlerLeft}require([`;
  9573. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  9574. if (!arrowFunctions && hasDynamicTarget) {
  9575. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9576. needsArrowReturnParens: false,
  9577. needsWrappedFunction: true
  9578. });
  9579. right = ')';
  9580. }
  9581. return {
  9582. helper,
  9583. mechanism: { left, right }
  9584. };
  9585. }
  9586. case 'system':
  9587. return {
  9588. helper: null,
  9589. mechanism: {
  9590. left: 'module.import(',
  9591. right: ')'
  9592. }
  9593. };
  9594. case 'es':
  9595. if (dynamicImportFunction) {
  9596. return {
  9597. helper: null,
  9598. mechanism: {
  9599. left: `${dynamicImportFunction}(`,
  9600. right: ')'
  9601. }
  9602. };
  9603. }
  9604. }
  9605. return { helper: null, mechanism: null };
  9606. }
  9607. }
  9608. function getInteropHelper(resolution, exportMode, interop) {
  9609. return exportMode === 'external'
  9610. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  9611. : exportMode === 'default'
  9612. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9613. : null;
  9614. }
  9615. const accessedImportGlobals = {
  9616. amd: ['require'],
  9617. cjs: ['require'],
  9618. system: ['module']
  9619. };
  9620. class ImportNamespaceSpecifier extends NodeBase {
  9621. applyDeoptimizations() { }
  9622. }
  9623. class ImportSpecifier extends NodeBase {
  9624. applyDeoptimizations() { }
  9625. }
  9626. class LabeledStatement extends NodeBase {
  9627. hasEffects(context) {
  9628. const brokenFlow = context.brokenFlow;
  9629. context.ignore.labels.add(this.label.name);
  9630. if (this.body.hasEffects(context))
  9631. return true;
  9632. context.ignore.labels.delete(this.label.name);
  9633. if (context.includedLabels.has(this.label.name)) {
  9634. context.includedLabels.delete(this.label.name);
  9635. context.brokenFlow = brokenFlow;
  9636. }
  9637. return false;
  9638. }
  9639. include(context, includeChildrenRecursively) {
  9640. this.included = true;
  9641. const brokenFlow = context.brokenFlow;
  9642. this.body.include(context, includeChildrenRecursively);
  9643. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  9644. this.label.include();
  9645. context.includedLabels.delete(this.label.name);
  9646. context.brokenFlow = brokenFlow;
  9647. }
  9648. }
  9649. render(code, options) {
  9650. if (this.label.included) {
  9651. this.label.render(code, options);
  9652. }
  9653. else {
  9654. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  9655. }
  9656. this.body.render(code, options);
  9657. }
  9658. }
  9659. class LogicalExpression extends NodeBase {
  9660. constructor() {
  9661. super(...arguments);
  9662. // We collect deoptimization information if usedBranch !== null
  9663. this.expressionsToBeDeoptimized = [];
  9664. this.isBranchResolutionAnalysed = false;
  9665. this.usedBranch = null;
  9666. }
  9667. deoptimizeCache() {
  9668. if (this.usedBranch) {
  9669. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  9670. this.usedBranch = null;
  9671. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9672. for (const expression of this.expressionsToBeDeoptimized) {
  9673. expression.deoptimizeCache();
  9674. }
  9675. // Request another pass because we need to ensure "include" runs again if
  9676. // it is rendered
  9677. this.context.requestTreeshakingPass();
  9678. }
  9679. }
  9680. deoptimizePath(path) {
  9681. const usedBranch = this.getUsedBranch();
  9682. if (!usedBranch) {
  9683. this.left.deoptimizePath(path);
  9684. this.right.deoptimizePath(path);
  9685. }
  9686. else {
  9687. usedBranch.deoptimizePath(path);
  9688. }
  9689. }
  9690. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9691. this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9692. this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9693. }
  9694. getLiteralValueAtPath(path, recursionTracker, origin) {
  9695. const usedBranch = this.getUsedBranch();
  9696. if (!usedBranch)
  9697. return UnknownValue;
  9698. this.expressionsToBeDeoptimized.push(origin);
  9699. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9700. }
  9701. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9702. const usedBranch = this.getUsedBranch();
  9703. if (!usedBranch)
  9704. return new MultiExpression([
  9705. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  9706. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  9707. ]);
  9708. this.expressionsToBeDeoptimized.push(origin);
  9709. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9710. }
  9711. hasEffects(context) {
  9712. if (this.left.hasEffects(context)) {
  9713. return true;
  9714. }
  9715. if (this.getUsedBranch() !== this.left) {
  9716. return this.right.hasEffects(context);
  9717. }
  9718. return false;
  9719. }
  9720. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9721. const usedBranch = this.getUsedBranch();
  9722. if (!usedBranch) {
  9723. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9724. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  9725. }
  9726. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9727. }
  9728. include(context, includeChildrenRecursively) {
  9729. this.included = true;
  9730. const usedBranch = this.getUsedBranch();
  9731. if (includeChildrenRecursively ||
  9732. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  9733. !usedBranch) {
  9734. this.left.include(context, includeChildrenRecursively);
  9735. this.right.include(context, includeChildrenRecursively);
  9736. }
  9737. else {
  9738. usedBranch.include(context, includeChildrenRecursively);
  9739. }
  9740. }
  9741. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9742. if (!this.left.included || !this.right.included) {
  9743. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  9744. if (this.right.included) {
  9745. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  9746. code.remove(this.start, removePos);
  9747. if (preventASI) {
  9748. removeLineBreaks(code, removePos, this.right.start);
  9749. }
  9750. }
  9751. else {
  9752. code.remove(operatorPos, this.end);
  9753. }
  9754. removeAnnotations(this, code);
  9755. this.getUsedBranch().render(code, options, {
  9756. isCalleeOfRenderedParent,
  9757. preventASI,
  9758. renderedParentType: renderedParentType || this.parent.type,
  9759. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9760. });
  9761. }
  9762. else {
  9763. this.left.render(code, options, {
  9764. preventASI,
  9765. renderedSurroundingElement
  9766. });
  9767. this.right.render(code, options);
  9768. }
  9769. }
  9770. getUsedBranch() {
  9771. if (!this.isBranchResolutionAnalysed) {
  9772. this.isBranchResolutionAnalysed = true;
  9773. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9774. if (typeof leftValue === 'symbol') {
  9775. return null;
  9776. }
  9777. else {
  9778. this.usedBranch =
  9779. (this.operator === '||' && leftValue) ||
  9780. (this.operator === '&&' && !leftValue) ||
  9781. (this.operator === '??' && leftValue != null)
  9782. ? this.left
  9783. : this.right;
  9784. }
  9785. }
  9786. return this.usedBranch;
  9787. }
  9788. }
  9789. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  9790. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  9791. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  9792. class MetaProperty extends NodeBase {
  9793. addAccessedGlobals(format, accessedGlobalsByScope) {
  9794. const metaProperty = this.metaProperty;
  9795. const accessedGlobals = (metaProperty &&
  9796. (metaProperty.startsWith(FILE_PREFIX) ||
  9797. metaProperty.startsWith(ASSET_PREFIX) ||
  9798. metaProperty.startsWith(CHUNK_PREFIX))
  9799. ? accessedFileUrlGlobals
  9800. : accessedMetaUrlGlobals)[format];
  9801. if (accessedGlobals.length > 0) {
  9802. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9803. }
  9804. }
  9805. getReferencedFileName(outputPluginDriver) {
  9806. const metaProperty = this.metaProperty;
  9807. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  9808. return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
  9809. }
  9810. return null;
  9811. }
  9812. hasEffects() {
  9813. return false;
  9814. }
  9815. hasEffectsOnInteractionAtPath(path, { type }) {
  9816. return path.length > 1 || type !== INTERACTION_ACCESSED;
  9817. }
  9818. include() {
  9819. if (!this.included) {
  9820. this.included = true;
  9821. if (this.meta.name === 'import') {
  9822. this.context.addImportMeta(this);
  9823. const parent = this.parent;
  9824. this.metaProperty =
  9825. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  9826. ? parent.propertyKey
  9827. : null;
  9828. }
  9829. }
  9830. }
  9831. renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
  9832. var _a;
  9833. const parent = this.parent;
  9834. const metaProperty = this.metaProperty;
  9835. if (metaProperty &&
  9836. (metaProperty.startsWith(FILE_PREFIX) ||
  9837. metaProperty.startsWith(ASSET_PREFIX) ||
  9838. metaProperty.startsWith(CHUNK_PREFIX))) {
  9839. let referenceId = null;
  9840. let assetReferenceId = null;
  9841. let chunkReferenceId = null;
  9842. let fileName;
  9843. if (metaProperty.startsWith(FILE_PREFIX)) {
  9844. referenceId = metaProperty.substring(FILE_PREFIX.length);
  9845. fileName = outputPluginDriver.getFileName(referenceId);
  9846. }
  9847. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  9848. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9849. assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
  9850. fileName = outputPluginDriver.getFileName(assetReferenceId);
  9851. }
  9852. else {
  9853. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9854. chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
  9855. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  9856. }
  9857. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  9858. let replacement;
  9859. if (assetReferenceId !== null) {
  9860. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  9861. {
  9862. assetFileName: fileName,
  9863. chunkId,
  9864. format,
  9865. moduleId: this.context.module.id,
  9866. relativeAssetPath: relativePath
  9867. }
  9868. ]);
  9869. }
  9870. if (!replacement) {
  9871. replacement =
  9872. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  9873. {
  9874. assetReferenceId,
  9875. chunkId,
  9876. chunkReferenceId,
  9877. fileName,
  9878. format,
  9879. moduleId: this.context.module.id,
  9880. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  9881. relativePath
  9882. }
  9883. ]) || relativeUrlMechanisms[format](relativePath);
  9884. }
  9885. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9886. return;
  9887. }
  9888. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  9889. metaProperty,
  9890. {
  9891. chunkId,
  9892. format,
  9893. moduleId: this.context.module.id
  9894. }
  9895. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
  9896. if (typeof replacement === 'string') {
  9897. if (parent instanceof MemberExpression) {
  9898. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9899. }
  9900. else {
  9901. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  9902. }
  9903. }
  9904. }
  9905. }
  9906. const accessedMetaUrlGlobals = {
  9907. amd: ['document', 'module', 'URL'],
  9908. cjs: ['document', 'require', 'URL'],
  9909. es: [],
  9910. iife: ['document', 'URL'],
  9911. system: ['module'],
  9912. umd: ['document', 'require', 'URL']
  9913. };
  9914. const accessedFileUrlGlobals = {
  9915. amd: ['document', 'require', 'URL'],
  9916. cjs: ['document', 'require', 'URL'],
  9917. es: [],
  9918. iife: ['document', 'URL'],
  9919. system: ['module', 'URL'],
  9920. umd: ['document', 'require', 'URL']
  9921. };
  9922. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  9923. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  9924. const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
  9925. const urlMechanism = getUrl(chunkId);
  9926. return prop === null
  9927. ? `({ url: ${urlMechanism} })`
  9928. : prop === 'url'
  9929. ? urlMechanism
  9930. : 'undefined';
  9931. };
  9932. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  9933. const relativeUrlMechanisms = {
  9934. amd: relativePath => {
  9935. if (relativePath[0] !== '.')
  9936. relativePath = './' + relativePath;
  9937. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  9938. },
  9939. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  9940. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  9941. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  9942. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  9943. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  9944. };
  9945. const importMetaMechanisms = {
  9946. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  9947. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  9948. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  9949. system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
  9950. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  9951. };
  9952. class NewExpression extends NodeBase {
  9953. hasEffects(context) {
  9954. try {
  9955. for (const argument of this.arguments) {
  9956. if (argument.hasEffects(context))
  9957. return true;
  9958. }
  9959. if (this.context.options.treeshake.annotations &&
  9960. this.annotations) {
  9961. return false;
  9962. }
  9963. return (this.callee.hasEffects(context) ||
  9964. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  9965. }
  9966. finally {
  9967. if (!this.deoptimized)
  9968. this.applyDeoptimizations();
  9969. }
  9970. }
  9971. hasEffectsOnInteractionAtPath(path, { type }) {
  9972. return path.length > 0 || type !== INTERACTION_ACCESSED;
  9973. }
  9974. include(context, includeChildrenRecursively) {
  9975. if (!this.deoptimized)
  9976. this.applyDeoptimizations();
  9977. if (includeChildrenRecursively) {
  9978. super.include(context, includeChildrenRecursively);
  9979. }
  9980. else {
  9981. this.included = true;
  9982. this.callee.include(context, false);
  9983. }
  9984. this.callee.includeCallArguments(context, this.arguments);
  9985. }
  9986. initialise() {
  9987. this.interaction = {
  9988. args: this.arguments,
  9989. thisArg: null,
  9990. type: INTERACTION_CALLED,
  9991. withNew: true
  9992. };
  9993. }
  9994. render(code, options) {
  9995. this.callee.render(code, options);
  9996. renderCallArguments(code, options, this);
  9997. }
  9998. applyDeoptimizations() {
  9999. this.deoptimized = true;
  10000. for (const argument of this.arguments) {
  10001. // This will make sure all properties of parameters behave as "unknown"
  10002. argument.deoptimizePath(UNKNOWN_PATH);
  10003. }
  10004. this.context.requestTreeshakingPass();
  10005. }
  10006. }
  10007. class ObjectExpression extends NodeBase {
  10008. constructor() {
  10009. super(...arguments);
  10010. this.objectEntity = null;
  10011. }
  10012. deoptimizeCache() {
  10013. this.getObjectEntity().deoptimizeAllProperties();
  10014. }
  10015. deoptimizePath(path) {
  10016. this.getObjectEntity().deoptimizePath(path);
  10017. }
  10018. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10019. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10020. }
  10021. getLiteralValueAtPath(path, recursionTracker, origin) {
  10022. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10023. }
  10024. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10025. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10026. }
  10027. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10028. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10029. }
  10030. render(code, options, { renderedSurroundingElement } = BLANK) {
  10031. super.render(code, options);
  10032. if (renderedSurroundingElement === ExpressionStatement$1 ||
  10033. renderedSurroundingElement === ArrowFunctionExpression$1) {
  10034. code.appendRight(this.start, '(');
  10035. code.prependLeft(this.end, ')');
  10036. }
  10037. }
  10038. applyDeoptimizations() { }
  10039. getObjectEntity() {
  10040. if (this.objectEntity !== null) {
  10041. return this.objectEntity;
  10042. }
  10043. let prototype = OBJECT_PROTOTYPE;
  10044. const properties = [];
  10045. for (const property of this.properties) {
  10046. if (property instanceof SpreadElement) {
  10047. properties.push({ key: UnknownKey, kind: 'init', property });
  10048. continue;
  10049. }
  10050. let key;
  10051. if (property.computed) {
  10052. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10053. if (typeof keyValue === 'symbol') {
  10054. properties.push({ key: UnknownKey, kind: property.kind, property });
  10055. continue;
  10056. }
  10057. else {
  10058. key = String(keyValue);
  10059. }
  10060. }
  10061. else {
  10062. key =
  10063. property.key instanceof Identifier
  10064. ? property.key.name
  10065. : String(property.key.value);
  10066. if (key === '__proto__' && property.kind === 'init') {
  10067. prototype =
  10068. property.value instanceof Literal && property.value.value === null
  10069. ? null
  10070. : property.value;
  10071. continue;
  10072. }
  10073. }
  10074. properties.push({ key, kind: property.kind, property });
  10075. }
  10076. return (this.objectEntity = new ObjectEntity(properties, prototype));
  10077. }
  10078. }
  10079. class PrivateIdentifier extends NodeBase {
  10080. }
  10081. class Program extends NodeBase {
  10082. constructor() {
  10083. super(...arguments);
  10084. this.hasCachedEffect = false;
  10085. }
  10086. hasEffects(context) {
  10087. // We are caching here to later more efficiently identify side-effect-free modules
  10088. if (this.hasCachedEffect)
  10089. return true;
  10090. for (const node of this.body) {
  10091. if (node.hasEffects(context)) {
  10092. return (this.hasCachedEffect = true);
  10093. }
  10094. }
  10095. return false;
  10096. }
  10097. include(context, includeChildrenRecursively) {
  10098. this.included = true;
  10099. for (const node of this.body) {
  10100. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  10101. node.include(context, includeChildrenRecursively);
  10102. }
  10103. }
  10104. }
  10105. render(code, options) {
  10106. if (this.body.length) {
  10107. renderStatementList(this.body, code, this.start, this.end, options);
  10108. }
  10109. else {
  10110. super.render(code, options);
  10111. }
  10112. }
  10113. applyDeoptimizations() { }
  10114. }
  10115. class Property extends MethodBase {
  10116. constructor() {
  10117. super(...arguments);
  10118. this.declarationInit = null;
  10119. }
  10120. declare(kind, init) {
  10121. this.declarationInit = init;
  10122. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  10123. }
  10124. hasEffects(context) {
  10125. if (!this.deoptimized)
  10126. this.applyDeoptimizations();
  10127. const propertyReadSideEffects = this.context.options.treeshake
  10128. .propertyReadSideEffects;
  10129. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  10130. this.key.hasEffects(context) ||
  10131. this.value.hasEffects(context));
  10132. }
  10133. markDeclarationReached() {
  10134. this.value.markDeclarationReached();
  10135. }
  10136. render(code, options) {
  10137. if (!this.shorthand) {
  10138. this.key.render(code, options);
  10139. }
  10140. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  10141. }
  10142. applyDeoptimizations() {
  10143. this.deoptimized = true;
  10144. if (this.declarationInit !== null) {
  10145. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  10146. this.context.requestTreeshakingPass();
  10147. }
  10148. }
  10149. }
  10150. class PropertyDefinition extends NodeBase {
  10151. deoptimizePath(path) {
  10152. var _a;
  10153. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  10154. }
  10155. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10156. var _a;
  10157. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10158. }
  10159. getLiteralValueAtPath(path, recursionTracker, origin) {
  10160. return this.value
  10161. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  10162. : UnknownValue;
  10163. }
  10164. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10165. return this.value
  10166. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  10167. : UNKNOWN_EXPRESSION;
  10168. }
  10169. hasEffects(context) {
  10170. var _a;
  10171. return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10172. }
  10173. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10174. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  10175. }
  10176. applyDeoptimizations() { }
  10177. }
  10178. class ReturnStatement extends NodeBase {
  10179. hasEffects(context) {
  10180. var _a;
  10181. if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
  10182. return true;
  10183. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10184. return false;
  10185. }
  10186. include(context, includeChildrenRecursively) {
  10187. var _a;
  10188. this.included = true;
  10189. (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10190. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10191. }
  10192. initialise() {
  10193. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  10194. }
  10195. render(code, options) {
  10196. if (this.argument) {
  10197. this.argument.render(code, options, { preventASI: true });
  10198. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  10199. code.prependLeft(this.start + 6, ' ');
  10200. }
  10201. }
  10202. }
  10203. }
  10204. class SequenceExpression extends NodeBase {
  10205. deoptimizePath(path) {
  10206. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  10207. }
  10208. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10209. this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10210. }
  10211. getLiteralValueAtPath(path, recursionTracker, origin) {
  10212. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  10213. }
  10214. hasEffects(context) {
  10215. for (const expression of this.expressions) {
  10216. if (expression.hasEffects(context))
  10217. return true;
  10218. }
  10219. return false;
  10220. }
  10221. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10222. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  10223. }
  10224. include(context, includeChildrenRecursively) {
  10225. this.included = true;
  10226. const lastExpression = this.expressions[this.expressions.length - 1];
  10227. for (const expression of this.expressions) {
  10228. if (includeChildrenRecursively ||
  10229. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  10230. expression.shouldBeIncluded(context))
  10231. expression.include(context, includeChildrenRecursively);
  10232. }
  10233. }
  10234. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  10235. let includedNodes = 0;
  10236. let lastSeparatorPos = null;
  10237. const lastNode = this.expressions[this.expressions.length - 1];
  10238. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  10239. if (!node.included) {
  10240. treeshakeNode(node, code, start, end);
  10241. continue;
  10242. }
  10243. includedNodes++;
  10244. lastSeparatorPos = separator;
  10245. if (includedNodes === 1 && preventASI) {
  10246. removeLineBreaks(code, start, node.start);
  10247. }
  10248. if (includedNodes === 1) {
  10249. const parentType = renderedParentType || this.parent.type;
  10250. node.render(code, options, {
  10251. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  10252. renderedParentType: parentType,
  10253. renderedSurroundingElement: parentType
  10254. });
  10255. }
  10256. else {
  10257. node.render(code, options);
  10258. }
  10259. }
  10260. if (lastSeparatorPos) {
  10261. code.remove(lastSeparatorPos, this.end);
  10262. }
  10263. }
  10264. }
  10265. class StaticBlock extends NodeBase {
  10266. createScope(parentScope) {
  10267. this.scope = new BlockScope(parentScope);
  10268. }
  10269. hasEffects(context) {
  10270. for (const node of this.body) {
  10271. if (node.hasEffects(context))
  10272. return true;
  10273. }
  10274. return false;
  10275. }
  10276. include(context, includeChildrenRecursively) {
  10277. this.included = true;
  10278. for (const node of this.body) {
  10279. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10280. node.include(context, includeChildrenRecursively);
  10281. }
  10282. }
  10283. render(code, options) {
  10284. if (this.body.length) {
  10285. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  10286. }
  10287. else {
  10288. super.render(code, options);
  10289. }
  10290. }
  10291. }
  10292. class Super extends NodeBase {
  10293. bind() {
  10294. this.variable = this.scope.findVariable('this');
  10295. }
  10296. deoptimizePath(path) {
  10297. this.variable.deoptimizePath(path);
  10298. }
  10299. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10300. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10301. }
  10302. include() {
  10303. if (!this.included) {
  10304. this.included = true;
  10305. this.context.includeVariableInModule(this.variable);
  10306. }
  10307. }
  10308. }
  10309. class SwitchCase extends NodeBase {
  10310. hasEffects(context) {
  10311. var _a;
  10312. if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
  10313. return true;
  10314. for (const node of this.consequent) {
  10315. if (context.brokenFlow)
  10316. break;
  10317. if (node.hasEffects(context))
  10318. return true;
  10319. }
  10320. return false;
  10321. }
  10322. include(context, includeChildrenRecursively) {
  10323. var _a;
  10324. this.included = true;
  10325. (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10326. for (const node of this.consequent) {
  10327. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10328. node.include(context, includeChildrenRecursively);
  10329. }
  10330. }
  10331. render(code, options, nodeRenderOptions) {
  10332. if (this.consequent.length) {
  10333. this.test && this.test.render(code, options);
  10334. const testEnd = this.test
  10335. ? this.test.end
  10336. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  10337. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  10338. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  10339. }
  10340. else {
  10341. super.render(code, options);
  10342. }
  10343. }
  10344. }
  10345. SwitchCase.prototype.needsBoundaries = true;
  10346. class SwitchStatement extends NodeBase {
  10347. createScope(parentScope) {
  10348. this.scope = new BlockScope(parentScope);
  10349. }
  10350. hasEffects(context) {
  10351. if (this.discriminant.hasEffects(context))
  10352. return true;
  10353. const { brokenFlow, ignore: { breaks } } = context;
  10354. let minBrokenFlow = Infinity;
  10355. context.ignore.breaks = true;
  10356. for (const switchCase of this.cases) {
  10357. if (switchCase.hasEffects(context))
  10358. return true;
  10359. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  10360. context.brokenFlow = brokenFlow;
  10361. }
  10362. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10363. context.brokenFlow = minBrokenFlow;
  10364. }
  10365. context.ignore.breaks = breaks;
  10366. return false;
  10367. }
  10368. include(context, includeChildrenRecursively) {
  10369. this.included = true;
  10370. this.discriminant.include(context, includeChildrenRecursively);
  10371. const { brokenFlow } = context;
  10372. let minBrokenFlow = Infinity;
  10373. let isCaseIncluded = includeChildrenRecursively ||
  10374. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  10375. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  10376. const switchCase = this.cases[caseIndex];
  10377. if (switchCase.included) {
  10378. isCaseIncluded = true;
  10379. }
  10380. if (!isCaseIncluded) {
  10381. const hasEffectsContext = createHasEffectsContext();
  10382. hasEffectsContext.ignore.breaks = true;
  10383. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  10384. }
  10385. if (isCaseIncluded) {
  10386. switchCase.include(context, includeChildrenRecursively);
  10387. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  10388. context.brokenFlow = brokenFlow;
  10389. }
  10390. else {
  10391. minBrokenFlow = brokenFlow;
  10392. }
  10393. }
  10394. if (isCaseIncluded &&
  10395. this.defaultCase !== null &&
  10396. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10397. context.brokenFlow = minBrokenFlow;
  10398. }
  10399. }
  10400. initialise() {
  10401. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  10402. if (this.cases[caseIndex].test === null) {
  10403. this.defaultCase = caseIndex;
  10404. return;
  10405. }
  10406. }
  10407. this.defaultCase = null;
  10408. }
  10409. render(code, options) {
  10410. this.discriminant.render(code, options);
  10411. if (this.cases.length > 0) {
  10412. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  10413. }
  10414. }
  10415. }
  10416. class TaggedTemplateExpression extends CallExpressionBase {
  10417. bind() {
  10418. super.bind();
  10419. if (this.tag.type === Identifier$1) {
  10420. const name = this.tag.name;
  10421. const variable = this.scope.findVariable(name);
  10422. if (variable.isNamespace) {
  10423. this.context.warn({
  10424. code: 'CANNOT_CALL_NAMESPACE',
  10425. message: `Cannot call a namespace ('${name}')`
  10426. }, this.start);
  10427. }
  10428. }
  10429. }
  10430. hasEffects(context) {
  10431. try {
  10432. for (const argument of this.quasi.expressions) {
  10433. if (argument.hasEffects(context))
  10434. return true;
  10435. }
  10436. return (this.tag.hasEffects(context) ||
  10437. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10438. }
  10439. finally {
  10440. if (!this.deoptimized)
  10441. this.applyDeoptimizations();
  10442. }
  10443. }
  10444. include(context, includeChildrenRecursively) {
  10445. if (!this.deoptimized)
  10446. this.applyDeoptimizations();
  10447. if (includeChildrenRecursively) {
  10448. super.include(context, includeChildrenRecursively);
  10449. }
  10450. else {
  10451. this.included = true;
  10452. this.tag.include(context, includeChildrenRecursively);
  10453. this.quasi.include(context, includeChildrenRecursively);
  10454. }
  10455. this.tag.includeCallArguments(context, this.interaction.args);
  10456. const returnExpression = this.getReturnExpression();
  10457. if (!returnExpression.included) {
  10458. returnExpression.include(context, false);
  10459. }
  10460. }
  10461. initialise() {
  10462. this.interaction = {
  10463. args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
  10464. thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  10465. type: INTERACTION_CALLED,
  10466. withNew: false
  10467. };
  10468. }
  10469. render(code, options) {
  10470. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  10471. this.quasi.render(code, options);
  10472. }
  10473. applyDeoptimizations() {
  10474. this.deoptimized = true;
  10475. if (this.interaction.thisArg) {
  10476. this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10477. }
  10478. for (const argument of this.quasi.expressions) {
  10479. // This will make sure all properties of parameters behave as "unknown"
  10480. argument.deoptimizePath(UNKNOWN_PATH);
  10481. }
  10482. this.context.requestTreeshakingPass();
  10483. }
  10484. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10485. if (this.returnExpression === null) {
  10486. this.returnExpression = UNKNOWN_EXPRESSION;
  10487. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10488. }
  10489. return this.returnExpression;
  10490. }
  10491. }
  10492. class TemplateElement extends NodeBase {
  10493. // Do not try to bind value
  10494. bind() { }
  10495. hasEffects() {
  10496. return false;
  10497. }
  10498. include() {
  10499. this.included = true;
  10500. }
  10501. parseNode(esTreeNode) {
  10502. this.value = esTreeNode.value;
  10503. super.parseNode(esTreeNode);
  10504. }
  10505. render() { }
  10506. }
  10507. class TemplateLiteral extends NodeBase {
  10508. deoptimizeThisOnInteractionAtPath() { }
  10509. getLiteralValueAtPath(path) {
  10510. if (path.length > 0 || this.quasis.length !== 1) {
  10511. return UnknownValue;
  10512. }
  10513. return this.quasis[0].value.cooked;
  10514. }
  10515. getReturnExpressionWhenCalledAtPath(path) {
  10516. if (path.length !== 1) {
  10517. return UNKNOWN_EXPRESSION;
  10518. }
  10519. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  10520. }
  10521. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10522. if (interaction.type === INTERACTION_ACCESSED) {
  10523. return path.length > 1;
  10524. }
  10525. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  10526. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  10527. }
  10528. return true;
  10529. }
  10530. render(code, options) {
  10531. code.indentExclusionRanges.push([this.start, this.end]);
  10532. super.render(code, options);
  10533. }
  10534. }
  10535. class UndefinedVariable extends Variable {
  10536. constructor() {
  10537. super('undefined');
  10538. }
  10539. getLiteralValueAtPath() {
  10540. return undefined;
  10541. }
  10542. }
  10543. class ExportDefaultVariable extends LocalVariable {
  10544. constructor(name, exportDefaultDeclaration, context) {
  10545. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  10546. this.hasId = false;
  10547. this.originalId = null;
  10548. this.originalVariable = null;
  10549. const declaration = exportDefaultDeclaration.declaration;
  10550. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10551. declaration.id) {
  10552. this.hasId = true;
  10553. this.originalId = declaration.id;
  10554. }
  10555. else if (declaration instanceof Identifier) {
  10556. this.originalId = declaration;
  10557. }
  10558. }
  10559. addReference(identifier) {
  10560. if (!this.hasId) {
  10561. this.name = identifier.name;
  10562. }
  10563. }
  10564. getAssignedVariableName() {
  10565. return (this.originalId && this.originalId.name) || null;
  10566. }
  10567. getBaseVariableName() {
  10568. const original = this.getOriginalVariable();
  10569. if (original === this) {
  10570. return super.getBaseVariableName();
  10571. }
  10572. else {
  10573. return original.getBaseVariableName();
  10574. }
  10575. }
  10576. getDirectOriginalVariable() {
  10577. return this.originalId &&
  10578. (this.hasId ||
  10579. !(this.originalId.isPossibleTDZ() ||
  10580. this.originalId.variable.isReassigned ||
  10581. this.originalId.variable instanceof UndefinedVariable ||
  10582. // this avoids a circular dependency
  10583. 'syntheticNamespace' in this.originalId.variable))
  10584. ? this.originalId.variable
  10585. : null;
  10586. }
  10587. getName(getPropertyAccess) {
  10588. const original = this.getOriginalVariable();
  10589. if (original === this) {
  10590. return super.getName(getPropertyAccess);
  10591. }
  10592. else {
  10593. return original.getName(getPropertyAccess);
  10594. }
  10595. }
  10596. getOriginalVariable() {
  10597. if (this.originalVariable)
  10598. return this.originalVariable;
  10599. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10600. let original = this;
  10601. let currentVariable;
  10602. const checkedVariables = new Set();
  10603. do {
  10604. checkedVariables.add(original);
  10605. currentVariable = original;
  10606. original = currentVariable.getDirectOriginalVariable();
  10607. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10608. return (this.originalVariable = original || currentVariable);
  10609. }
  10610. }
  10611. class ModuleScope extends ChildScope {
  10612. constructor(parent, context) {
  10613. super(parent);
  10614. this.context = context;
  10615. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  10616. }
  10617. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  10618. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  10619. this.variables.set('default', variable);
  10620. return variable;
  10621. }
  10622. addNamespaceMemberAccess() { }
  10623. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  10624. // all module level variables are already deconflicted when deconflicting the chunk
  10625. for (const scope of this.children)
  10626. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10627. }
  10628. findLexicalBoundary() {
  10629. return this;
  10630. }
  10631. findVariable(name) {
  10632. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  10633. if (knownVariable) {
  10634. return knownVariable;
  10635. }
  10636. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  10637. if (variable instanceof GlobalVariable) {
  10638. this.accessedOutsideVariables.set(name, variable);
  10639. }
  10640. return variable;
  10641. }
  10642. }
  10643. class ThisExpression extends NodeBase {
  10644. bind() {
  10645. this.variable = this.scope.findVariable('this');
  10646. }
  10647. deoptimizePath(path) {
  10648. this.variable.deoptimizePath(path);
  10649. }
  10650. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10651. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  10652. this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
  10653. }
  10654. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10655. if (path.length === 0) {
  10656. return interaction.type !== INTERACTION_ACCESSED;
  10657. }
  10658. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10659. }
  10660. include() {
  10661. if (!this.included) {
  10662. this.included = true;
  10663. this.context.includeVariableInModule(this.variable);
  10664. }
  10665. }
  10666. initialise() {
  10667. this.alias =
  10668. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  10669. if (this.alias === 'undefined') {
  10670. this.context.warn({
  10671. code: 'THIS_IS_UNDEFINED',
  10672. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  10673. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  10674. }, this.start);
  10675. }
  10676. }
  10677. render(code) {
  10678. if (this.alias !== null) {
  10679. code.overwrite(this.start, this.end, this.alias, {
  10680. contentOnly: false,
  10681. storeName: true
  10682. });
  10683. }
  10684. }
  10685. }
  10686. class ThrowStatement extends NodeBase {
  10687. hasEffects() {
  10688. return true;
  10689. }
  10690. include(context, includeChildrenRecursively) {
  10691. this.included = true;
  10692. this.argument.include(context, includeChildrenRecursively);
  10693. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10694. }
  10695. render(code, options) {
  10696. this.argument.render(code, options, { preventASI: true });
  10697. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  10698. code.prependLeft(this.start + 5, ' ');
  10699. }
  10700. }
  10701. }
  10702. class TryStatement extends NodeBase {
  10703. constructor() {
  10704. super(...arguments);
  10705. this.directlyIncluded = false;
  10706. this.includedLabelsAfterBlock = null;
  10707. }
  10708. hasEffects(context) {
  10709. var _a;
  10710. return ((this.context.options.treeshake.tryCatchDeoptimization
  10711. ? this.block.body.length > 0
  10712. : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10713. }
  10714. include(context, includeChildrenRecursively) {
  10715. var _a, _b;
  10716. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  10717. const { brokenFlow } = context;
  10718. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  10719. this.included = true;
  10720. this.directlyIncluded = true;
  10721. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  10722. if (context.includedLabels.size > 0) {
  10723. this.includedLabelsAfterBlock = [...context.includedLabels];
  10724. }
  10725. context.brokenFlow = brokenFlow;
  10726. }
  10727. else if (this.includedLabelsAfterBlock) {
  10728. for (const label of this.includedLabelsAfterBlock) {
  10729. context.includedLabels.add(label);
  10730. }
  10731. }
  10732. if (this.handler !== null) {
  10733. this.handler.include(context, includeChildrenRecursively);
  10734. context.brokenFlow = brokenFlow;
  10735. }
  10736. (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  10737. }
  10738. }
  10739. const unaryOperators = {
  10740. '!': value => !value,
  10741. '+': value => +value,
  10742. '-': value => -value,
  10743. delete: () => UnknownValue,
  10744. typeof: value => typeof value,
  10745. void: () => undefined,
  10746. '~': value => ~value
  10747. };
  10748. class UnaryExpression extends NodeBase {
  10749. getLiteralValueAtPath(path, recursionTracker, origin) {
  10750. if (path.length > 0)
  10751. return UnknownValue;
  10752. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10753. if (typeof argumentValue === 'symbol')
  10754. return UnknownValue;
  10755. return unaryOperators[this.operator](argumentValue);
  10756. }
  10757. hasEffects(context) {
  10758. if (!this.deoptimized)
  10759. this.applyDeoptimizations();
  10760. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  10761. return false;
  10762. return (this.argument.hasEffects(context) ||
  10763. (this.operator === 'delete' &&
  10764. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  10765. }
  10766. hasEffectsOnInteractionAtPath(path, { type }) {
  10767. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  10768. }
  10769. applyDeoptimizations() {
  10770. this.deoptimized = true;
  10771. if (this.operator === 'delete') {
  10772. this.argument.deoptimizePath(EMPTY_PATH);
  10773. this.context.requestTreeshakingPass();
  10774. }
  10775. }
  10776. }
  10777. class UnknownNode extends NodeBase {
  10778. hasEffects() {
  10779. return true;
  10780. }
  10781. include(context) {
  10782. super.include(context, true);
  10783. }
  10784. }
  10785. class UpdateExpression extends NodeBase {
  10786. hasEffects(context) {
  10787. if (!this.deoptimized)
  10788. this.applyDeoptimizations();
  10789. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  10790. }
  10791. hasEffectsOnInteractionAtPath(path, { type }) {
  10792. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10793. }
  10794. include(context, includeChildrenRecursively) {
  10795. if (!this.deoptimized)
  10796. this.applyDeoptimizations();
  10797. this.included = true;
  10798. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  10799. }
  10800. initialise() {
  10801. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  10802. }
  10803. render(code, options) {
  10804. const { exportNamesByVariable, format, snippets: { _ } } = options;
  10805. this.argument.render(code, options);
  10806. if (format === 'system') {
  10807. const variable = this.argument.variable;
  10808. const exportNames = exportNamesByVariable.get(variable);
  10809. if (exportNames) {
  10810. if (this.prefix) {
  10811. if (exportNames.length === 1) {
  10812. renderSystemExportExpression(variable, this.start, this.end, code, options);
  10813. }
  10814. else {
  10815. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  10816. }
  10817. }
  10818. else {
  10819. const operator = this.operator[0];
  10820. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  10821. }
  10822. }
  10823. }
  10824. }
  10825. applyDeoptimizations() {
  10826. this.deoptimized = true;
  10827. this.argument.deoptimizePath(EMPTY_PATH);
  10828. if (this.argument instanceof Identifier) {
  10829. const variable = this.scope.findVariable(this.argument.name);
  10830. variable.isReassigned = true;
  10831. }
  10832. this.context.requestTreeshakingPass();
  10833. }
  10834. }
  10835. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10836. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10837. }
  10838. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  10839. for (const declarator of declarations) {
  10840. if (!declarator.id.included)
  10841. return false;
  10842. if (declarator.id.type === Identifier$1) {
  10843. if (exportNamesByVariable.has(declarator.id.variable))
  10844. return false;
  10845. }
  10846. else {
  10847. const exportedVariables = [];
  10848. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  10849. if (exportedVariables.length > 0)
  10850. return false;
  10851. }
  10852. }
  10853. return true;
  10854. }
  10855. class VariableDeclaration extends NodeBase {
  10856. deoptimizePath() {
  10857. for (const declarator of this.declarations) {
  10858. declarator.deoptimizePath(EMPTY_PATH);
  10859. }
  10860. }
  10861. hasEffectsOnInteractionAtPath() {
  10862. return false;
  10863. }
  10864. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  10865. this.included = true;
  10866. for (const declarator of this.declarations) {
  10867. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  10868. declarator.include(context, includeChildrenRecursively);
  10869. if (asSingleStatement) {
  10870. declarator.id.include(context, includeChildrenRecursively);
  10871. }
  10872. }
  10873. }
  10874. initialise() {
  10875. for (const declarator of this.declarations) {
  10876. declarator.declareDeclarator(this.kind);
  10877. }
  10878. }
  10879. render(code, options, nodeRenderOptions = BLANK) {
  10880. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  10881. for (const declarator of this.declarations) {
  10882. declarator.render(code, options);
  10883. }
  10884. if (!nodeRenderOptions.isNoStatement &&
  10885. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  10886. code.appendLeft(this.end, ';');
  10887. }
  10888. }
  10889. else {
  10890. this.renderReplacedDeclarations(code, options);
  10891. }
  10892. }
  10893. applyDeoptimizations() { }
  10894. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  10895. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  10896. code.remove(this.end - 1, this.end);
  10897. }
  10898. separatorString += ';';
  10899. if (lastSeparatorPos !== null) {
  10900. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  10901. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  10902. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  10903. actualContentEnd--;
  10904. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  10905. actualContentEnd--;
  10906. }
  10907. }
  10908. if (actualContentEnd === lastSeparatorPos + 1) {
  10909. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  10910. }
  10911. else {
  10912. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  10913. code.remove(actualContentEnd, renderedContentEnd);
  10914. }
  10915. }
  10916. else {
  10917. code.appendLeft(renderedContentEnd, separatorString);
  10918. }
  10919. if (systemPatternExports.length > 0) {
  10920. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  10921. }
  10922. }
  10923. renderReplacedDeclarations(code, options) {
  10924. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  10925. let actualContentEnd, renderedContentEnd;
  10926. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  10927. let lastSeparatorPos = renderedContentEnd - 1;
  10928. code.remove(this.start, lastSeparatorPos);
  10929. let isInDeclaration = false;
  10930. let hasRenderedContent = false;
  10931. let separatorString = '', leadingString, nextSeparatorString;
  10932. const aggregatedSystemExports = [];
  10933. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  10934. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  10935. if (!node.included) {
  10936. code.remove(start, end);
  10937. continue;
  10938. }
  10939. node.render(code, options);
  10940. leadingString = '';
  10941. nextSeparatorString = '';
  10942. if (!node.id.included ||
  10943. (node.id instanceof Identifier &&
  10944. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  10945. if (hasRenderedContent) {
  10946. separatorString += ';';
  10947. }
  10948. isInDeclaration = false;
  10949. }
  10950. else {
  10951. if (singleSystemExport && singleSystemExport === node.id.variable) {
  10952. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  10953. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  10954. }
  10955. if (isInDeclaration) {
  10956. separatorString += ',';
  10957. }
  10958. else {
  10959. if (hasRenderedContent) {
  10960. separatorString += ';';
  10961. }
  10962. leadingString += `${this.kind} `;
  10963. isInDeclaration = true;
  10964. }
  10965. }
  10966. if (renderedContentEnd === lastSeparatorPos + 1) {
  10967. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  10968. }
  10969. else {
  10970. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  10971. code.appendLeft(renderedContentEnd, leadingString);
  10972. }
  10973. actualContentEnd = contentEnd;
  10974. renderedContentEnd = end;
  10975. hasRenderedContent = true;
  10976. lastSeparatorPos = separator;
  10977. separatorString = nextSeparatorString;
  10978. }
  10979. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  10980. }
  10981. }
  10982. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  10983. var _a;
  10984. let singleSystemExport = null;
  10985. if (options.format === 'system') {
  10986. for (const { node } of separatedNodes) {
  10987. if (node.id instanceof Identifier &&
  10988. node.init &&
  10989. aggregatedSystemExports.length === 0 &&
  10990. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  10991. singleSystemExport = node.id.variable;
  10992. aggregatedSystemExports.push(singleSystemExport);
  10993. }
  10994. else {
  10995. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  10996. }
  10997. }
  10998. if (aggregatedSystemExports.length > 1) {
  10999. singleSystemExport = null;
  11000. }
  11001. else if (singleSystemExport) {
  11002. aggregatedSystemExports.length = 0;
  11003. }
  11004. }
  11005. return singleSystemExport;
  11006. }
  11007. class VariableDeclarator extends NodeBase {
  11008. declareDeclarator(kind) {
  11009. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11010. }
  11011. deoptimizePath(path) {
  11012. this.id.deoptimizePath(path);
  11013. }
  11014. hasEffects(context) {
  11015. var _a;
  11016. const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
  11017. this.id.markDeclarationReached();
  11018. return initEffect || this.id.hasEffects(context);
  11019. }
  11020. include(context, includeChildrenRecursively) {
  11021. var _a;
  11022. this.included = true;
  11023. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  11024. this.id.markDeclarationReached();
  11025. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  11026. this.id.include(context, includeChildrenRecursively);
  11027. }
  11028. }
  11029. render(code, options) {
  11030. const { exportNamesByVariable, snippets: { _ } } = options;
  11031. const renderId = this.id.included;
  11032. if (renderId) {
  11033. this.id.render(code, options);
  11034. }
  11035. else {
  11036. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  11037. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  11038. }
  11039. if (this.init) {
  11040. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11041. }
  11042. else if (this.id instanceof Identifier &&
  11043. isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
  11044. code.appendLeft(this.end, `${_}=${_}void 0`);
  11045. }
  11046. }
  11047. applyDeoptimizations() { }
  11048. }
  11049. class WhileStatement extends NodeBase {
  11050. hasEffects(context) {
  11051. if (this.test.hasEffects(context))
  11052. return true;
  11053. const { brokenFlow, ignore: { breaks, continues } } = context;
  11054. context.ignore.breaks = true;
  11055. context.ignore.continues = true;
  11056. if (this.body.hasEffects(context))
  11057. return true;
  11058. context.ignore.breaks = breaks;
  11059. context.ignore.continues = continues;
  11060. context.brokenFlow = brokenFlow;
  11061. return false;
  11062. }
  11063. include(context, includeChildrenRecursively) {
  11064. this.included = true;
  11065. this.test.include(context, includeChildrenRecursively);
  11066. const { brokenFlow } = context;
  11067. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11068. context.brokenFlow = brokenFlow;
  11069. }
  11070. }
  11071. class YieldExpression extends NodeBase {
  11072. hasEffects(context) {
  11073. var _a;
  11074. if (!this.deoptimized)
  11075. this.applyDeoptimizations();
  11076. return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  11077. }
  11078. render(code, options) {
  11079. if (this.argument) {
  11080. this.argument.render(code, options, { preventASI: true });
  11081. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  11082. code.prependLeft(this.start + 5, ' ');
  11083. }
  11084. }
  11085. }
  11086. }
  11087. const nodeConstructors = {
  11088. ArrayExpression,
  11089. ArrayPattern,
  11090. ArrowFunctionExpression,
  11091. AssignmentExpression,
  11092. AssignmentPattern,
  11093. AwaitExpression,
  11094. BinaryExpression,
  11095. BlockStatement,
  11096. BreakStatement,
  11097. CallExpression,
  11098. CatchClause,
  11099. ChainExpression,
  11100. ClassBody,
  11101. ClassDeclaration,
  11102. ClassExpression,
  11103. ConditionalExpression,
  11104. ContinueStatement,
  11105. DoWhileStatement,
  11106. EmptyStatement,
  11107. ExportAllDeclaration,
  11108. ExportDefaultDeclaration,
  11109. ExportNamedDeclaration,
  11110. ExportSpecifier,
  11111. ExpressionStatement,
  11112. ForInStatement,
  11113. ForOfStatement,
  11114. ForStatement,
  11115. FunctionDeclaration,
  11116. FunctionExpression,
  11117. Identifier,
  11118. IfStatement,
  11119. ImportDeclaration,
  11120. ImportDefaultSpecifier,
  11121. ImportExpression,
  11122. ImportNamespaceSpecifier,
  11123. ImportSpecifier,
  11124. LabeledStatement,
  11125. Literal,
  11126. LogicalExpression,
  11127. MemberExpression,
  11128. MetaProperty,
  11129. MethodDefinition,
  11130. NewExpression,
  11131. ObjectExpression,
  11132. ObjectPattern,
  11133. PrivateIdentifier,
  11134. Program,
  11135. Property,
  11136. PropertyDefinition,
  11137. RestElement,
  11138. ReturnStatement,
  11139. SequenceExpression,
  11140. SpreadElement,
  11141. StaticBlock,
  11142. Super,
  11143. SwitchCase,
  11144. SwitchStatement,
  11145. TaggedTemplateExpression,
  11146. TemplateElement,
  11147. TemplateLiteral,
  11148. ThisExpression,
  11149. ThrowStatement,
  11150. TryStatement,
  11151. UnaryExpression,
  11152. UnknownNode,
  11153. UpdateExpression,
  11154. VariableDeclaration,
  11155. VariableDeclarator,
  11156. WhileStatement,
  11157. YieldExpression
  11158. };
  11159. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11160. class ExportShimVariable extends Variable {
  11161. constructor(module) {
  11162. super(MISSING_EXPORT_SHIM_VARIABLE);
  11163. this.module = module;
  11164. }
  11165. include() {
  11166. super.include();
  11167. this.module.needsExportShim = true;
  11168. }
  11169. }
  11170. class NamespaceVariable extends Variable {
  11171. constructor(context) {
  11172. super(context.getModuleName());
  11173. this.memberVariables = null;
  11174. this.mergedNamespaces = [];
  11175. this.referencedEarly = false;
  11176. this.references = [];
  11177. this.context = context;
  11178. this.module = context.module;
  11179. }
  11180. addReference(identifier) {
  11181. this.references.push(identifier);
  11182. this.name = identifier.name;
  11183. }
  11184. getMemberVariables() {
  11185. if (this.memberVariables) {
  11186. return this.memberVariables;
  11187. }
  11188. const memberVariables = Object.create(null);
  11189. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  11190. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  11191. const exportedVariable = this.context.traceExport(name);
  11192. if (exportedVariable) {
  11193. memberVariables[name] = exportedVariable;
  11194. }
  11195. }
  11196. }
  11197. return (this.memberVariables = memberVariables);
  11198. }
  11199. include() {
  11200. this.included = true;
  11201. this.context.includeAllExports();
  11202. }
  11203. prepare(accessedGlobalsByScope) {
  11204. if (this.mergedNamespaces.length > 0) {
  11205. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  11206. }
  11207. }
  11208. renderBlock(options) {
  11209. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  11210. const memberVariables = this.getMemberVariables();
  11211. const members = Object.entries(memberVariables).map(([name, original]) => {
  11212. if (this.referencedEarly || original.isReassigned) {
  11213. return [
  11214. null,
  11215. `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
  11216. ];
  11217. }
  11218. return [name, original.getName(getPropertyAccess)];
  11219. });
  11220. members.unshift([null, `__proto__:${_}null`]);
  11221. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  11222. if (this.mergedNamespaces.length > 0) {
  11223. const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  11224. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
  11225. }
  11226. else {
  11227. // The helper to merge namespaces will also take care of freezing and toStringTag
  11228. if (namespaceToStringTag) {
  11229. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  11230. }
  11231. if (freeze) {
  11232. output = `/*#__PURE__*/Object.freeze(${output})`;
  11233. }
  11234. }
  11235. const name = this.getName(getPropertyAccess);
  11236. output = `${cnst} ${name}${_}=${_}${output};`;
  11237. if (format === 'system' && exportNamesByVariable.has(this)) {
  11238. output += `${n}${getSystemExportStatement([this], options)};`;
  11239. }
  11240. return output;
  11241. }
  11242. renderFirst() {
  11243. return this.referencedEarly;
  11244. }
  11245. setMergedNamespaces(mergedNamespaces) {
  11246. this.mergedNamespaces = mergedNamespaces;
  11247. const moduleExecIndex = this.context.getModuleExecIndex();
  11248. for (const identifier of this.references) {
  11249. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  11250. this.referencedEarly = true;
  11251. break;
  11252. }
  11253. }
  11254. }
  11255. }
  11256. NamespaceVariable.prototype.isNamespace = true;
  11257. class SyntheticNamedExportVariable extends Variable {
  11258. constructor(context, name, syntheticNamespace) {
  11259. super(name);
  11260. this.baseVariable = null;
  11261. this.context = context;
  11262. this.module = context.module;
  11263. this.syntheticNamespace = syntheticNamespace;
  11264. }
  11265. getBaseVariable() {
  11266. if (this.baseVariable)
  11267. return this.baseVariable;
  11268. let baseVariable = this.syntheticNamespace;
  11269. while (baseVariable instanceof ExportDefaultVariable ||
  11270. baseVariable instanceof SyntheticNamedExportVariable) {
  11271. if (baseVariable instanceof ExportDefaultVariable) {
  11272. const original = baseVariable.getOriginalVariable();
  11273. if (original === baseVariable)
  11274. break;
  11275. baseVariable = original;
  11276. }
  11277. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11278. baseVariable = baseVariable.syntheticNamespace;
  11279. }
  11280. }
  11281. return (this.baseVariable = baseVariable);
  11282. }
  11283. getBaseVariableName() {
  11284. return this.syntheticNamespace.getBaseVariableName();
  11285. }
  11286. getName(getPropertyAccess) {
  11287. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11288. }
  11289. include() {
  11290. this.included = true;
  11291. this.context.includeVariableInModule(this.syntheticNamespace);
  11292. }
  11293. setRenderNames(baseName, name) {
  11294. super.setRenderNames(baseName, name);
  11295. }
  11296. }
  11297. var BuildPhase;
  11298. (function (BuildPhase) {
  11299. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11300. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11301. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11302. })(BuildPhase || (BuildPhase = {}));
  11303. function getId(m) {
  11304. return m.id;
  11305. }
  11306. function getOriginalLocation(sourcemapChain, location) {
  11307. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11308. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11309. const sourcemap = filteredSourcemapChain.pop();
  11310. const line = sourcemap.mappings[location.line - 1];
  11311. if (line) {
  11312. const filteredLine = line.filter((segment) => segment.length > 1);
  11313. const lastSegment = filteredLine[filteredLine.length - 1];
  11314. for (const segment of filteredLine) {
  11315. if (segment[0] >= location.column || segment === lastSegment) {
  11316. location = {
  11317. column: segment[3],
  11318. line: segment[2] + 1
  11319. };
  11320. continue traceSourcemap;
  11321. }
  11322. }
  11323. }
  11324. throw new Error("Can't resolve original location of error.");
  11325. }
  11326. return location;
  11327. }
  11328. const NOOP = () => { };
  11329. let timers = new Map();
  11330. function getPersistedLabel(label, level) {
  11331. switch (level) {
  11332. case 1:
  11333. return `# ${label}`;
  11334. case 2:
  11335. return `## ${label}`;
  11336. case 3:
  11337. return label;
  11338. default:
  11339. return `${' '.repeat(level - 4)}- ${label}`;
  11340. }
  11341. }
  11342. function timeStartImpl(label, level = 3) {
  11343. label = getPersistedLabel(label, level);
  11344. const startMemory = process$1.memoryUsage().heapUsed;
  11345. const startTime = performance.now();
  11346. const timer = timers.get(label);
  11347. if (timer === undefined) {
  11348. timers.set(label, {
  11349. memory: 0,
  11350. startMemory,
  11351. startTime,
  11352. time: 0,
  11353. totalMemory: 0
  11354. });
  11355. }
  11356. else {
  11357. timer.startMemory = startMemory;
  11358. timer.startTime = startTime;
  11359. }
  11360. }
  11361. function timeEndImpl(label, level = 3) {
  11362. label = getPersistedLabel(label, level);
  11363. const timer = timers.get(label);
  11364. if (timer !== undefined) {
  11365. const currentMemory = process$1.memoryUsage().heapUsed;
  11366. timer.memory += currentMemory - timer.startMemory;
  11367. timer.time += performance.now() - timer.startTime;
  11368. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  11369. }
  11370. }
  11371. function getTimings() {
  11372. const newTimings = {};
  11373. for (const [label, { memory, time, totalMemory }] of timers) {
  11374. newTimings[label] = [time, memory, totalMemory];
  11375. }
  11376. return newTimings;
  11377. }
  11378. let timeStart = NOOP;
  11379. let timeEnd = NOOP;
  11380. const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
  11381. function getPluginWithTimers(plugin, index) {
  11382. for (const hook of TIMED_PLUGIN_HOOKS) {
  11383. if (hook in plugin) {
  11384. let timerLabel = `plugin ${index}`;
  11385. if (plugin.name) {
  11386. timerLabel += ` (${plugin.name})`;
  11387. }
  11388. timerLabel += ` - ${hook}`;
  11389. const func = plugin[hook];
  11390. plugin[hook] = function (...args) {
  11391. timeStart(timerLabel, 4);
  11392. const result = func.apply(this, args);
  11393. timeEnd(timerLabel, 4);
  11394. if (result && typeof result.then === 'function') {
  11395. timeStart(`${timerLabel} (async)`, 4);
  11396. return result.then((hookResult) => {
  11397. timeEnd(`${timerLabel} (async)`, 4);
  11398. return hookResult;
  11399. });
  11400. }
  11401. return result;
  11402. };
  11403. }
  11404. }
  11405. return plugin;
  11406. }
  11407. function initialiseTimers(inputOptions) {
  11408. if (inputOptions.perf) {
  11409. timers = new Map();
  11410. timeStart = timeStartImpl;
  11411. timeEnd = timeEndImpl;
  11412. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  11413. }
  11414. else {
  11415. timeStart = NOOP;
  11416. timeEnd = NOOP;
  11417. }
  11418. }
  11419. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  11420. baseModule.isExecuted = true;
  11421. const modules = [baseModule];
  11422. const visitedModules = new Set();
  11423. for (const module of modules) {
  11424. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  11425. if (!(dependency instanceof ExternalModule) &&
  11426. !dependency.isExecuted &&
  11427. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  11428. !visitedModules.has(dependency.id)) {
  11429. dependency.isExecuted = true;
  11430. visitedModules.add(dependency.id);
  11431. modules.push(dependency);
  11432. }
  11433. }
  11434. }
  11435. }
  11436. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  11437. identifier: null,
  11438. localName: MISSING_EXPORT_SHIM_VARIABLE
  11439. };
  11440. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  11441. const searchedModules = searchedNamesAndModules.get(name);
  11442. if (searchedModules) {
  11443. if (searchedModules.has(target)) {
  11444. return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
  11445. }
  11446. searchedModules.add(target);
  11447. }
  11448. else {
  11449. searchedNamesAndModules.set(name, new Set([target]));
  11450. }
  11451. return target.getVariableForExportName(name, {
  11452. importerForSideEffects,
  11453. isExportAllSearch,
  11454. searchedNamesAndModules
  11455. });
  11456. }
  11457. function getAndExtendSideEffectModules(variable, module) {
  11458. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  11459. let currentVariable = variable;
  11460. const referencedVariables = new Set([currentVariable]);
  11461. while (true) {
  11462. const importingModule = currentVariable.module;
  11463. currentVariable =
  11464. currentVariable instanceof ExportDefaultVariable
  11465. ? currentVariable.getDirectOriginalVariable()
  11466. : currentVariable instanceof SyntheticNamedExportVariable
  11467. ? currentVariable.syntheticNamespace
  11468. : null;
  11469. if (!currentVariable || referencedVariables.has(currentVariable)) {
  11470. break;
  11471. }
  11472. referencedVariables.add(currentVariable);
  11473. sideEffectModules.add(importingModule);
  11474. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  11475. if (originalSideEffects) {
  11476. for (const module of originalSideEffects) {
  11477. sideEffectModules.add(module);
  11478. }
  11479. }
  11480. }
  11481. return sideEffectModules;
  11482. }
  11483. class Module {
  11484. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
  11485. this.graph = graph;
  11486. this.id = id;
  11487. this.options = options;
  11488. this.alternativeReexportModules = new Map();
  11489. this.chunkFileNames = new Set();
  11490. this.chunkNames = [];
  11491. this.cycles = new Set();
  11492. this.dependencies = new Set();
  11493. this.dynamicDependencies = new Set();
  11494. this.dynamicImporters = [];
  11495. this.dynamicImports = [];
  11496. this.execIndex = Infinity;
  11497. this.implicitlyLoadedAfter = new Set();
  11498. this.implicitlyLoadedBefore = new Set();
  11499. this.importDescriptions = new Map();
  11500. this.importMetas = [];
  11501. this.importedFromNotTreeshaken = false;
  11502. this.importers = [];
  11503. this.includedDynamicImporters = [];
  11504. this.includedImports = new Set();
  11505. this.isExecuted = false;
  11506. this.isUserDefinedEntryPoint = false;
  11507. this.needsExportShim = false;
  11508. this.sideEffectDependenciesByVariable = new Map();
  11509. this.sources = new Set();
  11510. this.usesTopLevelAwait = false;
  11511. this.allExportNames = null;
  11512. this.ast = null;
  11513. this.exportAllModules = [];
  11514. this.exportAllSources = new Set();
  11515. this.exportNamesByVariable = null;
  11516. this.exportShimVariable = new ExportShimVariable(this);
  11517. this.exports = new Map();
  11518. this.namespaceReexportsByName = new Map();
  11519. this.reexportDescriptions = new Map();
  11520. this.relevantDependencies = null;
  11521. this.syntheticExports = new Map();
  11522. this.syntheticNamespace = null;
  11523. this.transformDependencies = [];
  11524. this.transitiveReexports = null;
  11525. this.excludeFromSourcemap = /\0/.test(id);
  11526. this.context = options.moduleContext(id);
  11527. this.preserveSignature = this.options.preserveEntrySignatures;
  11528. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11529. const module = this;
  11530. const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
  11531. this.info = {
  11532. ast: null,
  11533. code: null,
  11534. get dynamicallyImportedIdResolutions() {
  11535. return dynamicImports
  11536. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  11537. .filter(Boolean);
  11538. },
  11539. get dynamicallyImportedIds() {
  11540. // We cannot use this.dynamicDependencies because this is needed before
  11541. // dynamicDependencies are populated
  11542. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  11543. },
  11544. get dynamicImporters() {
  11545. return dynamicImporters.sort();
  11546. },
  11547. get hasDefaultExport() {
  11548. // This information is only valid after parsing
  11549. if (!module.ast) {
  11550. return null;
  11551. }
  11552. return module.exports.has('default') || reexportDescriptions.has('default');
  11553. },
  11554. get hasModuleSideEffects() {
  11555. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  11556. return this.moduleSideEffects;
  11557. },
  11558. id,
  11559. get implicitlyLoadedAfterOneOf() {
  11560. return Array.from(implicitlyLoadedAfter, getId).sort();
  11561. },
  11562. get implicitlyLoadedBefore() {
  11563. return Array.from(implicitlyLoadedBefore, getId).sort();
  11564. },
  11565. get importedIdResolutions() {
  11566. return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
  11567. },
  11568. get importedIds() {
  11569. // We cannot use this.dependencies because this is needed before
  11570. // dependencies are populated
  11571. return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
  11572. },
  11573. get importers() {
  11574. return importers.sort();
  11575. },
  11576. isEntry,
  11577. isExternal: false,
  11578. get isIncluded() {
  11579. if (graph.phase !== BuildPhase.GENERATE) {
  11580. return null;
  11581. }
  11582. return module.isIncluded();
  11583. },
  11584. meta: { ...meta },
  11585. moduleSideEffects,
  11586. syntheticNamedExports
  11587. };
  11588. // Hide the deprecated key so that it only warns when accessed explicitly
  11589. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  11590. enumerable: false
  11591. });
  11592. }
  11593. basename() {
  11594. const base = basename(this.id);
  11595. const ext = extname(this.id);
  11596. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  11597. }
  11598. bindReferences() {
  11599. this.ast.bind();
  11600. }
  11601. error(props, pos) {
  11602. this.addLocationToLogProps(props, pos);
  11603. return error(props);
  11604. }
  11605. getAllExportNames() {
  11606. if (this.allExportNames) {
  11607. return this.allExportNames;
  11608. }
  11609. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  11610. for (const module of this.exportAllModules) {
  11611. if (module instanceof ExternalModule) {
  11612. this.allExportNames.add(`*${module.id}`);
  11613. continue;
  11614. }
  11615. for (const name of module.getAllExportNames()) {
  11616. if (name !== 'default')
  11617. this.allExportNames.add(name);
  11618. }
  11619. }
  11620. // We do not count the synthetic namespace as a regular export to hide it
  11621. // from entry signatures and namespace objects
  11622. if (typeof this.info.syntheticNamedExports === 'string') {
  11623. this.allExportNames.delete(this.info.syntheticNamedExports);
  11624. }
  11625. return this.allExportNames;
  11626. }
  11627. getDependenciesToBeIncluded() {
  11628. if (this.relevantDependencies)
  11629. return this.relevantDependencies;
  11630. this.relevantDependencies = new Set();
  11631. const necessaryDependencies = new Set();
  11632. const alwaysCheckedDependencies = new Set();
  11633. const dependencyVariables = new Set(this.includedImports);
  11634. if (this.info.isEntry ||
  11635. this.includedDynamicImporters.length > 0 ||
  11636. this.namespace.included ||
  11637. this.implicitlyLoadedAfter.size > 0) {
  11638. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  11639. const [exportedVariable] = this.getVariableForExportName(exportName);
  11640. if (exportedVariable) {
  11641. dependencyVariables.add(exportedVariable);
  11642. }
  11643. }
  11644. }
  11645. for (let variable of dependencyVariables) {
  11646. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  11647. if (sideEffectDependencies) {
  11648. for (const module of sideEffectDependencies) {
  11649. alwaysCheckedDependencies.add(module);
  11650. }
  11651. }
  11652. if (variable instanceof SyntheticNamedExportVariable) {
  11653. variable = variable.getBaseVariable();
  11654. }
  11655. else if (variable instanceof ExportDefaultVariable) {
  11656. variable = variable.getOriginalVariable();
  11657. }
  11658. necessaryDependencies.add(variable.module);
  11659. }
  11660. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  11661. for (const dependency of this.dependencies) {
  11662. this.relevantDependencies.add(dependency);
  11663. }
  11664. }
  11665. else {
  11666. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  11667. }
  11668. for (const dependency of necessaryDependencies) {
  11669. this.relevantDependencies.add(dependency);
  11670. }
  11671. return this.relevantDependencies;
  11672. }
  11673. getExportNamesByVariable() {
  11674. if (this.exportNamesByVariable) {
  11675. return this.exportNamesByVariable;
  11676. }
  11677. const exportNamesByVariable = new Map();
  11678. for (const exportName of this.getAllExportNames()) {
  11679. let [tracedVariable] = this.getVariableForExportName(exportName);
  11680. if (tracedVariable instanceof ExportDefaultVariable) {
  11681. tracedVariable = tracedVariable.getOriginalVariable();
  11682. }
  11683. if (!tracedVariable ||
  11684. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  11685. continue;
  11686. }
  11687. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  11688. if (existingExportNames) {
  11689. existingExportNames.push(exportName);
  11690. }
  11691. else {
  11692. exportNamesByVariable.set(tracedVariable, [exportName]);
  11693. }
  11694. }
  11695. return (this.exportNamesByVariable = exportNamesByVariable);
  11696. }
  11697. getExports() {
  11698. return Array.from(this.exports.keys());
  11699. }
  11700. getReexports() {
  11701. if (this.transitiveReexports) {
  11702. return this.transitiveReexports;
  11703. }
  11704. // to avoid infinite recursion when using circular `export * from X`
  11705. this.transitiveReexports = [];
  11706. const reexports = new Set(this.reexportDescriptions.keys());
  11707. for (const module of this.exportAllModules) {
  11708. if (module instanceof ExternalModule) {
  11709. reexports.add(`*${module.id}`);
  11710. }
  11711. else {
  11712. for (const name of [...module.getReexports(), ...module.getExports()]) {
  11713. if (name !== 'default')
  11714. reexports.add(name);
  11715. }
  11716. }
  11717. }
  11718. return (this.transitiveReexports = [...reexports]);
  11719. }
  11720. getRenderedExports() {
  11721. // only direct exports are counted here, not reexports at all
  11722. const renderedExports = [];
  11723. const removedExports = [];
  11724. for (const exportName of this.exports.keys()) {
  11725. const [variable] = this.getVariableForExportName(exportName);
  11726. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  11727. }
  11728. return { removedExports, renderedExports };
  11729. }
  11730. getSyntheticNamespace() {
  11731. if (this.syntheticNamespace === null) {
  11732. this.syntheticNamespace = undefined;
  11733. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  11734. ? this.info.syntheticNamedExports
  11735. : 'default', { onlyExplicit: true });
  11736. }
  11737. if (!this.syntheticNamespace) {
  11738. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  11739. }
  11740. return this.syntheticNamespace;
  11741. }
  11742. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  11743. var _a;
  11744. if (name[0] === '*') {
  11745. if (name.length === 1) {
  11746. // export * from './other'
  11747. return [this.namespace];
  11748. }
  11749. // export * from 'external'
  11750. const module = this.graph.modulesById.get(name.slice(1));
  11751. return module.getVariableForExportName('*');
  11752. }
  11753. // export { foo } from './other'
  11754. const reexportDeclaration = this.reexportDescriptions.get(name);
  11755. if (reexportDeclaration) {
  11756. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  11757. if (!variable) {
  11758. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  11759. }
  11760. if (importerForSideEffects) {
  11761. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11762. }
  11763. return [variable];
  11764. }
  11765. const exportDeclaration = this.exports.get(name);
  11766. if (exportDeclaration) {
  11767. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  11768. return [this.exportShimVariable];
  11769. }
  11770. const name = exportDeclaration.localName;
  11771. const variable = this.traceVariable(name, {
  11772. importerForSideEffects,
  11773. searchedNamesAndModules
  11774. });
  11775. if (importerForSideEffects) {
  11776. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  11777. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11778. }
  11779. return [variable];
  11780. }
  11781. if (onlyExplicit) {
  11782. return [null];
  11783. }
  11784. if (name !== 'default') {
  11785. const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  11786. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  11787. if (foundNamespaceReexport[0]) {
  11788. return foundNamespaceReexport;
  11789. }
  11790. }
  11791. if (this.info.syntheticNamedExports) {
  11792. return [
  11793. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  11794. ];
  11795. }
  11796. // we don't want to create shims when we are just
  11797. // probing export * modules for exports
  11798. if (!isExportAllSearch) {
  11799. if (this.options.shimMissingExports) {
  11800. this.shimMissingExport(name);
  11801. return [this.exportShimVariable];
  11802. }
  11803. }
  11804. return [null];
  11805. }
  11806. hasEffects() {
  11807. return (this.info.moduleSideEffects === 'no-treeshake' ||
  11808. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  11809. }
  11810. include() {
  11811. const context = createInclusionContext();
  11812. if (this.ast.shouldBeIncluded(context))
  11813. this.ast.include(context, false);
  11814. }
  11815. includeAllExports(includeNamespaceMembers) {
  11816. if (!this.isExecuted) {
  11817. markModuleAndImpureDependenciesAsExecuted(this);
  11818. this.graph.needsTreeshakingPass = true;
  11819. }
  11820. for (const exportName of this.exports.keys()) {
  11821. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  11822. const variable = this.getVariableForExportName(exportName)[0];
  11823. variable.deoptimizePath(UNKNOWN_PATH);
  11824. if (!variable.included) {
  11825. this.includeVariable(variable);
  11826. }
  11827. }
  11828. }
  11829. for (const name of this.getReexports()) {
  11830. const [variable] = this.getVariableForExportName(name);
  11831. if (variable) {
  11832. variable.deoptimizePath(UNKNOWN_PATH);
  11833. if (!variable.included) {
  11834. this.includeVariable(variable);
  11835. }
  11836. if (variable instanceof ExternalVariable) {
  11837. variable.module.reexported = true;
  11838. }
  11839. }
  11840. }
  11841. if (includeNamespaceMembers) {
  11842. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  11843. }
  11844. }
  11845. includeAllInBundle() {
  11846. this.ast.include(createInclusionContext(), true);
  11847. this.includeAllExports(false);
  11848. }
  11849. isIncluded() {
  11850. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  11851. }
  11852. linkImports() {
  11853. this.addModulesToImportDescriptions(this.importDescriptions);
  11854. this.addModulesToImportDescriptions(this.reexportDescriptions);
  11855. const externalExportAllModules = [];
  11856. for (const source of this.exportAllSources) {
  11857. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  11858. if (module instanceof ExternalModule) {
  11859. externalExportAllModules.push(module);
  11860. continue;
  11861. }
  11862. this.exportAllModules.push(module);
  11863. }
  11864. this.exportAllModules.push(...externalExportAllModules);
  11865. }
  11866. render(options) {
  11867. const magicString = this.magicString.clone();
  11868. this.ast.render(magicString, options);
  11869. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  11870. return magicString;
  11871. }
  11872. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  11873. this.info.code = code;
  11874. this.originalCode = originalCode;
  11875. this.originalSourcemap = originalSourcemap;
  11876. this.sourcemapChain = sourcemapChain;
  11877. if (transformFiles) {
  11878. this.transformFiles = transformFiles;
  11879. }
  11880. this.transformDependencies = transformDependencies;
  11881. this.customTransformCache = customTransformCache;
  11882. this.updateOptions(moduleOptions);
  11883. timeStart('generate ast', 3);
  11884. if (!ast) {
  11885. ast = this.tryParse();
  11886. }
  11887. timeEnd('generate ast', 3);
  11888. this.resolvedIds = resolvedIds || Object.create(null);
  11889. // By default, `id` is the file name. Custom resolvers and loaders
  11890. // can change that, but it makes sense to use it for the source file name
  11891. const fileName = this.id;
  11892. this.magicString = new MagicString(code, {
  11893. filename: (this.excludeFromSourcemap ? null : fileName),
  11894. indentExclusionRanges: []
  11895. });
  11896. timeStart('analyse ast', 3);
  11897. this.astContext = {
  11898. addDynamicImport: this.addDynamicImport.bind(this),
  11899. addExport: this.addExport.bind(this),
  11900. addImport: this.addImport.bind(this),
  11901. addImportMeta: this.addImportMeta.bind(this),
  11902. code,
  11903. deoptimizationTracker: this.graph.deoptimizationTracker,
  11904. error: this.error.bind(this),
  11905. fileName,
  11906. getExports: this.getExports.bind(this),
  11907. getModuleExecIndex: () => this.execIndex,
  11908. getModuleName: this.basename.bind(this),
  11909. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  11910. getReexports: this.getReexports.bind(this),
  11911. importDescriptions: this.importDescriptions,
  11912. includeAllExports: () => this.includeAllExports(true),
  11913. includeDynamicImport: this.includeDynamicImport.bind(this),
  11914. includeVariableInModule: this.includeVariableInModule.bind(this),
  11915. magicString: this.magicString,
  11916. module: this,
  11917. moduleContext: this.context,
  11918. options: this.options,
  11919. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  11920. traceExport: (name) => this.getVariableForExportName(name)[0],
  11921. traceVariable: this.traceVariable.bind(this),
  11922. usesTopLevelAwait: false,
  11923. warn: this.warn.bind(this)
  11924. };
  11925. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  11926. this.namespace = new NamespaceVariable(this.astContext);
  11927. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  11928. this.info.ast = ast;
  11929. timeEnd('analyse ast', 3);
  11930. }
  11931. toJSON() {
  11932. return {
  11933. ast: this.ast.esTreeNode,
  11934. code: this.info.code,
  11935. customTransformCache: this.customTransformCache,
  11936. dependencies: Array.from(this.dependencies, getId),
  11937. id: this.id,
  11938. meta: this.info.meta,
  11939. moduleSideEffects: this.info.moduleSideEffects,
  11940. originalCode: this.originalCode,
  11941. originalSourcemap: this.originalSourcemap,
  11942. resolvedIds: this.resolvedIds,
  11943. sourcemapChain: this.sourcemapChain,
  11944. syntheticNamedExports: this.info.syntheticNamedExports,
  11945. transformDependencies: this.transformDependencies,
  11946. transformFiles: this.transformFiles
  11947. };
  11948. }
  11949. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  11950. const localVariable = this.scope.variables.get(name);
  11951. if (localVariable) {
  11952. return localVariable;
  11953. }
  11954. const importDeclaration = this.importDescriptions.get(name);
  11955. if (importDeclaration) {
  11956. const otherModule = importDeclaration.module;
  11957. if (otherModule instanceof Module && importDeclaration.name === '*') {
  11958. return otherModule.namespace;
  11959. }
  11960. const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  11961. if (!declaration) {
  11962. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  11963. }
  11964. return declaration;
  11965. }
  11966. return null;
  11967. }
  11968. tryParse() {
  11969. try {
  11970. return this.graph.contextParse(this.info.code);
  11971. }
  11972. catch (err) {
  11973. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  11974. if (this.id.endsWith('.json')) {
  11975. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  11976. }
  11977. else if (!this.id.endsWith('.js')) {
  11978. message += ' (Note that you need plugins to import files that are not JavaScript)';
  11979. }
  11980. return this.error({
  11981. code: 'PARSE_ERROR',
  11982. message,
  11983. parserError: err
  11984. }, err.pos);
  11985. }
  11986. }
  11987. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  11988. if (moduleSideEffects != null) {
  11989. this.info.moduleSideEffects = moduleSideEffects;
  11990. }
  11991. if (syntheticNamedExports != null) {
  11992. this.info.syntheticNamedExports = syntheticNamedExports;
  11993. }
  11994. if (meta != null) {
  11995. Object.assign(this.info.meta, meta);
  11996. }
  11997. }
  11998. warn(props, pos) {
  11999. this.addLocationToLogProps(props, pos);
  12000. this.options.onwarn(props);
  12001. }
  12002. addDynamicImport(node) {
  12003. let argument = node.source;
  12004. if (argument instanceof TemplateLiteral) {
  12005. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  12006. argument = argument.quasis[0].value.cooked;
  12007. }
  12008. }
  12009. else if (argument instanceof Literal && typeof argument.value === 'string') {
  12010. argument = argument.value;
  12011. }
  12012. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  12013. }
  12014. addExport(node) {
  12015. if (node instanceof ExportDefaultDeclaration) {
  12016. // export default foo;
  12017. this.exports.set('default', {
  12018. identifier: node.variable.getAssignedVariableName(),
  12019. localName: 'default'
  12020. });
  12021. }
  12022. else if (node instanceof ExportAllDeclaration) {
  12023. const source = node.source.value;
  12024. this.sources.add(source);
  12025. if (node.exported) {
  12026. // export * as name from './other'
  12027. const name = node.exported.name;
  12028. this.reexportDescriptions.set(name, {
  12029. localName: '*',
  12030. module: null,
  12031. source,
  12032. start: node.start
  12033. });
  12034. }
  12035. else {
  12036. // export * from './other'
  12037. this.exportAllSources.add(source);
  12038. }
  12039. }
  12040. else if (node.source instanceof Literal) {
  12041. // export { name } from './other'
  12042. const source = node.source.value;
  12043. this.sources.add(source);
  12044. for (const specifier of node.specifiers) {
  12045. const name = specifier.exported.name;
  12046. this.reexportDescriptions.set(name, {
  12047. localName: specifier.local.name,
  12048. module: null,
  12049. source,
  12050. start: specifier.start
  12051. });
  12052. }
  12053. }
  12054. else if (node.declaration) {
  12055. const declaration = node.declaration;
  12056. if (declaration instanceof VariableDeclaration) {
  12057. // export var { foo, bar } = ...
  12058. // export var foo = 1, bar = 2;
  12059. for (const declarator of declaration.declarations) {
  12060. for (const localName of extractAssignedNames(declarator.id)) {
  12061. this.exports.set(localName, { identifier: null, localName });
  12062. }
  12063. }
  12064. }
  12065. else {
  12066. // export function foo () {}
  12067. const localName = declaration.id.name;
  12068. this.exports.set(localName, { identifier: null, localName });
  12069. }
  12070. }
  12071. else {
  12072. // export { foo, bar, baz }
  12073. for (const specifier of node.specifiers) {
  12074. const localName = specifier.local.name;
  12075. const exportedName = specifier.exported.name;
  12076. this.exports.set(exportedName, { identifier: null, localName });
  12077. }
  12078. }
  12079. }
  12080. addImport(node) {
  12081. const source = node.source.value;
  12082. this.sources.add(source);
  12083. for (const specifier of node.specifiers) {
  12084. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  12085. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  12086. const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
  12087. this.importDescriptions.set(specifier.local.name, {
  12088. module: null,
  12089. name,
  12090. source,
  12091. start: specifier.start
  12092. });
  12093. }
  12094. }
  12095. addImportMeta(node) {
  12096. this.importMetas.push(node);
  12097. }
  12098. addLocationToLogProps(props, pos) {
  12099. props.id = this.id;
  12100. props.pos = pos;
  12101. let code = this.info.code;
  12102. const location = locate(code, pos, { offsetLine: 1 });
  12103. if (location) {
  12104. let { column, line } = location;
  12105. try {
  12106. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  12107. code = this.originalCode;
  12108. }
  12109. catch (err) {
  12110. this.options.onwarn({
  12111. code: 'SOURCEMAP_ERROR',
  12112. id: this.id,
  12113. loc: {
  12114. column,
  12115. file: this.id,
  12116. line
  12117. },
  12118. message: `Error when using sourcemap for reporting an error: ${err.message}`,
  12119. pos
  12120. });
  12121. }
  12122. augmentCodeLocation(props, { column, line }, code, this.id);
  12123. }
  12124. }
  12125. addModulesToImportDescriptions(importDescription) {
  12126. for (const specifier of importDescription.values()) {
  12127. const { id } = this.resolvedIds[specifier.source];
  12128. specifier.module = this.graph.modulesById.get(id);
  12129. }
  12130. }
  12131. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  12132. const handledDependencies = new Set();
  12133. const addSideEffectDependencies = (possibleDependencies) => {
  12134. for (const dependency of possibleDependencies) {
  12135. if (handledDependencies.has(dependency)) {
  12136. continue;
  12137. }
  12138. handledDependencies.add(dependency);
  12139. if (necessaryDependencies.has(dependency)) {
  12140. relevantDependencies.add(dependency);
  12141. continue;
  12142. }
  12143. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  12144. continue;
  12145. }
  12146. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  12147. relevantDependencies.add(dependency);
  12148. continue;
  12149. }
  12150. addSideEffectDependencies(dependency.dependencies);
  12151. }
  12152. };
  12153. addSideEffectDependencies(this.dependencies);
  12154. addSideEffectDependencies(alwaysCheckedDependencies);
  12155. }
  12156. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  12157. let foundSyntheticDeclaration = null;
  12158. const foundInternalDeclarations = new Map();
  12159. const foundExternalDeclarations = new Set();
  12160. for (const module of this.exportAllModules) {
  12161. // Synthetic namespaces should not hide "regular" exports of the same name
  12162. if (module.info.syntheticNamedExports === name) {
  12163. continue;
  12164. }
  12165. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  12166. // We are creating a copy to handle the case where the same binding is
  12167. // imported through different namespace reexports gracefully
  12168. copyNameToModulesMap(searchedNamesAndModules));
  12169. if (module instanceof ExternalModule || indirectExternal) {
  12170. foundExternalDeclarations.add(variable);
  12171. }
  12172. else if (variable instanceof SyntheticNamedExportVariable) {
  12173. if (!foundSyntheticDeclaration) {
  12174. foundSyntheticDeclaration = variable;
  12175. }
  12176. }
  12177. else if (variable) {
  12178. foundInternalDeclarations.set(variable, module);
  12179. }
  12180. }
  12181. if (foundInternalDeclarations.size > 0) {
  12182. const foundDeclarationList = [...foundInternalDeclarations];
  12183. const usedDeclaration = foundDeclarationList[0][0];
  12184. if (foundDeclarationList.length === 1) {
  12185. return [usedDeclaration];
  12186. }
  12187. this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  12188. // TODO we are pretending it was not found while it should behave like "undefined"
  12189. return [null];
  12190. }
  12191. if (foundExternalDeclarations.size > 0) {
  12192. const foundDeclarationList = [...foundExternalDeclarations];
  12193. const usedDeclaration = foundDeclarationList[0];
  12194. if (foundDeclarationList.length > 1) {
  12195. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  12196. }
  12197. return [usedDeclaration, true];
  12198. }
  12199. if (foundSyntheticDeclaration) {
  12200. return [foundSyntheticDeclaration];
  12201. }
  12202. return [null];
  12203. }
  12204. includeAndGetAdditionalMergedNamespaces() {
  12205. const externalNamespaces = new Set();
  12206. const syntheticNamespaces = new Set();
  12207. for (const module of [this, ...this.exportAllModules]) {
  12208. if (module instanceof ExternalModule) {
  12209. const [externalVariable] = module.getVariableForExportName('*');
  12210. externalVariable.include();
  12211. this.includedImports.add(externalVariable);
  12212. externalNamespaces.add(externalVariable);
  12213. }
  12214. else if (module.info.syntheticNamedExports) {
  12215. const syntheticNamespace = module.getSyntheticNamespace();
  12216. syntheticNamespace.include();
  12217. this.includedImports.add(syntheticNamespace);
  12218. syntheticNamespaces.add(syntheticNamespace);
  12219. }
  12220. }
  12221. return [...syntheticNamespaces, ...externalNamespaces];
  12222. }
  12223. includeDynamicImport(node) {
  12224. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  12225. if (resolution instanceof Module) {
  12226. resolution.includedDynamicImporters.push(this);
  12227. resolution.includeAllExports(true);
  12228. }
  12229. }
  12230. includeVariable(variable) {
  12231. if (!variable.included) {
  12232. variable.include();
  12233. this.graph.needsTreeshakingPass = true;
  12234. const variableModule = variable.module;
  12235. if (variableModule instanceof Module) {
  12236. if (!variableModule.isExecuted) {
  12237. markModuleAndImpureDependenciesAsExecuted(variableModule);
  12238. }
  12239. if (variableModule !== this) {
  12240. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  12241. for (const module of sideEffectModules) {
  12242. if (!module.isExecuted) {
  12243. markModuleAndImpureDependenciesAsExecuted(module);
  12244. }
  12245. }
  12246. }
  12247. }
  12248. }
  12249. }
  12250. includeVariableInModule(variable) {
  12251. this.includeVariable(variable);
  12252. const variableModule = variable.module;
  12253. if (variableModule && variableModule !== this) {
  12254. this.includedImports.add(variable);
  12255. }
  12256. }
  12257. shimMissingExport(name) {
  12258. this.options.onwarn({
  12259. code: 'SHIMMED_EXPORT',
  12260. exporter: relativeId(this.id),
  12261. exportName: name,
  12262. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  12263. });
  12264. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  12265. }
  12266. }
  12267. // if there is a cyclic import in the reexport chain, we should not
  12268. // import from the original module but from the cyclic module to not
  12269. // mess up execution order.
  12270. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  12271. if (variable.module instanceof Module && variable.module !== reexporter) {
  12272. const exporterCycles = variable.module.cycles;
  12273. if (exporterCycles.size > 0) {
  12274. const importerCycles = reexporter.cycles;
  12275. for (const cycleSymbol of importerCycles) {
  12276. if (exporterCycles.has(cycleSymbol)) {
  12277. importer.alternativeReexportModules.set(variable, reexporter);
  12278. break;
  12279. }
  12280. }
  12281. }
  12282. }
  12283. }
  12284. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  12285. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  12286. function removeJsExtension(name) {
  12287. return name.endsWith('.js') ? name.slice(0, -3) : name;
  12288. }
  12289. function getCompleteAmdId(options, chunkId) {
  12290. if (options.autoId) {
  12291. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  12292. }
  12293. return options.id || '';
  12294. }
  12295. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  12296. const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  12297. if (!namedExportsMode) {
  12298. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  12299. }
  12300. let exportBlock = '';
  12301. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12302. if (reexports && namedExportsMode) {
  12303. for (const specifier of reexports) {
  12304. if (specifier.reexported !== '*') {
  12305. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12306. if (exportBlock)
  12307. exportBlock += n;
  12308. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  12309. const [left, right] = getDirectReturnFunction([], {
  12310. functionReturn: true,
  12311. lineBreakIndent: null,
  12312. name: null
  12313. });
  12314. exportBlock +=
  12315. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  12316. `${t}enumerable:${_}true,${n}` +
  12317. `${t}get:${_}${left}${importName}${right}${n}});`;
  12318. }
  12319. else {
  12320. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  12321. }
  12322. }
  12323. }
  12324. }
  12325. }
  12326. for (const { exported, local } of exports) {
  12327. const lhs = `exports${getPropertyAccess(exported)}`;
  12328. const rhs = local;
  12329. if (lhs !== rhs) {
  12330. if (exportBlock)
  12331. exportBlock += n;
  12332. exportBlock += `${lhs}${_}=${_}${rhs};`;
  12333. }
  12334. }
  12335. for (const { name, reexports } of dependencies) {
  12336. if (reexports && namedExportsMode) {
  12337. for (const specifier of reexports) {
  12338. if (specifier.reexported === '*') {
  12339. if (exportBlock)
  12340. exportBlock += n;
  12341. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  12342. exportBlock +=
  12343. cnst === 'var' && specifier.needsLiveBinding
  12344. ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  12345. isAsync: false,
  12346. name: null
  12347. })}${copyPropertyIfNecessary});`
  12348. : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
  12349. }
  12350. }
  12351. }
  12352. }
  12353. if (exportBlock) {
  12354. return `${n}${n}${exportBlock}`;
  12355. }
  12356. return '';
  12357. }
  12358. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  12359. if (exports.length > 0) {
  12360. return exports[0].local;
  12361. }
  12362. else {
  12363. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12364. if (reexports) {
  12365. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12366. }
  12367. }
  12368. }
  12369. }
  12370. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  12371. if (imported === 'default') {
  12372. if (!isChunk) {
  12373. const moduleInterop = String(interop(moduleId));
  12374. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  12375. ? defaultVariableName
  12376. : moduleVariableName;
  12377. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  12378. ? `${variableName}${getPropertyAccess('default')}`
  12379. : variableName;
  12380. }
  12381. return depNamedExportsMode
  12382. ? `${moduleVariableName}${getPropertyAccess('default')}`
  12383. : moduleVariableName;
  12384. }
  12385. if (imported === '*') {
  12386. return (isChunk
  12387. ? !depNamedExportsMode
  12388. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  12389. ? namespaceVariableName
  12390. : moduleVariableName;
  12391. }
  12392. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  12393. }
  12394. function getEsModuleValue(getObject) {
  12395. return getObject([['value', 'true']], {
  12396. lineBreakIndent: null
  12397. });
  12398. }
  12399. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  12400. if (hasNamedExports) {
  12401. if (addEsModule) {
  12402. if (addNamespaceToStringTag) {
  12403. return `Object.defineProperties(exports,${_}${getObject([
  12404. ['__esModule', getEsModuleValue(getObject)],
  12405. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  12406. ], {
  12407. lineBreakIndent: null
  12408. })});`;
  12409. }
  12410. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  12411. }
  12412. if (addNamespaceToStringTag) {
  12413. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  12414. }
  12415. }
  12416. return '';
  12417. }
  12418. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  12419. if (needsLiveBinding) {
  12420. const [left, right] = getDirectReturnFunction([], {
  12421. functionReturn: true,
  12422. lineBreakIndent: null,
  12423. name: null
  12424. });
  12425. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  12426. `${t}${t}enumerable:${_}true,${n}` +
  12427. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  12428. }
  12429. return `exports[k]${_}=${_}${name}[k]`;
  12430. };
  12431. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  12432. const { _, cnst, n } = snippets;
  12433. const neededInteropHelpers = new Set();
  12434. const interopStatements = [];
  12435. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  12436. neededInteropHelpers.add(helper);
  12437. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  12438. };
  12439. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12440. if (isChunk) {
  12441. for (const { imported, reexported } of [
  12442. ...(imports || []),
  12443. ...(reexports || [])
  12444. ]) {
  12445. if (imported === '*' && reexported !== '*') {
  12446. if (!namedExportsMode) {
  12447. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  12448. }
  12449. break;
  12450. }
  12451. }
  12452. }
  12453. else {
  12454. const moduleInterop = String(interop(id));
  12455. let hasDefault = false;
  12456. let hasNamespace = false;
  12457. for (const { imported, reexported } of [
  12458. ...(imports || []),
  12459. ...(reexports || [])
  12460. ]) {
  12461. let helper;
  12462. let variableName;
  12463. if (imported === 'default') {
  12464. if (!hasDefault) {
  12465. hasDefault = true;
  12466. if (defaultVariableName !== namespaceVariableName) {
  12467. variableName = defaultVariableName;
  12468. helper = defaultInteropHelpersByInteropType[moduleInterop];
  12469. }
  12470. }
  12471. }
  12472. else if (imported === '*' && reexported !== '*') {
  12473. if (!hasNamespace) {
  12474. hasNamespace = true;
  12475. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  12476. variableName = namespaceVariableName;
  12477. }
  12478. }
  12479. if (helper) {
  12480. addInteropStatement(variableName, helper, name);
  12481. }
  12482. }
  12483. }
  12484. }
  12485. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  12486. }
  12487. function addJsExtension(name) {
  12488. return name.endsWith('.js') ? name : name + '.js';
  12489. }
  12490. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  12491. // The assumption is that this makes sense for all relative ids:
  12492. // https://requirejs.org/docs/api.html#jsfiles
  12493. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  12494. if (id[0] !== '.') {
  12495. return id;
  12496. }
  12497. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  12498. }
  12499. const builtins = {
  12500. assert: true,
  12501. buffer: true,
  12502. console: true,
  12503. constants: true,
  12504. domain: true,
  12505. events: true,
  12506. http: true,
  12507. https: true,
  12508. os: true,
  12509. path: true,
  12510. process: true,
  12511. punycode: true,
  12512. querystring: true,
  12513. stream: true,
  12514. string_decoder: true,
  12515. timers: true,
  12516. tty: true,
  12517. url: true,
  12518. util: true,
  12519. vm: true,
  12520. zlib: true
  12521. };
  12522. function warnOnBuiltins(warn, dependencies) {
  12523. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  12524. if (!externalBuiltins.length)
  12525. return;
  12526. warn({
  12527. code: 'MISSING_NODE_BUILTINS',
  12528. 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`,
  12529. modules: externalBuiltins
  12530. });
  12531. }
  12532. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12533. warnOnBuiltins(warn, dependencies);
  12534. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
  12535. const args = dependencies.map(m => m.name);
  12536. const { n, getNonArrowFunctionIntro, _ } = snippets;
  12537. if (namedExportsMode && hasExports) {
  12538. args.unshift(`exports`);
  12539. deps.unshift(`'exports'`);
  12540. }
  12541. if (accessedGlobals.has('require')) {
  12542. args.unshift('require');
  12543. deps.unshift(`'require'`);
  12544. }
  12545. if (accessedGlobals.has('module')) {
  12546. args.unshift('module');
  12547. deps.unshift(`'module'`);
  12548. }
  12549. const completeAmdId = getCompleteAmdId(amd, id);
  12550. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12551. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  12552. const useStrict = strict ? `${_}'use strict';` : '';
  12553. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  12554. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12555. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12556. if (namespaceMarkers) {
  12557. namespaceMarkers = n + n + namespaceMarkers;
  12558. }
  12559. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12560. return (magicString
  12561. .indent(t)
  12562. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12563. // cf. https://v8.dev/blog/preparser#pife
  12564. .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
  12565. isAsync: false,
  12566. name: null
  12567. })}{${useStrict}${n}${n}`)
  12568. .append(`${n}${n}}));`));
  12569. }
  12570. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12571. const { _, n } = snippets;
  12572. const useStrict = strict ? `'use strict';${n}${n}` : '';
  12573. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12574. if (namespaceMarkers) {
  12575. namespaceMarkers += n + n;
  12576. }
  12577. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  12578. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12579. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  12580. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  12581. return magicString.append(`${exportBlock}${outro}`);
  12582. }
  12583. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  12584. let importBlock = '';
  12585. let definingVariable = false;
  12586. for (const { id, name, reexports, imports } of dependencies) {
  12587. if (!reexports && !imports) {
  12588. if (importBlock) {
  12589. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  12590. }
  12591. definingVariable = false;
  12592. importBlock += `require('${id}')`;
  12593. }
  12594. else {
  12595. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  12596. definingVariable = true;
  12597. importBlock += `${name}${_}=${_}require('${id}')`;
  12598. }
  12599. }
  12600. if (importBlock) {
  12601. return `${importBlock};${n}${n}`;
  12602. }
  12603. return '';
  12604. }
  12605. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  12606. const { _, n } = snippets;
  12607. const importBlock = getImportBlock(dependencies, _);
  12608. if (importBlock.length > 0)
  12609. intro += importBlock.join(n) + n + n;
  12610. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  12611. if (intro)
  12612. magicString.prepend(intro);
  12613. const exportBlock = getExportBlock(exports, snippets);
  12614. if (exportBlock.length)
  12615. magicString.append(n + n + exportBlock.join(n).trim());
  12616. if (outro)
  12617. magicString.append(outro);
  12618. return magicString.trim();
  12619. }
  12620. function getImportBlock(dependencies, _) {
  12621. const importBlock = [];
  12622. for (const { id, reexports, imports, name } of dependencies) {
  12623. if (!reexports && !imports) {
  12624. importBlock.push(`import${_}'${id}';`);
  12625. continue;
  12626. }
  12627. if (imports) {
  12628. let defaultImport = null;
  12629. let starImport = null;
  12630. const importedNames = [];
  12631. for (const specifier of imports) {
  12632. if (specifier.imported === 'default') {
  12633. defaultImport = specifier;
  12634. }
  12635. else if (specifier.imported === '*') {
  12636. starImport = specifier;
  12637. }
  12638. else {
  12639. importedNames.push(specifier);
  12640. }
  12641. }
  12642. if (starImport) {
  12643. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  12644. }
  12645. if (defaultImport && importedNames.length === 0) {
  12646. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  12647. }
  12648. else if (importedNames.length > 0) {
  12649. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  12650. .map(specifier => {
  12651. if (specifier.imported === specifier.local) {
  12652. return specifier.imported;
  12653. }
  12654. else {
  12655. return `${specifier.imported} as ${specifier.local}`;
  12656. }
  12657. })
  12658. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12659. }
  12660. }
  12661. if (reexports) {
  12662. let starExport = null;
  12663. const namespaceReexports = [];
  12664. const namedReexports = [];
  12665. for (const specifier of reexports) {
  12666. if (specifier.reexported === '*') {
  12667. starExport = specifier;
  12668. }
  12669. else if (specifier.imported === '*') {
  12670. namespaceReexports.push(specifier);
  12671. }
  12672. else {
  12673. namedReexports.push(specifier);
  12674. }
  12675. }
  12676. if (starExport) {
  12677. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  12678. }
  12679. if (namespaceReexports.length > 0) {
  12680. if (!imports ||
  12681. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  12682. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  12683. }
  12684. for (const specifier of namespaceReexports) {
  12685. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  12686. }
  12687. }
  12688. if (namedReexports.length > 0) {
  12689. importBlock.push(`export${_}{${_}${namedReexports
  12690. .map(specifier => {
  12691. if (specifier.imported === specifier.reexported) {
  12692. return specifier.imported;
  12693. }
  12694. else {
  12695. return `${specifier.imported} as ${specifier.reexported}`;
  12696. }
  12697. })
  12698. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12699. }
  12700. }
  12701. }
  12702. return importBlock;
  12703. }
  12704. function getExportBlock(exports, { _, cnst }) {
  12705. const exportBlock = [];
  12706. const exportDeclaration = [];
  12707. for (const specifier of exports) {
  12708. if (specifier.expression) {
  12709. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  12710. }
  12711. exportDeclaration.push(specifier.exported === specifier.local
  12712. ? specifier.local
  12713. : `${specifier.local} as ${specifier.exported}`);
  12714. }
  12715. if (exportDeclaration.length) {
  12716. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  12717. }
  12718. return exportBlock;
  12719. }
  12720. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  12721. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  12722. const parts = name.split('.');
  12723. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12724. parts.pop();
  12725. let propertyPath = root;
  12726. return (parts
  12727. .map(part => {
  12728. propertyPath += getPropertyAccess(part);
  12729. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  12730. })
  12731. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  12732. }
  12733. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  12734. const parts = deepName.split('.');
  12735. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12736. const last = parts.pop();
  12737. let propertyPath = root;
  12738. let deepAssignment = parts
  12739. .map(part => {
  12740. propertyPath += getPropertyAccess(part);
  12741. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  12742. })
  12743. .concat(`${propertyPath}${getPropertyAccess(last)}`)
  12744. .join(`,${_}`) + `${_}=${_}${assignment}`;
  12745. if (parts.length > 0) {
  12746. deepAssignment = `(${deepAssignment})`;
  12747. }
  12748. return deepAssignment;
  12749. }
  12750. function trimEmptyImports(dependencies) {
  12751. let i = dependencies.length;
  12752. while (i--) {
  12753. const { imports, reexports } = dependencies[i];
  12754. if (imports || reexports) {
  12755. return dependencies.slice(0, i + 1);
  12756. }
  12757. }
  12758. return [];
  12759. }
  12760. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  12761. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  12762. const isNamespaced = name && name.includes('.');
  12763. const useVariableAssignment = !extend && !isNamespaced;
  12764. if (name && useVariableAssignment && !isLegal(name)) {
  12765. return error({
  12766. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  12767. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  12768. });
  12769. }
  12770. warnOnBuiltins(warn, dependencies);
  12771. const external = trimEmptyImports(dependencies);
  12772. const deps = external.map(dep => dep.globalName || 'null');
  12773. const args = external.map(m => m.name);
  12774. if (hasExports && !name) {
  12775. warn({
  12776. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12777. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  12778. });
  12779. }
  12780. if (namedExportsMode && hasExports) {
  12781. if (extend) {
  12782. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  12783. args.unshift('exports');
  12784. }
  12785. else {
  12786. deps.unshift('{}');
  12787. args.unshift('exports');
  12788. }
  12789. }
  12790. const useStrict = strict ? `${t}'use strict';${n}` : '';
  12791. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12792. magicString.prepend(`${intro}${interopBlock}`);
  12793. let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
  12794. isAsync: false,
  12795. name: null
  12796. })}{${n}${useStrict}${n}`;
  12797. if (hasExports) {
  12798. if (name && !(extend && namedExportsMode)) {
  12799. wrapperIntro =
  12800. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  12801. `${_}=${_}${wrapperIntro}`;
  12802. }
  12803. if (isNamespaced) {
  12804. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  12805. }
  12806. }
  12807. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  12808. if (hasExports && !extend && namedExportsMode) {
  12809. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  12810. }
  12811. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12812. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  12813. if (namespaceMarkers) {
  12814. namespaceMarkers = n + n + namespaceMarkers;
  12815. }
  12816. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12817. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  12818. }
  12819. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  12820. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  12821. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  12822. const registeredName = name ? `'${name}',${_}` : '';
  12823. const wrapperParams = accessedGlobals.has('module')
  12824. ? ['exports', 'module']
  12825. : hasExports
  12826. ? ['exports']
  12827. : [];
  12828. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12829. // cf. https://v8.dev/blog/preparser#pife
  12830. let wrapperStart = `System.register(${registeredName}[` +
  12831. dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
  12832. `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
  12833. getStarExcludesBlock(starExcludes, t, snippets) +
  12834. getImportBindingsBlock(importBindings, t, snippets) +
  12835. `${n}${t}return${_}{${setters.length
  12836. ? `${n}${t}${t}setters:${_}[${setters
  12837. .map(setter => setter
  12838. ? `${getFunctionIntro(['module'], {
  12839. isAsync: false,
  12840. name: null
  12841. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  12842. : systemNullSetters
  12843. ? `null`
  12844. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  12845. .join(`,${_}`)}],`
  12846. : ''}${n}`;
  12847. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  12848. isAsync: usesTopLevelAwait,
  12849. name: null
  12850. })}{${n}${n}`;
  12851. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  12852. magicString.prepend(intro +
  12853. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  12854. getHoistedExportsBlock(exports, t, snippets));
  12855. magicString.append(`${outro}${n}${n}` +
  12856. getSyntheticExportsBlock(exports, t, snippets) +
  12857. getMissingExportsBlock(exports, t, snippets));
  12858. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  12859. }
  12860. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  12861. const importBindings = [];
  12862. const setters = [];
  12863. let starExcludes = null;
  12864. for (const { imports, reexports } of dependencies) {
  12865. const setter = [];
  12866. if (imports) {
  12867. for (const specifier of imports) {
  12868. importBindings.push(specifier.local);
  12869. if (specifier.imported === '*') {
  12870. setter.push(`${specifier.local}${_}=${_}module;`);
  12871. }
  12872. else {
  12873. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  12874. }
  12875. }
  12876. }
  12877. if (reexports) {
  12878. const reexportedNames = [];
  12879. let hasStarReexport = false;
  12880. for (const { imported, reexported } of reexports) {
  12881. if (reexported === '*') {
  12882. hasStarReexport = true;
  12883. }
  12884. else {
  12885. reexportedNames.push([
  12886. reexported,
  12887. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  12888. ]);
  12889. }
  12890. }
  12891. if (reexportedNames.length > 1 || hasStarReexport) {
  12892. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  12893. if (hasStarReexport) {
  12894. if (!starExcludes) {
  12895. starExcludes = getStarExcludes({ dependencies, exports });
  12896. }
  12897. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  12898. }
  12899. else {
  12900. setter.push(`exports(${exportMapping});`);
  12901. }
  12902. }
  12903. else {
  12904. const [key, value] = reexportedNames[0];
  12905. setter.push(`exports('${key}',${_}${value});`);
  12906. }
  12907. }
  12908. setters.push(setter.join(`${n}${t}${t}${t}`));
  12909. }
  12910. return { importBindings, setters, starExcludes };
  12911. }
  12912. const getStarExcludes = ({ dependencies, exports }) => {
  12913. const starExcludes = new Set(exports.map(expt => expt.exported));
  12914. starExcludes.add('default');
  12915. for (const { reexports } of dependencies) {
  12916. if (reexports) {
  12917. for (const reexport of reexports) {
  12918. if (reexport.reexported !== '*')
  12919. starExcludes.add(reexport.reexported);
  12920. }
  12921. }
  12922. }
  12923. return starExcludes;
  12924. };
  12925. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  12926. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
  12927. : '';
  12928. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  12929. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12930. function getExportsBlock(exports, t, { _, n }) {
  12931. if (exports.length === 0) {
  12932. return '';
  12933. }
  12934. if (exports.length === 1) {
  12935. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  12936. }
  12937. return (`exports({${n}` +
  12938. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  12939. `${n}});${n}${n}`);
  12940. }
  12941. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  12942. .filter(expt => expt.expression)
  12943. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12944. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  12945. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  12946. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  12947. function globalProp(name, globalVar, getPropertyAccess) {
  12948. if (!name)
  12949. return 'null';
  12950. return `${globalVar}${keypath(name, getPropertyAccess)}`;
  12951. }
  12952. function safeAccess(name, globalVar, { _, getPropertyAccess }) {
  12953. let propertyPath = globalVar;
  12954. return name
  12955. .split('.')
  12956. .map(part => (propertyPath += getPropertyAccess(part)))
  12957. .join(`${_}&&${_}`);
  12958. }
  12959. function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  12960. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  12961. const factoryVar = compact ? 'f' : 'factory';
  12962. const globalVar = compact ? 'g' : 'global';
  12963. if (hasExports && !name) {
  12964. return error({
  12965. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12966. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  12967. });
  12968. }
  12969. warnOnBuiltins(warn, dependencies);
  12970. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
  12971. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  12972. const trimmedImports = trimEmptyImports(dependencies);
  12973. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
  12974. const factoryParams = trimmedImports.map(m => m.name);
  12975. if (namedExportsMode && (hasExports || noConflict)) {
  12976. amdDeps.unshift(`'exports'`);
  12977. cjsDeps.unshift(`exports`);
  12978. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  12979. factoryParams.unshift('exports');
  12980. }
  12981. const completeAmdId = getCompleteAmdId(amd, id);
  12982. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12983. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  12984. const define = amd.define;
  12985. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  12986. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  12987. let iifeExport;
  12988. if (noConflict) {
  12989. const noConflictExportsVar = compact ? 'e' : 'exports';
  12990. let factory;
  12991. if (!namedExportsMode && hasExports) {
  12992. factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  12993. }
  12994. else {
  12995. const module = globalDeps.shift();
  12996. factory =
  12997. `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
  12998. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  12999. }
  13000. iifeExport =
  13001. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  13002. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
  13003. `${t}${t}${factory}${n}` +
  13004. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
  13005. isAsync: false,
  13006. name: null
  13007. })}{${_}` +
  13008. `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
  13009. `${t}})()`;
  13010. }
  13011. else {
  13012. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  13013. if (!namedExportsMode && hasExports) {
  13014. iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
  13015. }
  13016. }
  13017. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  13018. const wrapperParams = [factoryVar];
  13019. if (iifeNeedsGlobal) {
  13020. wrapperParams.unshift(globalVar);
  13021. }
  13022. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  13023. const iifeStart = iifeNeedsGlobal
  13024. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  13025. : '';
  13026. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  13027. const cjsIntro = iifeNeedsGlobal
  13028. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  13029. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  13030. : '';
  13031. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
  13032. cjsIntro +
  13033. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  13034. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  13035. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13036. // cf. https://v8.dev/blog/preparser#pife
  13037. `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
  13038. isAsync: false,
  13039. name: null
  13040. })}{${useStrict}${n}`;
  13041. const wrapperOutro = n + n + '}));';
  13042. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13043. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13044. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  13045. if (namespaceMarkers) {
  13046. namespaceMarkers = n + n + namespaceMarkers;
  13047. }
  13048. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  13049. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  13050. }
  13051. const finalisers = { amd, cjs, es, iife, system, umd };
  13052. class Source {
  13053. constructor(filename, content) {
  13054. this.isOriginal = true;
  13055. this.filename = filename;
  13056. this.content = content;
  13057. }
  13058. traceSegment(line, column, name) {
  13059. return { column, line, name, source: this };
  13060. }
  13061. }
  13062. class Link {
  13063. constructor(map, sources) {
  13064. this.sources = sources;
  13065. this.names = map.names;
  13066. this.mappings = map.mappings;
  13067. }
  13068. traceMappings() {
  13069. const sources = [];
  13070. const sourceIndexMap = new Map();
  13071. const sourcesContent = [];
  13072. const names = [];
  13073. const nameIndexMap = new Map();
  13074. const mappings = [];
  13075. for (const line of this.mappings) {
  13076. const tracedLine = [];
  13077. for (const segment of line) {
  13078. if (segment.length === 1)
  13079. continue;
  13080. const source = this.sources[segment[1]];
  13081. if (!source)
  13082. continue;
  13083. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  13084. if (traced) {
  13085. const { column, line, name, source: { content, filename } } = traced;
  13086. let sourceIndex = sourceIndexMap.get(filename);
  13087. if (sourceIndex === undefined) {
  13088. sourceIndex = sources.length;
  13089. sources.push(filename);
  13090. sourceIndexMap.set(filename, sourceIndex);
  13091. sourcesContent[sourceIndex] = content;
  13092. }
  13093. else if (sourcesContent[sourceIndex] == null) {
  13094. sourcesContent[sourceIndex] = content;
  13095. }
  13096. else if (content != null && sourcesContent[sourceIndex] !== content) {
  13097. return error({
  13098. message: `Multiple conflicting contents for sourcemap source ${filename}`
  13099. });
  13100. }
  13101. const tracedSegment = [segment[0], sourceIndex, line, column];
  13102. if (name) {
  13103. let nameIndex = nameIndexMap.get(name);
  13104. if (nameIndex === undefined) {
  13105. nameIndex = names.length;
  13106. names.push(name);
  13107. nameIndexMap.set(name, nameIndex);
  13108. }
  13109. tracedSegment[4] = nameIndex;
  13110. }
  13111. tracedLine.push(tracedSegment);
  13112. }
  13113. }
  13114. mappings.push(tracedLine);
  13115. }
  13116. return { mappings, names, sources, sourcesContent };
  13117. }
  13118. traceSegment(line, column, name) {
  13119. const segments = this.mappings[line];
  13120. if (!segments)
  13121. return null;
  13122. // binary search through segments for the given column
  13123. let searchStart = 0;
  13124. let searchEnd = segments.length - 1;
  13125. while (searchStart <= searchEnd) {
  13126. const m = (searchStart + searchEnd) >> 1;
  13127. const segment = segments[m];
  13128. // If a sourcemap does not have sufficient resolution to contain a
  13129. // necessary mapping, e.g. because it only contains line information, we
  13130. // use the best approximation we could find
  13131. if (segment[0] === column || searchStart === searchEnd) {
  13132. if (segment.length == 1)
  13133. return null;
  13134. const source = this.sources[segment[1]];
  13135. if (!source)
  13136. return null;
  13137. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  13138. }
  13139. if (segment[0] > column) {
  13140. searchEnd = m - 1;
  13141. }
  13142. else {
  13143. searchStart = m + 1;
  13144. }
  13145. }
  13146. return null;
  13147. }
  13148. }
  13149. function getLinkMap(warn) {
  13150. return function linkMap(source, map) {
  13151. if (map.mappings) {
  13152. return new Link(map, [source]);
  13153. }
  13154. warn({
  13155. code: 'SOURCEMAP_BROKEN',
  13156. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  13157. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  13158. 'documentation for help',
  13159. plugin: map.plugin,
  13160. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  13161. });
  13162. return new Link({
  13163. mappings: [],
  13164. names: []
  13165. }, [source]);
  13166. };
  13167. }
  13168. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  13169. let source;
  13170. if (!originalSourcemap) {
  13171. source = new Source(id, originalCode);
  13172. }
  13173. else {
  13174. const sources = originalSourcemap.sources;
  13175. const sourcesContent = originalSourcemap.sourcesContent || [];
  13176. const directory = dirname(id) || '.';
  13177. const sourceRoot = originalSourcemap.sourceRoot || '.';
  13178. const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
  13179. source = new Link(originalSourcemap, baseSources);
  13180. }
  13181. return sourcemapChain.reduce(linkMap, source);
  13182. }
  13183. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  13184. const linkMap = getLinkMap(warn);
  13185. const moduleSources = modules
  13186. .filter(module => !module.excludeFromSourcemap)
  13187. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  13188. const link = new Link(map, moduleSources);
  13189. const source = bundleSourcemapChain.reduce(linkMap, link);
  13190. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  13191. if (file) {
  13192. const directory = dirname(file);
  13193. sources = sources.map((source) => relative$1(directory, source));
  13194. file = basename(file);
  13195. }
  13196. sourcesContent = (excludeContent ? null : sourcesContent);
  13197. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  13198. }
  13199. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  13200. if (!sourcemapChain.length) {
  13201. return originalSourcemap;
  13202. }
  13203. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  13204. const map = source.traceMappings();
  13205. return { version: 3, ...map };
  13206. }
  13207. const createHash = () => createHash$1('sha256');
  13208. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  13209. amd: deconflictImportsOther,
  13210. cjs: deconflictImportsOther,
  13211. es: deconflictImportsEsmOrSystem,
  13212. iife: deconflictImportsOther,
  13213. system: deconflictImportsEsmOrSystem,
  13214. umd: deconflictImportsOther
  13215. };
  13216. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  13217. const reversedModules = modules.slice().reverse();
  13218. for (const module of reversedModules) {
  13219. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  13220. }
  13221. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  13222. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  13223. for (const module of reversedModules) {
  13224. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13225. }
  13226. }
  13227. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  13228. // This is needed for namespace reexports
  13229. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  13230. if (preserveModules || dependency instanceof ExternalModule) {
  13231. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  13232. }
  13233. }
  13234. for (const variable of imports) {
  13235. const module = variable.module;
  13236. const name = variable.name;
  13237. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  13238. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  13239. }
  13240. else if (module instanceof ExternalModule && name === 'default') {
  13241. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  13242. ? module.suggestedVariableName + '__default'
  13243. : module.suggestedVariableName, usedNames));
  13244. }
  13245. else {
  13246. variable.setRenderNames(null, getSafeName(name, usedNames));
  13247. }
  13248. }
  13249. for (const variable of syntheticExports) {
  13250. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13251. }
  13252. }
  13253. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  13254. for (const chunkOrExternalModule of dependencies) {
  13255. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  13256. }
  13257. for (const externalModuleOrChunk of deconflictedNamespace) {
  13258. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  13259. }
  13260. for (const externalModule of deconflictedDefault) {
  13261. if (deconflictedNamespace.has(externalModule) &&
  13262. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  13263. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  13264. }
  13265. else {
  13266. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  13267. }
  13268. }
  13269. for (const variable of imports) {
  13270. const module = variable.module;
  13271. if (module instanceof ExternalModule) {
  13272. const name = variable.name;
  13273. if (name === 'default') {
  13274. const moduleInterop = String(interop(module.id));
  13275. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13276. ? module.defaultVariableName
  13277. : module.variableName;
  13278. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  13279. variable.setRenderNames(variableName, 'default');
  13280. }
  13281. else {
  13282. variable.setRenderNames(null, variableName);
  13283. }
  13284. }
  13285. else if (name === '*') {
  13286. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  13287. ? module.namespaceVariableName
  13288. : module.variableName);
  13289. }
  13290. else {
  13291. // if the second parameter is `null`, it uses its "name" for the property name
  13292. variable.setRenderNames(module.variableName, null);
  13293. }
  13294. }
  13295. else {
  13296. const chunk = chunkByModule.get(module);
  13297. if (preserveModules && variable.isNamespace) {
  13298. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  13299. }
  13300. else if (chunk.exportMode === 'default') {
  13301. variable.setRenderNames(null, chunk.variableName);
  13302. }
  13303. else {
  13304. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  13305. }
  13306. }
  13307. }
  13308. }
  13309. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  13310. for (const module of modules) {
  13311. for (const variable of module.scope.variables.values()) {
  13312. if (variable.included &&
  13313. // this will only happen for exports in some formats
  13314. !(variable.renderBaseName ||
  13315. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  13316. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13317. }
  13318. }
  13319. if (includedNamespaces.has(module)) {
  13320. const namespace = module.namespace;
  13321. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  13322. }
  13323. }
  13324. }
  13325. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  13326. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  13327. const backSlashRegEx = /\\/g;
  13328. function escapeId(id) {
  13329. if (!id.match(needsEscapeRegEx))
  13330. return id;
  13331. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  13332. }
  13333. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  13334. let nameIndex = 0;
  13335. for (const variable of exports) {
  13336. let [exportName] = variable.name;
  13337. if (exportsByName.has(exportName)) {
  13338. do {
  13339. exportName = toBase64(++nameIndex);
  13340. // skip past leading number identifiers
  13341. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  13342. nameIndex += 9 * 64 ** (exportName.length - 1);
  13343. exportName = toBase64(nameIndex);
  13344. }
  13345. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  13346. }
  13347. exportsByName.set(exportName, variable);
  13348. exportNamesByVariable.set(variable, [exportName]);
  13349. }
  13350. }
  13351. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  13352. for (const variable of exports) {
  13353. let nameIndex = 0;
  13354. let exportName = variable.name;
  13355. while (exportsByName.has(exportName)) {
  13356. exportName = variable.name + '$' + ++nameIndex;
  13357. }
  13358. exportsByName.set(exportName, variable);
  13359. exportNamesByVariable.set(variable, [exportName]);
  13360. }
  13361. }
  13362. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  13363. const exportKeys = chunk.getExportNames();
  13364. if (exportMode === 'default') {
  13365. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  13366. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  13367. }
  13368. }
  13369. else if (exportMode === 'none' && exportKeys.length) {
  13370. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  13371. }
  13372. if (exportMode === 'auto') {
  13373. if (exportKeys.length === 0) {
  13374. exportMode = 'none';
  13375. }
  13376. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  13377. if (format === 'cjs' && unsetOptions.has('exports')) {
  13378. warn(errPreferNamedExports(facadeModuleId));
  13379. }
  13380. exportMode = 'default';
  13381. }
  13382. else {
  13383. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  13384. warn(errMixedExport(facadeModuleId, name));
  13385. }
  13386. exportMode = 'named';
  13387. }
  13388. }
  13389. return exportMode;
  13390. }
  13391. function guessIndentString(code) {
  13392. const lines = code.split('\n');
  13393. const tabbed = lines.filter(line => /^\t+/.test(line));
  13394. const spaced = lines.filter(line => /^ {2,}/.test(line));
  13395. if (tabbed.length === 0 && spaced.length === 0) {
  13396. return null;
  13397. }
  13398. // More lines tabbed than spaced? Assume tabs, and
  13399. // default to tabs in the case of a tie (or nothing
  13400. // to go on)
  13401. if (tabbed.length >= spaced.length) {
  13402. return '\t';
  13403. }
  13404. // Otherwise, we need to guess the multiple
  13405. const min = spaced.reduce((previous, current) => {
  13406. const numSpaces = /^ +/.exec(current)[0].length;
  13407. return Math.min(numSpaces, previous);
  13408. }, Infinity);
  13409. return new Array(min + 1).join(' ');
  13410. }
  13411. function getIndentString(modules, options) {
  13412. if (options.indent !== true)
  13413. return options.indent;
  13414. for (const module of modules) {
  13415. const indent = guessIndentString(module.originalCode);
  13416. if (indent !== null)
  13417. return indent;
  13418. }
  13419. return '\t';
  13420. }
  13421. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  13422. const staticDependencyBlocks = [];
  13423. const handledDependencies = new Set();
  13424. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  13425. const module = orderedModules[modulePos];
  13426. if (!handledDependencies.has(module)) {
  13427. const staticDependencies = [];
  13428. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  13429. staticDependencyBlocks.unshift(staticDependencies);
  13430. }
  13431. }
  13432. const dependencies = new Set();
  13433. for (const block of staticDependencyBlocks) {
  13434. for (const dependency of block) {
  13435. dependencies.add(dependency);
  13436. }
  13437. }
  13438. return dependencies;
  13439. }
  13440. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  13441. const dependencies = module.getDependenciesToBeIncluded();
  13442. for (const dependency of dependencies) {
  13443. if (dependency instanceof ExternalModule) {
  13444. staticDependencies.push(dependency);
  13445. continue;
  13446. }
  13447. const dependencyChunk = chunkByModule.get(dependency);
  13448. if (dependencyChunk !== chunk) {
  13449. staticDependencies.push(dependencyChunk);
  13450. continue;
  13451. }
  13452. if (!handledModules.has(dependency)) {
  13453. handledModules.add(dependency);
  13454. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  13455. }
  13456. }
  13457. }
  13458. function decodedSourcemap(map) {
  13459. if (!map)
  13460. return null;
  13461. if (typeof map === 'string') {
  13462. map = JSON.parse(map);
  13463. }
  13464. if (map.mappings === '') {
  13465. return {
  13466. mappings: [],
  13467. names: [],
  13468. sources: [],
  13469. version: 3
  13470. };
  13471. }
  13472. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  13473. return { ...map, mappings };
  13474. }
  13475. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  13476. const renderChunkReducer = (code, result, plugin) => {
  13477. if (result == null)
  13478. return code;
  13479. if (typeof result === 'string')
  13480. result = {
  13481. code: result,
  13482. map: undefined
  13483. };
  13484. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  13485. if (result.map !== null) {
  13486. const map = decodedSourcemap(result.map);
  13487. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  13488. }
  13489. return result.code;
  13490. };
  13491. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  13492. }
  13493. const lowercaseBundleKeys = Symbol('bundleKeys');
  13494. const FILE_PLACEHOLDER = {
  13495. type: 'placeholder'
  13496. };
  13497. const getOutputBundle = (outputBundleBase) => {
  13498. const reservedLowercaseBundleKeys = new Set();
  13499. return new Proxy(outputBundleBase, {
  13500. deleteProperty(target, key) {
  13501. if (typeof key === 'string') {
  13502. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  13503. }
  13504. return Reflect.deleteProperty(target, key);
  13505. },
  13506. get(target, key) {
  13507. if (key === lowercaseBundleKeys) {
  13508. return reservedLowercaseBundleKeys;
  13509. }
  13510. return Reflect.get(target, key);
  13511. },
  13512. set(target, key, value) {
  13513. if (typeof key === 'string') {
  13514. reservedLowercaseBundleKeys.add(key.toLowerCase());
  13515. }
  13516. return Reflect.set(target, key, value);
  13517. }
  13518. });
  13519. };
  13520. function renderNamePattern(pattern, patternName, replacements) {
  13521. if (isPathFragment(pattern))
  13522. return error(errFailedValidation(`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.`));
  13523. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  13524. if (!replacements.hasOwnProperty(type)) {
  13525. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  13526. }
  13527. const replacement = replacements[type]();
  13528. if (isPathFragment(replacement))
  13529. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  13530. return replacement;
  13531. });
  13532. }
  13533. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  13534. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  13535. return name;
  13536. const ext = extname(name);
  13537. name = name.substring(0, name.length - ext.length);
  13538. let uniqueName, uniqueIndex = 1;
  13539. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  13540. ;
  13541. return uniqueName;
  13542. }
  13543. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  13544. function getGlobalName(module, globals, hasExports, warn) {
  13545. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  13546. if (globalName) {
  13547. return globalName;
  13548. }
  13549. if (hasExports) {
  13550. warn({
  13551. code: 'MISSING_GLOBAL_NAME',
  13552. guess: module.variableName,
  13553. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  13554. source: module.id
  13555. });
  13556. return module.variableName;
  13557. }
  13558. }
  13559. class Chunk {
  13560. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  13561. this.orderedModules = orderedModules;
  13562. this.inputOptions = inputOptions;
  13563. this.outputOptions = outputOptions;
  13564. this.unsetOptions = unsetOptions;
  13565. this.pluginDriver = pluginDriver;
  13566. this.modulesById = modulesById;
  13567. this.chunkByModule = chunkByModule;
  13568. this.facadeChunkByModule = facadeChunkByModule;
  13569. this.includedNamespaces = includedNamespaces;
  13570. this.manualChunkAlias = manualChunkAlias;
  13571. this.entryModules = [];
  13572. this.exportMode = 'named';
  13573. this.facadeModule = null;
  13574. this.id = null;
  13575. this.namespaceVariableName = '';
  13576. this.needsExportsShim = false;
  13577. this.variableName = '';
  13578. this.accessedGlobalsByScope = new Map();
  13579. this.dependencies = new Set();
  13580. this.dynamicDependencies = new Set();
  13581. this.dynamicEntryModules = [];
  13582. this.dynamicName = null;
  13583. this.exportNamesByVariable = new Map();
  13584. this.exports = new Set();
  13585. this.exportsByName = new Map();
  13586. this.fileName = null;
  13587. this.implicitEntryModules = [];
  13588. this.implicitlyLoadedBefore = new Set();
  13589. this.imports = new Set();
  13590. this.includedReexportsByModule = new Map();
  13591. this.indentString = undefined;
  13592. // This may only be updated in the constructor
  13593. this.isEmpty = true;
  13594. this.name = null;
  13595. this.renderedDependencies = null;
  13596. this.renderedExports = null;
  13597. this.renderedHash = undefined;
  13598. this.renderedModuleSources = new Map();
  13599. this.renderedModules = Object.create(null);
  13600. this.renderedSource = null;
  13601. this.sortedExportNames = null;
  13602. this.strictFacade = false;
  13603. this.usedModules = undefined;
  13604. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  13605. const chunkModules = new Set(orderedModules);
  13606. for (const module of orderedModules) {
  13607. if (module.namespace.included) {
  13608. includedNamespaces.add(module);
  13609. }
  13610. if (this.isEmpty && module.isIncluded()) {
  13611. this.isEmpty = false;
  13612. }
  13613. if (module.info.isEntry || outputOptions.preserveModules) {
  13614. this.entryModules.push(module);
  13615. }
  13616. for (const importer of module.includedDynamicImporters) {
  13617. if (!chunkModules.has(importer)) {
  13618. this.dynamicEntryModules.push(module);
  13619. // Modules with synthetic exports need an artificial namespace for dynamic imports
  13620. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  13621. includedNamespaces.add(module);
  13622. this.exports.add(module.namespace);
  13623. }
  13624. }
  13625. }
  13626. if (module.implicitlyLoadedAfter.size > 0) {
  13627. this.implicitEntryModules.push(module);
  13628. }
  13629. }
  13630. this.suggestedVariableName = makeLegal(this.generateVariableName());
  13631. }
  13632. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  13633. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  13634. chunk.assignFacadeName(facadeName, facadedModule);
  13635. if (!facadeChunkByModule.has(facadedModule)) {
  13636. facadeChunkByModule.set(facadedModule, chunk);
  13637. }
  13638. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  13639. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  13640. }
  13641. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  13642. facadedModule.info.moduleSideEffects &&
  13643. facadedModule.hasEffects()) {
  13644. chunk.dependencies.add(chunkByModule.get(facadedModule));
  13645. }
  13646. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  13647. chunk.facadeModule = facadedModule;
  13648. chunk.strictFacade = true;
  13649. return chunk;
  13650. }
  13651. canModuleBeFacade(module, exposedVariables) {
  13652. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  13653. for (const exposedVariable of this.exports) {
  13654. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  13655. if (moduleExportNamesByVariable.size === 0 &&
  13656. module.isUserDefinedEntryPoint &&
  13657. module.preserveSignature === 'strict' &&
  13658. this.unsetOptions.has('preserveEntrySignatures')) {
  13659. this.inputOptions.onwarn({
  13660. code: 'EMPTY_FACADE',
  13661. id: module.id,
  13662. message: `To preserve the export signature of the entry module "${relativeId(module.id)}", an empty facade chunk was created. This often happens when creating a bundle for a web app where chunks are placed in script tags and exports are ignored. In this case it is recommended to set "preserveEntrySignatures: false" to avoid this and reduce the number of chunks. Otherwise if this is intentional, set "preserveEntrySignatures: 'strict'" explicitly to silence this warning.`,
  13663. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  13664. });
  13665. }
  13666. return false;
  13667. }
  13668. }
  13669. for (const exposedVariable of exposedVariables) {
  13670. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  13671. return false;
  13672. }
  13673. }
  13674. return true;
  13675. }
  13676. generateExports() {
  13677. this.sortedExportNames = null;
  13678. const remainingExports = new Set(this.exports);
  13679. if (this.facadeModule !== null &&
  13680. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  13681. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  13682. for (const [variable, exportNames] of exportNamesByVariable) {
  13683. this.exportNamesByVariable.set(variable, [...exportNames]);
  13684. for (const exportName of exportNames) {
  13685. this.exportsByName.set(exportName, variable);
  13686. }
  13687. remainingExports.delete(variable);
  13688. }
  13689. }
  13690. if (this.outputOptions.minifyInternalExports) {
  13691. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13692. }
  13693. else {
  13694. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13695. }
  13696. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  13697. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  13698. }
  13699. generateFacades() {
  13700. var _a;
  13701. const facades = [];
  13702. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  13703. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  13704. for (const module of entryModules) {
  13705. if (module.preserveSignature) {
  13706. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  13707. exposedVariables.add(exportedVariable);
  13708. }
  13709. }
  13710. }
  13711. for (const module of entryModules) {
  13712. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  13713. // mapping must run after Set 'name' dedupe
  13714. name => ({
  13715. name
  13716. }));
  13717. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  13718. requiredFacades.push({});
  13719. }
  13720. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  13721. if (requiredFacades.length === 0) {
  13722. requiredFacades.push({});
  13723. }
  13724. if (!this.facadeModule) {
  13725. const needsStrictFacade = module.preserveSignature === 'strict' ||
  13726. (module.preserveSignature === 'exports-only' &&
  13727. module.getExportNamesByVariable().size !== 0);
  13728. if (!needsStrictFacade ||
  13729. this.outputOptions.preserveModules ||
  13730. this.canModuleBeFacade(module, exposedVariables)) {
  13731. this.facadeModule = module;
  13732. this.facadeChunkByModule.set(module, this);
  13733. if (module.preserveSignature) {
  13734. this.strictFacade = needsStrictFacade;
  13735. }
  13736. this.assignFacadeName(requiredFacades.shift(), module);
  13737. }
  13738. }
  13739. for (const facadeName of requiredFacades) {
  13740. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  13741. }
  13742. }
  13743. for (const module of this.dynamicEntryModules) {
  13744. if (module.info.syntheticNamedExports)
  13745. continue;
  13746. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  13747. this.facadeModule = module;
  13748. this.facadeChunkByModule.set(module, this);
  13749. this.strictFacade = true;
  13750. this.dynamicName = getChunkNameFromModule(module);
  13751. }
  13752. else if (this.facadeModule === module &&
  13753. !this.strictFacade &&
  13754. this.canModuleBeFacade(module, exposedVariables)) {
  13755. this.strictFacade = true;
  13756. }
  13757. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  13758. this.includedNamespaces.add(module);
  13759. this.exports.add(module.namespace);
  13760. }
  13761. }
  13762. if (!this.outputOptions.preserveModules) {
  13763. this.addNecessaryImportsForFacades();
  13764. }
  13765. return facades;
  13766. }
  13767. generateId(addons, options, bundle, includeHash) {
  13768. if (this.fileName !== null) {
  13769. return this.fileName;
  13770. }
  13771. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  13772. ? [options.entryFileNames, 'output.entryFileNames']
  13773. : [options.chunkFileNames, 'output.chunkFileNames'];
  13774. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  13775. format: () => options.format,
  13776. hash: () => includeHash
  13777. ? this.computeContentHashWithDependencies(addons, options, bundle)
  13778. : '[hash]',
  13779. name: () => this.getChunkName()
  13780. }), bundle);
  13781. }
  13782. generateIdPreserveModules(preserveModulesRelativeDir, options, bundle, unsetOptions) {
  13783. const [{ id }] = this.orderedModules;
  13784. const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
  13785. let path;
  13786. const patternOpt = unsetOptions.has('entryFileNames')
  13787. ? '[name][assetExtname].js'
  13788. : options.entryFileNames;
  13789. const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
  13790. if (isAbsolute(sanitizedId)) {
  13791. const currentDir = dirname(sanitizedId);
  13792. const extension = extname(sanitizedId);
  13793. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13794. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13795. ext: () => extension.substring(1),
  13796. extname: () => extension,
  13797. format: () => options.format,
  13798. name: () => this.getChunkName()
  13799. });
  13800. const currentPath = `${currentDir}/${fileName}`;
  13801. const { preserveModulesRoot } = options;
  13802. if (preserveModulesRoot && resolve(currentPath).startsWith(preserveModulesRoot)) {
  13803. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  13804. }
  13805. else {
  13806. path = relative(preserveModulesRelativeDir, currentPath);
  13807. }
  13808. }
  13809. else {
  13810. const extension = extname(sanitizedId);
  13811. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13812. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13813. ext: () => extension.substring(1),
  13814. extname: () => extension,
  13815. format: () => options.format,
  13816. name: () => getAliasName(sanitizedId)
  13817. });
  13818. path = `_virtual/${fileName}`;
  13819. }
  13820. return makeUnique(normalize(path), bundle);
  13821. }
  13822. getChunkInfo() {
  13823. const facadeModule = this.facadeModule;
  13824. const getChunkName = this.getChunkName.bind(this);
  13825. return {
  13826. exports: this.getExportNames(),
  13827. facadeModuleId: facadeModule && facadeModule.id,
  13828. isDynamicEntry: this.dynamicEntryModules.length > 0,
  13829. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  13830. isImplicitEntry: this.implicitEntryModules.length > 0,
  13831. modules: this.renderedModules,
  13832. get name() {
  13833. return getChunkName();
  13834. },
  13835. type: 'chunk'
  13836. };
  13837. }
  13838. getChunkInfoWithFileNames() {
  13839. return Object.assign(this.getChunkInfo(), {
  13840. code: undefined,
  13841. dynamicImports: Array.from(this.dynamicDependencies, getId),
  13842. fileName: this.id,
  13843. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  13844. importedBindings: this.getImportedBindingsPerDependency(),
  13845. imports: Array.from(this.dependencies, getId),
  13846. map: undefined,
  13847. referencedFiles: this.getReferencedFiles()
  13848. });
  13849. }
  13850. getChunkName() {
  13851. var _a;
  13852. return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  13853. }
  13854. getExportNames() {
  13855. var _a;
  13856. return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
  13857. }
  13858. getRenderedHash() {
  13859. if (this.renderedHash)
  13860. return this.renderedHash;
  13861. const hash = createHash();
  13862. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  13863. if (pluginHash) {
  13864. augmentation += pluginHash;
  13865. }
  13866. return augmentation;
  13867. });
  13868. hash.update(hashAugmentation);
  13869. hash.update(this.renderedSource.toString());
  13870. hash.update(this.getExportNames()
  13871. .map(exportName => {
  13872. const variable = this.exportsByName.get(exportName);
  13873. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  13874. })
  13875. .join(','));
  13876. return (this.renderedHash = hash.digest('hex'));
  13877. }
  13878. getVariableExportName(variable) {
  13879. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  13880. return '*';
  13881. }
  13882. return this.exportNamesByVariable.get(variable)[0];
  13883. }
  13884. link() {
  13885. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  13886. for (const module of this.orderedModules) {
  13887. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  13888. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  13889. this.setUpChunkImportsAndExportsForModule(module);
  13890. }
  13891. }
  13892. // prerender allows chunk hashes and names to be generated before finalizing
  13893. preRender(options, inputBase, snippets) {
  13894. const { _, getPropertyAccess, n } = snippets;
  13895. const magicString = new Bundle$1({ separator: `${n}${n}` });
  13896. this.usedModules = [];
  13897. this.indentString = getIndentString(this.orderedModules, options);
  13898. const renderOptions = {
  13899. dynamicImportFunction: options.dynamicImportFunction,
  13900. exportNamesByVariable: this.exportNamesByVariable,
  13901. format: options.format,
  13902. freeze: options.freeze,
  13903. indent: this.indentString,
  13904. namespaceToStringTag: options.namespaceToStringTag,
  13905. outputPluginDriver: this.pluginDriver,
  13906. snippets
  13907. };
  13908. // for static and dynamic entry points, inline the execution list to avoid loading latency
  13909. if (options.hoistTransitiveImports &&
  13910. !this.outputOptions.preserveModules &&
  13911. this.facadeModule !== null) {
  13912. for (const dep of this.dependencies) {
  13913. if (dep instanceof Chunk)
  13914. this.inlineChunkDependencies(dep);
  13915. }
  13916. }
  13917. this.prepareModulesForRendering(snippets);
  13918. this.setIdentifierRenderResolutions(options);
  13919. let hoistedSource = '';
  13920. const renderedModules = this.renderedModules;
  13921. for (const module of this.orderedModules) {
  13922. let renderedLength = 0;
  13923. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  13924. const source = module.render(renderOptions).trim();
  13925. renderedLength = source.length();
  13926. if (renderedLength) {
  13927. if (options.compact && source.lastLine().includes('//'))
  13928. source.append('\n');
  13929. this.renderedModuleSources.set(module, source);
  13930. magicString.addSource(source);
  13931. this.usedModules.push(module);
  13932. }
  13933. const namespace = module.namespace;
  13934. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  13935. const rendered = namespace.renderBlock(renderOptions);
  13936. if (namespace.renderFirst())
  13937. hoistedSource += n + rendered;
  13938. else
  13939. magicString.addSource(new MagicString(rendered));
  13940. }
  13941. }
  13942. const { renderedExports, removedExports } = module.getRenderedExports();
  13943. const { renderedModuleSources } = this;
  13944. renderedModules[module.id] = {
  13945. get code() {
  13946. var _a, _b;
  13947. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  13948. },
  13949. originalLength: module.originalCode.length,
  13950. removedExports,
  13951. renderedExports,
  13952. renderedLength
  13953. };
  13954. }
  13955. if (hoistedSource)
  13956. magicString.prepend(hoistedSource + n + n);
  13957. if (this.needsExportsShim) {
  13958. magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  13959. }
  13960. if (options.compact) {
  13961. this.renderedSource = magicString;
  13962. }
  13963. else {
  13964. this.renderedSource = magicString.trim();
  13965. }
  13966. this.renderedHash = undefined;
  13967. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  13968. const chunkName = this.getChunkName();
  13969. this.inputOptions.onwarn({
  13970. chunkName,
  13971. code: 'EMPTY_BUNDLE',
  13972. message: `Generated an empty chunk: "${chunkName}"`
  13973. });
  13974. }
  13975. this.setExternalRenderPaths(options, inputBase);
  13976. this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
  13977. this.renderedExports =
  13978. this.exportMode === 'none'
  13979. ? []
  13980. : this.getChunkExportDeclarations(options.format, getPropertyAccess);
  13981. }
  13982. async render(options, addons, outputChunk, snippets) {
  13983. timeStart('render format', 2);
  13984. const format = options.format;
  13985. const finalise = finalisers[format];
  13986. if (options.dynamicImportFunction && format !== 'es') {
  13987. this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
  13988. }
  13989. // populate ids in the rendered declarations only here
  13990. // as chunk ids known only after prerender
  13991. for (const dependency of this.dependencies) {
  13992. const renderedDependency = this.renderedDependencies.get(dependency);
  13993. if (dependency instanceof ExternalModule) {
  13994. const originalId = dependency.renderPath;
  13995. renderedDependency.id = escapeId(dependency.renormalizeRenderPath
  13996. ? getImportPath(this.id, originalId, false, false)
  13997. : originalId);
  13998. }
  13999. else {
  14000. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  14001. renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
  14002. }
  14003. }
  14004. this.finaliseDynamicImports(options, snippets);
  14005. this.finaliseImportMetas(format, snippets);
  14006. const hasExports = this.renderedExports.length !== 0 ||
  14007. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  14008. let topLevelAwaitModule = null;
  14009. const accessedGlobals = new Set();
  14010. for (const module of this.orderedModules) {
  14011. if (module.usesTopLevelAwait) {
  14012. topLevelAwaitModule = module.id;
  14013. }
  14014. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  14015. if (accessedGlobalVariables) {
  14016. for (const name of accessedGlobalVariables) {
  14017. accessedGlobals.add(name);
  14018. }
  14019. }
  14020. }
  14021. if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
  14022. return error({
  14023. code: 'INVALID_TLA_FORMAT',
  14024. id: topLevelAwaitModule,
  14025. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  14026. });
  14027. }
  14028. /* istanbul ignore next */
  14029. if (!this.id) {
  14030. throw new Error('Internal Error: expecting chunk id');
  14031. }
  14032. const magicString = finalise(this.renderedSource, {
  14033. accessedGlobals,
  14034. dependencies: [...this.renderedDependencies.values()],
  14035. exports: this.renderedExports,
  14036. hasExports,
  14037. id: this.id,
  14038. indent: this.indentString,
  14039. intro: addons.intro,
  14040. isEntryFacade: this.outputOptions.preserveModules ||
  14041. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  14042. isModuleFacade: this.facadeModule !== null,
  14043. namedExportsMode: this.exportMode !== 'default',
  14044. outro: addons.outro,
  14045. snippets,
  14046. usesTopLevelAwait: topLevelAwaitModule !== null,
  14047. warn: this.inputOptions.onwarn
  14048. }, options);
  14049. if (addons.banner)
  14050. magicString.prepend(addons.banner);
  14051. if (addons.footer)
  14052. magicString.append(addons.footer);
  14053. const prevCode = magicString.toString();
  14054. timeEnd('render format', 2);
  14055. let map = null;
  14056. const chunkSourcemapChain = [];
  14057. let code = await renderChunk({
  14058. code: prevCode,
  14059. options,
  14060. outputPluginDriver: this.pluginDriver,
  14061. renderChunk: outputChunk,
  14062. sourcemapChain: chunkSourcemapChain
  14063. });
  14064. if (options.sourcemap) {
  14065. timeStart('sourcemap', 2);
  14066. let file;
  14067. if (options.file)
  14068. file = resolve(options.sourcemapFile || options.file);
  14069. else if (options.dir)
  14070. file = resolve(options.dir, this.id);
  14071. else
  14072. file = resolve(this.id);
  14073. const decodedMap = magicString.generateDecodedMap({});
  14074. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  14075. map.sources = map.sources
  14076. .map(sourcePath => {
  14077. const { sourcemapPathTransform } = options;
  14078. if (sourcemapPathTransform) {
  14079. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  14080. if (typeof newSourcePath !== 'string') {
  14081. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  14082. }
  14083. return newSourcePath;
  14084. }
  14085. return sourcePath;
  14086. })
  14087. .map(normalize);
  14088. timeEnd('sourcemap', 2);
  14089. }
  14090. if (!options.compact && code[code.length - 1] !== '\n')
  14091. code += '\n';
  14092. return { code, map };
  14093. }
  14094. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  14095. for (const module of moduleDependencies) {
  14096. if (module instanceof Module) {
  14097. const chunk = this.chunkByModule.get(module);
  14098. if (chunk && chunk !== this) {
  14099. chunkDependencies.add(chunk);
  14100. }
  14101. }
  14102. else {
  14103. chunkDependencies.add(module);
  14104. }
  14105. }
  14106. }
  14107. addNecessaryImportsForFacades() {
  14108. for (const [module, variables] of this.includedReexportsByModule) {
  14109. if (this.includedNamespaces.has(module)) {
  14110. for (const variable of variables) {
  14111. this.imports.add(variable);
  14112. }
  14113. }
  14114. }
  14115. }
  14116. assignFacadeName({ fileName, name }, facadedModule) {
  14117. if (fileName) {
  14118. this.fileName = fileName;
  14119. }
  14120. else {
  14121. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  14122. }
  14123. }
  14124. checkCircularDependencyImport(variable, importingModule) {
  14125. const variableModule = variable.module;
  14126. if (variableModule instanceof Module) {
  14127. const exportChunk = this.chunkByModule.get(variableModule);
  14128. let alternativeReexportModule;
  14129. do {
  14130. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  14131. if (alternativeReexportModule) {
  14132. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  14133. if (exportingChunk && exportingChunk !== exportChunk) {
  14134. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  14135. }
  14136. importingModule = alternativeReexportModule;
  14137. }
  14138. } while (alternativeReexportModule);
  14139. }
  14140. }
  14141. computeContentHashWithDependencies(addons, options, bundle) {
  14142. const hash = createHash();
  14143. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
  14144. hash.update(options.format);
  14145. const dependenciesForHashing = new Set([this]);
  14146. for (const current of dependenciesForHashing) {
  14147. if (current instanceof ExternalModule) {
  14148. hash.update(`:${current.renderPath}`);
  14149. }
  14150. else {
  14151. hash.update(current.getRenderedHash());
  14152. hash.update(current.generateId(addons, options, bundle, false));
  14153. }
  14154. if (current instanceof ExternalModule)
  14155. continue;
  14156. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  14157. dependenciesForHashing.add(dependency);
  14158. }
  14159. }
  14160. return hash.digest('hex').substr(0, 8);
  14161. }
  14162. ensureReexportsAreAvailableForModule(module) {
  14163. const includedReexports = [];
  14164. const map = module.getExportNamesByVariable();
  14165. for (const exportedVariable of map.keys()) {
  14166. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  14167. const importedVariable = isSynthetic
  14168. ? exportedVariable.getBaseVariable()
  14169. : exportedVariable;
  14170. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  14171. this.checkCircularDependencyImport(importedVariable, module);
  14172. const exportingModule = importedVariable.module;
  14173. if (exportingModule instanceof Module) {
  14174. const chunk = this.chunkByModule.get(exportingModule);
  14175. if (chunk && chunk !== this) {
  14176. chunk.exports.add(importedVariable);
  14177. includedReexports.push(importedVariable);
  14178. if (isSynthetic) {
  14179. this.imports.add(importedVariable);
  14180. }
  14181. }
  14182. }
  14183. }
  14184. }
  14185. if (includedReexports.length) {
  14186. this.includedReexportsByModule.set(module, includedReexports);
  14187. }
  14188. }
  14189. finaliseDynamicImports(options, snippets) {
  14190. const stripKnownJsExtensions = options.format === 'amd' && !options.amd.forceJsExtensionForImports;
  14191. for (const [module, code] of this.renderedModuleSources) {
  14192. for (const { node, resolution } of module.dynamicImports) {
  14193. const chunk = this.chunkByModule.get(resolution);
  14194. const facadeChunk = this.facadeChunkByModule.get(resolution);
  14195. if (!resolution || !node.included || chunk === this) {
  14196. continue;
  14197. }
  14198. const renderedResolution = resolution instanceof Module
  14199. ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
  14200. : resolution instanceof ExternalModule
  14201. ? `'${escapeId(resolution.renormalizeRenderPath
  14202. ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
  14203. : resolution.renderPath)}'`
  14204. : resolution;
  14205. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  14206. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  14207. chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
  14208. }
  14209. }
  14210. }
  14211. finaliseImportMetas(format, snippets) {
  14212. for (const [module, code] of this.renderedModuleSources) {
  14213. for (const importMeta of module.importMetas) {
  14214. importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
  14215. }
  14216. }
  14217. }
  14218. generateVariableName() {
  14219. if (this.manualChunkAlias) {
  14220. return this.manualChunkAlias;
  14221. }
  14222. const moduleForNaming = this.entryModules[0] ||
  14223. this.implicitEntryModules[0] ||
  14224. this.dynamicEntryModules[0] ||
  14225. this.orderedModules[this.orderedModules.length - 1];
  14226. if (moduleForNaming) {
  14227. return getChunkNameFromModule(moduleForNaming);
  14228. }
  14229. return 'chunk';
  14230. }
  14231. getChunkDependencyDeclarations(options, getPropertyAccess) {
  14232. const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
  14233. const reexportSpecifiers = this.getReexportSpecifiers();
  14234. const dependencyDeclaration = new Map();
  14235. for (const dep of this.dependencies) {
  14236. const imports = importSpecifiers.get(dep) || null;
  14237. const reexports = reexportSpecifiers.get(dep) || null;
  14238. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  14239. dependencyDeclaration.set(dep, {
  14240. defaultVariableName: dep.defaultVariableName,
  14241. globalName: (dep instanceof ExternalModule &&
  14242. (options.format === 'umd' || options.format === 'iife') &&
  14243. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  14244. id: undefined,
  14245. imports,
  14246. isChunk: dep instanceof Chunk,
  14247. name: dep.variableName,
  14248. namedExportsMode,
  14249. namespaceVariableName: dep.namespaceVariableName,
  14250. reexports
  14251. });
  14252. }
  14253. return dependencyDeclaration;
  14254. }
  14255. getChunkExportDeclarations(format, getPropertyAccess) {
  14256. const exports = [];
  14257. for (const exportName of this.getExportNames()) {
  14258. if (exportName[0] === '*')
  14259. continue;
  14260. const variable = this.exportsByName.get(exportName);
  14261. if (!(variable instanceof SyntheticNamedExportVariable)) {
  14262. const module = variable.module;
  14263. if (module && this.chunkByModule.get(module) !== this)
  14264. continue;
  14265. }
  14266. let expression = null;
  14267. let hoisted = false;
  14268. let local = variable.getName(getPropertyAccess);
  14269. if (variable instanceof LocalVariable) {
  14270. for (const declaration of variable.declarations) {
  14271. if (declaration.parent instanceof FunctionDeclaration ||
  14272. (declaration instanceof ExportDefaultDeclaration &&
  14273. declaration.declaration instanceof FunctionDeclaration)) {
  14274. hoisted = true;
  14275. break;
  14276. }
  14277. }
  14278. }
  14279. else if (variable instanceof SyntheticNamedExportVariable) {
  14280. expression = local;
  14281. if (format === 'es') {
  14282. local = variable.renderName;
  14283. }
  14284. }
  14285. exports.push({
  14286. exported: exportName,
  14287. expression,
  14288. hoisted,
  14289. local
  14290. });
  14291. }
  14292. return exports;
  14293. }
  14294. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  14295. const dependencies = new Set();
  14296. const deconflictedDefault = new Set();
  14297. const deconflictedNamespace = new Set();
  14298. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  14299. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  14300. const module = variable.module;
  14301. if (module instanceof ExternalModule) {
  14302. dependencies.add(module);
  14303. if (addNonNamespacesAndInteropHelpers) {
  14304. if (variable.name === 'default') {
  14305. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  14306. deconflictedDefault.add(module);
  14307. }
  14308. }
  14309. else if (variable.name === '*') {
  14310. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  14311. deconflictedNamespace.add(module);
  14312. }
  14313. }
  14314. }
  14315. }
  14316. else {
  14317. const chunk = this.chunkByModule.get(module);
  14318. if (chunk !== this) {
  14319. dependencies.add(chunk);
  14320. if (addNonNamespacesAndInteropHelpers &&
  14321. chunk.exportMode === 'default' &&
  14322. variable.isNamespace) {
  14323. deconflictedNamespace.add(chunk);
  14324. }
  14325. }
  14326. }
  14327. }
  14328. }
  14329. if (addDependenciesWithoutBindings) {
  14330. for (const dependency of this.dependencies) {
  14331. dependencies.add(dependency);
  14332. }
  14333. }
  14334. return { deconflictedDefault, deconflictedNamespace, dependencies };
  14335. }
  14336. getFallbackChunkName() {
  14337. if (this.manualChunkAlias) {
  14338. return this.manualChunkAlias;
  14339. }
  14340. if (this.dynamicName) {
  14341. return this.dynamicName;
  14342. }
  14343. if (this.fileName) {
  14344. return getAliasName(this.fileName);
  14345. }
  14346. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  14347. }
  14348. getImportSpecifiers(getPropertyAccess) {
  14349. const { interop } = this.outputOptions;
  14350. const importsByDependency = new Map();
  14351. for (const variable of this.imports) {
  14352. const module = variable.module;
  14353. let dependency;
  14354. let imported;
  14355. if (module instanceof ExternalModule) {
  14356. dependency = module;
  14357. imported = variable.name;
  14358. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14359. return error(errUnexpectedNamedImport(module.id, imported, false));
  14360. }
  14361. }
  14362. else {
  14363. dependency = this.chunkByModule.get(module);
  14364. imported = dependency.getVariableExportName(variable);
  14365. }
  14366. getOrCreate(importsByDependency, dependency, () => []).push({
  14367. imported,
  14368. local: variable.getName(getPropertyAccess)
  14369. });
  14370. }
  14371. return importsByDependency;
  14372. }
  14373. getImportedBindingsPerDependency() {
  14374. const importSpecifiers = {};
  14375. for (const [dependency, declaration] of this.renderedDependencies) {
  14376. const specifiers = new Set();
  14377. if (declaration.imports) {
  14378. for (const { imported } of declaration.imports) {
  14379. specifiers.add(imported);
  14380. }
  14381. }
  14382. if (declaration.reexports) {
  14383. for (const { imported } of declaration.reexports) {
  14384. specifiers.add(imported);
  14385. }
  14386. }
  14387. importSpecifiers[dependency.id] = [...specifiers];
  14388. }
  14389. return importSpecifiers;
  14390. }
  14391. getReexportSpecifiers() {
  14392. const { externalLiveBindings, interop } = this.outputOptions;
  14393. const reexportSpecifiers = new Map();
  14394. for (let exportName of this.getExportNames()) {
  14395. let dependency;
  14396. let imported;
  14397. let needsLiveBinding = false;
  14398. if (exportName[0] === '*') {
  14399. const id = exportName.substring(1);
  14400. if (interop(id) === 'defaultOnly') {
  14401. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  14402. }
  14403. needsLiveBinding = externalLiveBindings;
  14404. dependency = this.modulesById.get(id);
  14405. imported = exportName = '*';
  14406. }
  14407. else {
  14408. const variable = this.exportsByName.get(exportName);
  14409. if (variable instanceof SyntheticNamedExportVariable)
  14410. continue;
  14411. const module = variable.module;
  14412. if (module instanceof Module) {
  14413. dependency = this.chunkByModule.get(module);
  14414. if (dependency === this)
  14415. continue;
  14416. imported = dependency.getVariableExportName(variable);
  14417. needsLiveBinding = variable.isReassigned;
  14418. }
  14419. else {
  14420. dependency = module;
  14421. imported = variable.name;
  14422. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14423. return error(errUnexpectedNamedImport(module.id, imported, true));
  14424. }
  14425. needsLiveBinding =
  14426. externalLiveBindings &&
  14427. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  14428. }
  14429. }
  14430. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  14431. imported,
  14432. needsLiveBinding,
  14433. reexported: exportName
  14434. });
  14435. }
  14436. return reexportSpecifiers;
  14437. }
  14438. getReferencedFiles() {
  14439. const referencedFiles = [];
  14440. for (const module of this.orderedModules) {
  14441. for (const meta of module.importMetas) {
  14442. const fileName = meta.getReferencedFileName(this.pluginDriver);
  14443. if (fileName) {
  14444. referencedFiles.push(fileName);
  14445. }
  14446. }
  14447. }
  14448. return referencedFiles;
  14449. }
  14450. inlineChunkDependencies(chunk) {
  14451. for (const dep of chunk.dependencies) {
  14452. if (this.dependencies.has(dep))
  14453. continue;
  14454. this.dependencies.add(dep);
  14455. if (dep instanceof Chunk) {
  14456. this.inlineChunkDependencies(dep);
  14457. }
  14458. }
  14459. }
  14460. prepareModulesForRendering(snippets) {
  14461. var _a;
  14462. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  14463. for (const module of this.orderedModules) {
  14464. for (const { node, resolution } of module.dynamicImports) {
  14465. if (node.included) {
  14466. if (resolution instanceof Module) {
  14467. const chunk = this.chunkByModule.get(resolution);
  14468. if (chunk === this) {
  14469. node.setInternalResolution(resolution.namespace);
  14470. }
  14471. else {
  14472. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14473. }
  14474. }
  14475. else {
  14476. node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14477. }
  14478. }
  14479. }
  14480. for (const importMeta of module.importMetas) {
  14481. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  14482. }
  14483. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14484. module.namespace.prepare(accessedGlobalsByScope);
  14485. }
  14486. }
  14487. }
  14488. setExternalRenderPaths(options, inputBase) {
  14489. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  14490. if (dependency instanceof ExternalModule) {
  14491. dependency.setRenderPath(options, inputBase);
  14492. }
  14493. }
  14494. }
  14495. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  14496. const syntheticExports = new Set();
  14497. for (const exportName of this.getExportNames()) {
  14498. const exportVariable = this.exportsByName.get(exportName);
  14499. if (format !== 'es' &&
  14500. format !== 'system' &&
  14501. exportVariable.isReassigned &&
  14502. !exportVariable.isId) {
  14503. exportVariable.setRenderNames('exports', exportName);
  14504. }
  14505. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  14506. syntheticExports.add(exportVariable);
  14507. }
  14508. else {
  14509. exportVariable.setRenderNames(null, null);
  14510. }
  14511. }
  14512. for (const module of this.orderedModules) {
  14513. if (module.needsExportShim) {
  14514. this.needsExportsShim = true;
  14515. break;
  14516. }
  14517. }
  14518. const usedNames = new Set(['Object', 'Promise']);
  14519. if (this.needsExportsShim) {
  14520. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  14521. }
  14522. if (namespaceToStringTag) {
  14523. usedNames.add('Symbol');
  14524. }
  14525. switch (format) {
  14526. case 'system':
  14527. usedNames.add('module').add('exports');
  14528. break;
  14529. case 'es':
  14530. break;
  14531. case 'cjs':
  14532. usedNames.add('module').add('require').add('__filename').add('__dirname');
  14533. // fallthrough
  14534. default:
  14535. usedNames.add('exports');
  14536. for (const helper of HELPER_NAMES) {
  14537. usedNames.add(helper);
  14538. }
  14539. }
  14540. deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
  14541. }
  14542. setUpChunkImportsAndExportsForModule(module) {
  14543. const moduleImports = new Set(module.includedImports);
  14544. // when we are not preserving modules, we need to make all namespace variables available for
  14545. // rendering the namespace object
  14546. if (!this.outputOptions.preserveModules) {
  14547. if (this.includedNamespaces.has(module)) {
  14548. const memberVariables = module.namespace.getMemberVariables();
  14549. for (const variable of Object.values(memberVariables)) {
  14550. moduleImports.add(variable);
  14551. }
  14552. }
  14553. }
  14554. for (let variable of moduleImports) {
  14555. if (variable instanceof ExportDefaultVariable) {
  14556. variable = variable.getOriginalVariable();
  14557. }
  14558. if (variable instanceof SyntheticNamedExportVariable) {
  14559. variable = variable.getBaseVariable();
  14560. }
  14561. const chunk = this.chunkByModule.get(variable.module);
  14562. if (chunk !== this) {
  14563. this.imports.add(variable);
  14564. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  14565. variable.module instanceof Module) {
  14566. chunk.exports.add(variable);
  14567. this.checkCircularDependencyImport(variable, module);
  14568. }
  14569. }
  14570. }
  14571. if (this.includedNamespaces.has(module) ||
  14572. (module.info.isEntry && module.preserveSignature !== false) ||
  14573. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  14574. this.ensureReexportsAreAvailableForModule(module);
  14575. }
  14576. for (const { node, resolution } of module.dynamicImports) {
  14577. if (node.included &&
  14578. resolution instanceof Module &&
  14579. this.chunkByModule.get(resolution) === this &&
  14580. !this.includedNamespaces.has(resolution)) {
  14581. this.includedNamespaces.add(resolution);
  14582. this.ensureReexportsAreAvailableForModule(resolution);
  14583. }
  14584. }
  14585. }
  14586. }
  14587. function getChunkNameFromModule(module) {
  14588. var _a, _b, _c, _d;
  14589. return ((_d = (_b = (_a = module.chunkNames.find(({ isUserDefined }) => isUserDefined)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : (_c = module.chunkNames[0]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : getAliasName(module.id));
  14590. }
  14591. const QUERY_HASH_REGEX = /[?#]/;
  14592. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  14593. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  14594. async function createAddons(options, outputPluginDriver) {
  14595. try {
  14596. let [banner, footer, intro, outro] = await Promise.all([
  14597. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  14598. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  14599. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  14600. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  14601. ]);
  14602. if (intro)
  14603. intro += '\n\n';
  14604. if (outro)
  14605. outro = `\n\n${outro}`;
  14606. if (banner.length)
  14607. banner += '\n';
  14608. if (footer.length)
  14609. footer = '\n' + footer;
  14610. return { banner, footer, intro, outro };
  14611. }
  14612. catch (err) {
  14613. return error({
  14614. code: 'ADDON_ERROR',
  14615. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  14616. \tError Message: ${err.message}`
  14617. });
  14618. }
  14619. }
  14620. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  14621. const chunkDefinitions = [];
  14622. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  14623. const manualChunkModulesByAlias = Object.create(null);
  14624. for (const [entry, alias] of manualChunkAliasByEntry) {
  14625. const chunkModules = (manualChunkModulesByAlias[alias] =
  14626. manualChunkModulesByAlias[alias] || []);
  14627. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  14628. }
  14629. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  14630. chunkDefinitions.push({ alias, modules });
  14631. }
  14632. const assignedEntryPointsByModule = new Map();
  14633. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  14634. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  14635. const staticEntries = new Set(entryModules);
  14636. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  14637. const modulesToHandle = new Set([entry]);
  14638. for (const module of modulesToHandle) {
  14639. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  14640. if (dynamicDependentEntryPoints &&
  14641. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  14642. continue;
  14643. }
  14644. else {
  14645. assignedEntryPoints.add(entry);
  14646. }
  14647. for (const dependency of module.getDependenciesToBeIncluded()) {
  14648. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14649. modulesToHandle.add(dependency);
  14650. }
  14651. }
  14652. }
  14653. }
  14654. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  14655. const entriesToCheck = new Set(entryPoints);
  14656. for (const entry of entriesToCheck) {
  14657. if (!containedIn.has(entry)) {
  14658. if (staticEntries.has(entry))
  14659. return false;
  14660. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  14661. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  14662. entriesToCheck.add(dependentEntry);
  14663. }
  14664. }
  14665. }
  14666. return true;
  14667. }
  14668. for (const entry of entryModules) {
  14669. if (!modulesInManualChunks.has(entry)) {
  14670. assignEntryToStaticDependencies(entry, null);
  14671. }
  14672. }
  14673. for (const entry of dynamicEntryModules) {
  14674. if (!modulesInManualChunks.has(entry)) {
  14675. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  14676. }
  14677. }
  14678. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  14679. return chunkDefinitions;
  14680. }
  14681. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  14682. const modulesToHandle = new Set([entry]);
  14683. for (const module of modulesToHandle) {
  14684. modulesInManualChunks.add(module);
  14685. manualChunkModules.push(module);
  14686. for (const dependency of module.dependencies) {
  14687. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14688. modulesToHandle.add(dependency);
  14689. }
  14690. }
  14691. }
  14692. }
  14693. function analyzeModuleGraph(entryModules) {
  14694. const dynamicEntryModules = new Set();
  14695. const dependentEntryPointsByModule = new Map();
  14696. const entriesToHandle = new Set(entryModules);
  14697. for (const currentEntry of entriesToHandle) {
  14698. const modulesToHandle = new Set([currentEntry]);
  14699. for (const module of modulesToHandle) {
  14700. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  14701. for (const dependency of module.getDependenciesToBeIncluded()) {
  14702. if (!(dependency instanceof ExternalModule)) {
  14703. modulesToHandle.add(dependency);
  14704. }
  14705. }
  14706. for (const { resolution } of module.dynamicImports) {
  14707. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  14708. dynamicEntryModules.add(resolution);
  14709. entriesToHandle.add(resolution);
  14710. }
  14711. }
  14712. for (const dependency of module.implicitlyLoadedBefore) {
  14713. dynamicEntryModules.add(dependency);
  14714. entriesToHandle.add(dependency);
  14715. }
  14716. }
  14717. }
  14718. return { dependentEntryPointsByModule, dynamicEntryModules };
  14719. }
  14720. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  14721. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  14722. for (const dynamicEntry of dynamicEntryModules) {
  14723. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  14724. for (const importer of [
  14725. ...dynamicEntry.includedDynamicImporters,
  14726. ...dynamicEntry.implicitlyLoadedAfter
  14727. ]) {
  14728. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  14729. dynamicDependentEntryPoints.add(entryPoint);
  14730. }
  14731. }
  14732. }
  14733. return dynamicallyDependentEntryPointsByDynamicEntry;
  14734. }
  14735. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  14736. const chunkModules = Object.create(null);
  14737. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  14738. let chunkSignature = '';
  14739. for (const entry of allEntryPoints) {
  14740. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  14741. }
  14742. const chunk = chunkModules[chunkSignature];
  14743. if (chunk) {
  14744. chunk.push(module);
  14745. }
  14746. else {
  14747. chunkModules[chunkSignature] = [module];
  14748. }
  14749. }
  14750. return Object.values(chunkModules).map(modules => ({
  14751. alias: null,
  14752. modules
  14753. }));
  14754. }
  14755. // ported from https://github.com/substack/node-commondir
  14756. function commondir(files) {
  14757. if (files.length === 0)
  14758. return '/';
  14759. if (files.length === 1)
  14760. return dirname(files[0]);
  14761. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  14762. const pathSegements = file.split(/\/+|\\+/);
  14763. let i;
  14764. for (i = 0; commonSegments[i] === pathSegements[i] &&
  14765. i < Math.min(commonSegments.length, pathSegements.length); i++)
  14766. ;
  14767. return commonSegments.slice(0, i);
  14768. }, files[0].split(/\/+|\\+/));
  14769. // Windows correctly handles paths with forward-slashes
  14770. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  14771. }
  14772. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  14773. function sortByExecutionOrder(units) {
  14774. units.sort(compareExecIndex);
  14775. }
  14776. function analyseModuleExecution(entryModules) {
  14777. let nextExecIndex = 0;
  14778. const cyclePaths = [];
  14779. const analysedModules = new Set();
  14780. const dynamicImports = new Set();
  14781. const parents = new Map();
  14782. const orderedModules = [];
  14783. const analyseModule = (module) => {
  14784. if (module instanceof Module) {
  14785. for (const dependency of module.dependencies) {
  14786. if (parents.has(dependency)) {
  14787. if (!analysedModules.has(dependency)) {
  14788. cyclePaths.push(getCyclePath(dependency, module, parents));
  14789. }
  14790. continue;
  14791. }
  14792. parents.set(dependency, module);
  14793. analyseModule(dependency);
  14794. }
  14795. for (const dependency of module.implicitlyLoadedBefore) {
  14796. dynamicImports.add(dependency);
  14797. }
  14798. for (const { resolution } of module.dynamicImports) {
  14799. if (resolution instanceof Module) {
  14800. dynamicImports.add(resolution);
  14801. }
  14802. }
  14803. orderedModules.push(module);
  14804. }
  14805. module.execIndex = nextExecIndex++;
  14806. analysedModules.add(module);
  14807. };
  14808. for (const curEntry of entryModules) {
  14809. if (!parents.has(curEntry)) {
  14810. parents.set(curEntry, null);
  14811. analyseModule(curEntry);
  14812. }
  14813. }
  14814. for (const curEntry of dynamicImports) {
  14815. if (!parents.has(curEntry)) {
  14816. parents.set(curEntry, null);
  14817. analyseModule(curEntry);
  14818. }
  14819. }
  14820. return { cyclePaths, orderedModules };
  14821. }
  14822. function getCyclePath(module, parent, parents) {
  14823. const cycleSymbol = Symbol(module.id);
  14824. const path = [relativeId(module.id)];
  14825. let nextModule = parent;
  14826. module.cycles.add(cycleSymbol);
  14827. while (nextModule !== module) {
  14828. nextModule.cycles.add(cycleSymbol);
  14829. path.push(relativeId(nextModule.id));
  14830. nextModule = parents.get(nextModule);
  14831. }
  14832. path.push(path[0]);
  14833. path.reverse();
  14834. return path;
  14835. }
  14836. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  14837. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  14838. const cnst = constBindings ? 'const' : 'var';
  14839. const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
  14840. const getFunctionIntro = arrowFunctions
  14841. ? (params, { isAsync, name }) => {
  14842. const singleParam = params.length === 1;
  14843. const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
  14844. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
  14845. }
  14846. : getNonArrowFunctionIntro;
  14847. const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
  14848. `${getFunctionIntro(params, {
  14849. isAsync: false,
  14850. name
  14851. })}${arrowFunctions
  14852. ? lineBreakIndent
  14853. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  14854. : ''
  14855. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  14856. arrowFunctions
  14857. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  14858. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  14859. ];
  14860. const isValidPropName = reservedNamesAsProps
  14861. ? (name) => validPropName.test(name)
  14862. : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
  14863. return {
  14864. _,
  14865. cnst,
  14866. getDirectReturnFunction,
  14867. getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  14868. const [left, right] = getDirectReturnFunction(params, {
  14869. functionReturn: true,
  14870. lineBreakIndent: null,
  14871. name: null
  14872. });
  14873. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  14874. },
  14875. getFunctionIntro,
  14876. getNonArrowFunctionIntro,
  14877. getObject(fields, { lineBreakIndent }) {
  14878. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  14879. return `{${fields
  14880. .map(([key, value]) => {
  14881. if (key === null)
  14882. return `${prefix}${value}`;
  14883. const needsQuotes = !isValidPropName(key);
  14884. return key === value && objectShorthand && !needsQuotes
  14885. ? prefix + key
  14886. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  14887. })
  14888. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  14889. },
  14890. getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  14891. n,
  14892. s
  14893. };
  14894. }
  14895. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  14896. const validPropName = /^(?!\d)[\w$]+$/;
  14897. class Bundle {
  14898. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  14899. this.outputOptions = outputOptions;
  14900. this.unsetOptions = unsetOptions;
  14901. this.inputOptions = inputOptions;
  14902. this.pluginDriver = pluginDriver;
  14903. this.graph = graph;
  14904. this.facadeChunkByModule = new Map();
  14905. this.includedNamespaces = new Set();
  14906. }
  14907. async generate(isWrite) {
  14908. timeStart('GENERATE', 1);
  14909. const outputBundleBase = Object.create(null);
  14910. const outputBundle = getOutputBundle(outputBundleBase);
  14911. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  14912. try {
  14913. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  14914. timeStart('generate chunks', 2);
  14915. const chunks = await this.generateChunks();
  14916. if (chunks.length > 1) {
  14917. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  14918. }
  14919. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  14920. timeEnd('generate chunks', 2);
  14921. timeStart('render modules', 2);
  14922. // We need to create addons before prerender because at the moment, there
  14923. // can be no async code between prerender and render due to internal state
  14924. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  14925. const snippets = getGenerateCodeSnippets(this.outputOptions);
  14926. this.prerenderChunks(chunks, inputBase, snippets);
  14927. timeEnd('render modules', 2);
  14928. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
  14929. }
  14930. catch (err) {
  14931. await this.pluginDriver.hookParallel('renderError', [err]);
  14932. throw err;
  14933. }
  14934. await this.pluginDriver.hookSeq('generateBundle', [
  14935. this.outputOptions,
  14936. outputBundle,
  14937. isWrite
  14938. ]);
  14939. this.finaliseAssets(outputBundle);
  14940. timeEnd('GENERATE', 1);
  14941. return outputBundleBase;
  14942. }
  14943. async addFinalizedChunksToBundle(chunks, inputBase, addons, bundle, snippets) {
  14944. this.assignChunkIds(chunks, inputBase, addons, bundle);
  14945. for (const chunk of chunks) {
  14946. bundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  14947. }
  14948. await Promise.all(chunks.map(async (chunk) => {
  14949. const outputChunk = bundle[chunk.id];
  14950. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
  14951. }));
  14952. }
  14953. async addManualChunks(manualChunks) {
  14954. const manualChunkAliasByEntry = new Map();
  14955. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  14956. alias,
  14957. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  14958. })));
  14959. for (const { alias, entries } of chunkEntries) {
  14960. for (const entry of entries) {
  14961. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  14962. }
  14963. }
  14964. return manualChunkAliasByEntry;
  14965. }
  14966. assignChunkIds(chunks, inputBase, addons, bundle) {
  14967. const entryChunks = [];
  14968. const otherChunks = [];
  14969. for (const chunk of chunks) {
  14970. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  14971. ? entryChunks
  14972. : otherChunks).push(chunk);
  14973. }
  14974. // make sure entry chunk names take precedence with regard to deconflicting
  14975. const chunksForNaming = entryChunks.concat(otherChunks);
  14976. for (const chunk of chunksForNaming) {
  14977. if (this.outputOptions.file) {
  14978. chunk.id = basename(this.outputOptions.file);
  14979. }
  14980. else if (this.outputOptions.preserveModules) {
  14981. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  14982. }
  14983. else {
  14984. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  14985. }
  14986. bundle[chunk.id] = FILE_PLACEHOLDER;
  14987. }
  14988. }
  14989. assignManualChunks(getManualChunk) {
  14990. const manualChunkAliasesWithEntry = [];
  14991. const manualChunksApi = {
  14992. getModuleIds: () => this.graph.modulesById.keys(),
  14993. getModuleInfo: this.graph.getModuleInfo
  14994. };
  14995. for (const module of this.graph.modulesById.values()) {
  14996. if (module instanceof Module) {
  14997. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  14998. if (typeof manualChunkAlias === 'string') {
  14999. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  15000. }
  15001. }
  15002. }
  15003. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  15004. const manualChunkAliasByEntry = new Map();
  15005. for (const [alias, module] of manualChunkAliasesWithEntry) {
  15006. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  15007. }
  15008. return manualChunkAliasByEntry;
  15009. }
  15010. finaliseAssets(outputBundle) {
  15011. for (const file of Object.values(outputBundle)) {
  15012. if (!file.type) {
  15013. warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', true, this.inputOptions);
  15014. file.type = 'asset';
  15015. }
  15016. if (this.outputOptions.validate && 'code' in file) {
  15017. try {
  15018. this.graph.contextParse(file.code, {
  15019. allowHashBang: true,
  15020. ecmaVersion: 'latest'
  15021. });
  15022. }
  15023. catch (err) {
  15024. this.inputOptions.onwarn(errChunkInvalid(file, err));
  15025. }
  15026. }
  15027. }
  15028. this.pluginDriver.finaliseAssets();
  15029. }
  15030. async generateChunks() {
  15031. const { manualChunks } = this.outputOptions;
  15032. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  15033. ? await this.addManualChunks(manualChunks)
  15034. : this.assignManualChunks(manualChunks);
  15035. const chunks = [];
  15036. const chunkByModule = new Map();
  15037. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  15038. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  15039. : this.outputOptions.preserveModules
  15040. ? getIncludedModules(this.graph.modulesById).map(module => ({
  15041. alias: null,
  15042. modules: [module]
  15043. }))
  15044. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  15045. sortByExecutionOrder(modules);
  15046. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  15047. chunks.push(chunk);
  15048. for (const module of modules) {
  15049. chunkByModule.set(module, chunk);
  15050. }
  15051. }
  15052. for (const chunk of chunks) {
  15053. chunk.link();
  15054. }
  15055. const facades = [];
  15056. for (const chunk of chunks) {
  15057. facades.push(...chunk.generateFacades());
  15058. }
  15059. return [...chunks, ...facades];
  15060. }
  15061. prerenderChunks(chunks, inputBase, snippets) {
  15062. for (const chunk of chunks) {
  15063. chunk.generateExports();
  15064. }
  15065. for (const chunk of chunks) {
  15066. chunk.preRender(this.outputOptions, inputBase, snippets);
  15067. }
  15068. }
  15069. }
  15070. function getAbsoluteEntryModulePaths(chunks) {
  15071. const absoluteEntryModulePaths = [];
  15072. for (const chunk of chunks) {
  15073. for (const entryModule of chunk.entryModules) {
  15074. if (isAbsolute(entryModule.id)) {
  15075. absoluteEntryModulePaths.push(entryModule.id);
  15076. }
  15077. }
  15078. }
  15079. return absoluteEntryModulePaths;
  15080. }
  15081. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  15082. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  15083. return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  15084. if (typeof outputOptions.file === 'string')
  15085. return error(errInvalidOption('output.file', 'outputdir', 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
  15086. if (outputOptions.sourcemapFile)
  15087. return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
  15088. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  15089. onWarn(errInvalidOption('output.amd.id', 'outputamd', 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
  15090. }
  15091. function getIncludedModules(modulesById) {
  15092. return [...modulesById.values()].filter((module) => module instanceof Module &&
  15093. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  15094. }
  15095. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  15096. const existingAlias = manualChunkAliasByEntry.get(module);
  15097. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  15098. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  15099. }
  15100. manualChunkAliasByEntry.set(module, alias);
  15101. }
  15102. // This file was generated. Do not modify manually!
  15103. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  15104. // This file was generated. Do not modify manually!
  15105. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  15106. // This file was generated. Do not modify manually!
  15107. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  15108. // This file was generated. Do not modify manually!
  15109. 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";
  15110. // These are a run-length and offset encoded representation of the
  15111. // Reserved word lists for various dialects of the language
  15112. var reservedWords = {
  15113. 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",
  15114. 5: "class enum extends super const export import",
  15115. 6: "enum",
  15116. strict: "implements interface let package private protected public static yield",
  15117. strictBind: "eval arguments"
  15118. };
  15119. // And the keywords
  15120. 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";
  15121. var keywords$1 = {
  15122. 5: ecma5AndLessKeywords,
  15123. "5module": ecma5AndLessKeywords + " export import",
  15124. 6: ecma5AndLessKeywords + " const class extends export import super"
  15125. };
  15126. var keywordRelationalOperator = /^in(stanceof)?$/;
  15127. // ## Character categories
  15128. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  15129. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  15130. // This has a complexity linear to the value of the code. The
  15131. // assumption is that looking up astral identifier characters is
  15132. // rare.
  15133. function isInAstralSet(code, set) {
  15134. var pos = 0x10000;
  15135. for (var i = 0; i < set.length; i += 2) {
  15136. pos += set[i];
  15137. if (pos > code) { return false }
  15138. pos += set[i + 1];
  15139. if (pos >= code) { return true }
  15140. }
  15141. }
  15142. // Test whether a given character code starts an identifier.
  15143. function isIdentifierStart(code, astral) {
  15144. if (code < 65) { return code === 36 }
  15145. if (code < 91) { return true }
  15146. if (code < 97) { return code === 95 }
  15147. if (code < 123) { return true }
  15148. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  15149. if (astral === false) { return false }
  15150. return isInAstralSet(code, astralIdentifierStartCodes)
  15151. }
  15152. // Test whether a given character is part of an identifier.
  15153. function isIdentifierChar(code, astral) {
  15154. if (code < 48) { return code === 36 }
  15155. if (code < 58) { return true }
  15156. if (code < 65) { return false }
  15157. if (code < 91) { return true }
  15158. if (code < 97) { return code === 95 }
  15159. if (code < 123) { return true }
  15160. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  15161. if (astral === false) { return false }
  15162. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  15163. }
  15164. // ## Token types
  15165. // The assignment of fine-grained, information-carrying type objects
  15166. // allows the tokenizer to store the information it has about a
  15167. // token in a way that is very cheap for the parser to look up.
  15168. // All token type variables start with an underscore, to make them
  15169. // easy to recognize.
  15170. // The `beforeExpr` property is used to disambiguate between regular
  15171. // expressions and divisions. It is set on all token types that can
  15172. // be followed by an expression (thus, a slash after them would be a
  15173. // regular expression).
  15174. //
  15175. // The `startsExpr` property is used to check if the token ends a
  15176. // `yield` expression. It is set on all token types that either can
  15177. // directly start an expression (like a quotation mark) or can
  15178. // continue an expression (like the body of a string).
  15179. //
  15180. // `isLoop` marks a keyword as starting a loop, which is important
  15181. // to know when parsing a label, in order to allow or disallow
  15182. // continue jumps to that label.
  15183. var TokenType = function TokenType(label, conf) {
  15184. if ( conf === void 0 ) conf = {};
  15185. this.label = label;
  15186. this.keyword = conf.keyword;
  15187. this.beforeExpr = !!conf.beforeExpr;
  15188. this.startsExpr = !!conf.startsExpr;
  15189. this.isLoop = !!conf.isLoop;
  15190. this.isAssign = !!conf.isAssign;
  15191. this.prefix = !!conf.prefix;
  15192. this.postfix = !!conf.postfix;
  15193. this.binop = conf.binop || null;
  15194. this.updateContext = null;
  15195. };
  15196. function binop(name, prec) {
  15197. return new TokenType(name, {beforeExpr: true, binop: prec})
  15198. }
  15199. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  15200. // Map keyword names to token types.
  15201. var keywords = {};
  15202. // Succinct definitions of keyword token types
  15203. function kw(name, options) {
  15204. if ( options === void 0 ) options = {};
  15205. options.keyword = name;
  15206. return keywords[name] = new TokenType(name, options)
  15207. }
  15208. var types$1 = {
  15209. num: new TokenType("num", startsExpr),
  15210. regexp: new TokenType("regexp", startsExpr),
  15211. string: new TokenType("string", startsExpr),
  15212. name: new TokenType("name", startsExpr),
  15213. privateId: new TokenType("privateId", startsExpr),
  15214. eof: new TokenType("eof"),
  15215. // Punctuation token types.
  15216. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  15217. bracketR: new TokenType("]"),
  15218. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  15219. braceR: new TokenType("}"),
  15220. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  15221. parenR: new TokenType(")"),
  15222. comma: new TokenType(",", beforeExpr),
  15223. semi: new TokenType(";", beforeExpr),
  15224. colon: new TokenType(":", beforeExpr),
  15225. dot: new TokenType("."),
  15226. question: new TokenType("?", beforeExpr),
  15227. questionDot: new TokenType("?."),
  15228. arrow: new TokenType("=>", beforeExpr),
  15229. template: new TokenType("template"),
  15230. invalidTemplate: new TokenType("invalidTemplate"),
  15231. ellipsis: new TokenType("...", beforeExpr),
  15232. backQuote: new TokenType("`", startsExpr),
  15233. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  15234. // Operators. These carry several kinds of properties to help the
  15235. // parser use them properly (the presence of these properties is
  15236. // what categorizes them as operators).
  15237. //
  15238. // `binop`, when present, specifies that this operator is a binary
  15239. // operator, and will refer to its precedence.
  15240. //
  15241. // `prefix` and `postfix` mark the operator as a prefix or postfix
  15242. // unary operator.
  15243. //
  15244. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  15245. // binary operators with a very low precedence, that should result
  15246. // in AssignmentExpression nodes.
  15247. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  15248. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  15249. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  15250. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  15251. logicalOR: binop("||", 1),
  15252. logicalAND: binop("&&", 2),
  15253. bitwiseOR: binop("|", 3),
  15254. bitwiseXOR: binop("^", 4),
  15255. bitwiseAND: binop("&", 5),
  15256. equality: binop("==/!=/===/!==", 6),
  15257. relational: binop("</>/<=/>=", 7),
  15258. bitShift: binop("<</>>/>>>", 8),
  15259. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  15260. modulo: binop("%", 10),
  15261. star: binop("*", 10),
  15262. slash: binop("/", 10),
  15263. starstar: new TokenType("**", {beforeExpr: true}),
  15264. coalesce: binop("??", 1),
  15265. // Keyword token types.
  15266. _break: kw("break"),
  15267. _case: kw("case", beforeExpr),
  15268. _catch: kw("catch"),
  15269. _continue: kw("continue"),
  15270. _debugger: kw("debugger"),
  15271. _default: kw("default", beforeExpr),
  15272. _do: kw("do", {isLoop: true, beforeExpr: true}),
  15273. _else: kw("else", beforeExpr),
  15274. _finally: kw("finally"),
  15275. _for: kw("for", {isLoop: true}),
  15276. _function: kw("function", startsExpr),
  15277. _if: kw("if"),
  15278. _return: kw("return", beforeExpr),
  15279. _switch: kw("switch"),
  15280. _throw: kw("throw", beforeExpr),
  15281. _try: kw("try"),
  15282. _var: kw("var"),
  15283. _const: kw("const"),
  15284. _while: kw("while", {isLoop: true}),
  15285. _with: kw("with"),
  15286. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  15287. _this: kw("this", startsExpr),
  15288. _super: kw("super", startsExpr),
  15289. _class: kw("class", startsExpr),
  15290. _extends: kw("extends", beforeExpr),
  15291. _export: kw("export"),
  15292. _import: kw("import", startsExpr),
  15293. _null: kw("null", startsExpr),
  15294. _true: kw("true", startsExpr),
  15295. _false: kw("false", startsExpr),
  15296. _in: kw("in", {beforeExpr: true, binop: 7}),
  15297. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  15298. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  15299. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  15300. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  15301. };
  15302. // Matches a whole line break (where CRLF is considered a single
  15303. // line break). Used to count lines.
  15304. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  15305. var lineBreakG = new RegExp(lineBreak.source, "g");
  15306. function isNewLine(code) {
  15307. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  15308. }
  15309. function nextLineBreak(code, from, end) {
  15310. if ( end === void 0 ) end = code.length;
  15311. for (var i = from; i < end; i++) {
  15312. var next = code.charCodeAt(i);
  15313. if (isNewLine(next))
  15314. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  15315. }
  15316. return -1
  15317. }
  15318. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  15319. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  15320. var ref = Object.prototype;
  15321. var hasOwnProperty = ref.hasOwnProperty;
  15322. var toString = ref.toString;
  15323. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  15324. hasOwnProperty.call(obj, propName)
  15325. ); });
  15326. var isArray = Array.isArray || (function (obj) { return (
  15327. toString.call(obj) === "[object Array]"
  15328. ); });
  15329. function wordsRegexp(words) {
  15330. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  15331. }
  15332. function codePointToString(code) {
  15333. // UTF-16 Decoding
  15334. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  15335. code -= 0x10000;
  15336. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  15337. }
  15338. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  15339. // These are used when `options.locations` is on, for the
  15340. // `startLoc` and `endLoc` properties.
  15341. var Position = function Position(line, col) {
  15342. this.line = line;
  15343. this.column = col;
  15344. };
  15345. Position.prototype.offset = function offset (n) {
  15346. return new Position(this.line, this.column + n)
  15347. };
  15348. var SourceLocation = function SourceLocation(p, start, end) {
  15349. this.start = start;
  15350. this.end = end;
  15351. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  15352. };
  15353. // The `getLineInfo` function is mostly useful when the
  15354. // `locations` option is off (for performance reasons) and you
  15355. // want to find the line/column position for a given character
  15356. // offset. `input` should be the code string that the offset refers
  15357. // into.
  15358. function getLineInfo(input, offset) {
  15359. for (var line = 1, cur = 0;;) {
  15360. var nextBreak = nextLineBreak(input, cur, offset);
  15361. if (nextBreak < 0) { return new Position(line, offset - cur) }
  15362. ++line;
  15363. cur = nextBreak;
  15364. }
  15365. }
  15366. // A second argument must be given to configure the parser process.
  15367. // These options are recognized (only `ecmaVersion` is required):
  15368. var defaultOptions = {
  15369. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  15370. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  15371. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  15372. // latest version the library supports). This influences support
  15373. // for strict mode, the set of reserved words, and support for
  15374. // new syntax features.
  15375. ecmaVersion: null,
  15376. // `sourceType` indicates the mode the code should be parsed in.
  15377. // Can be either `"script"` or `"module"`. This influences global
  15378. // strict mode and parsing of `import` and `export` declarations.
  15379. sourceType: "script",
  15380. // `onInsertedSemicolon` can be a callback that will be called
  15381. // when a semicolon is automatically inserted. It will be passed
  15382. // the position of the comma as an offset, and if `locations` is
  15383. // enabled, it is given the location as a `{line, column}` object
  15384. // as second argument.
  15385. onInsertedSemicolon: null,
  15386. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  15387. // trailing commas.
  15388. onTrailingComma: null,
  15389. // By default, reserved words are only enforced if ecmaVersion >= 5.
  15390. // Set `allowReserved` to a boolean value to explicitly turn this on
  15391. // an off. When this option has the value "never", reserved words
  15392. // and keywords can also not be used as property names.
  15393. allowReserved: null,
  15394. // When enabled, a return at the top level is not considered an
  15395. // error.
  15396. allowReturnOutsideFunction: false,
  15397. // When enabled, import/export statements are not constrained to
  15398. // appearing at the top of the program, and an import.meta expression
  15399. // in a script isn't considered an error.
  15400. allowImportExportEverywhere: false,
  15401. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  15402. // When enabled, await identifiers are allowed to appear at the top-level scope,
  15403. // but they are still not allowed in non-async functions.
  15404. allowAwaitOutsideFunction: null,
  15405. // When enabled, super identifiers are not constrained to
  15406. // appearing in methods and do not raise an error when they appear elsewhere.
  15407. allowSuperOutsideMethod: null,
  15408. // When enabled, hashbang directive in the beginning of file
  15409. // is allowed and treated as a line comment.
  15410. allowHashBang: false,
  15411. // When `locations` is on, `loc` properties holding objects with
  15412. // `start` and `end` properties in `{line, column}` form (with
  15413. // line being 1-based and column 0-based) will be attached to the
  15414. // nodes.
  15415. locations: false,
  15416. // A function can be passed as `onToken` option, which will
  15417. // cause Acorn to call that function with object in the same
  15418. // format as tokens returned from `tokenizer().getToken()`. Note
  15419. // that you are not allowed to call the parser from the
  15420. // callback—that will corrupt its internal state.
  15421. onToken: null,
  15422. // A function can be passed as `onComment` option, which will
  15423. // cause Acorn to call that function with `(block, text, start,
  15424. // end)` parameters whenever a comment is skipped. `block` is a
  15425. // boolean indicating whether this is a block (`/* */`) comment,
  15426. // `text` is the content of the comment, and `start` and `end` are
  15427. // character offsets that denote the start and end of the comment.
  15428. // When the `locations` option is on, two more parameters are
  15429. // passed, the full `{line, column}` locations of the start and
  15430. // end of the comments. Note that you are not allowed to call the
  15431. // parser from the callback—that will corrupt its internal state.
  15432. onComment: null,
  15433. // Nodes have their start and end characters offsets recorded in
  15434. // `start` and `end` properties (directly on the node, rather than
  15435. // the `loc` object, which holds line/column data. To also add a
  15436. // [semi-standardized][range] `range` property holding a `[start,
  15437. // end]` array with the same numbers, set the `ranges` option to
  15438. // `true`.
  15439. //
  15440. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  15441. ranges: false,
  15442. // It is possible to parse multiple files into a single AST by
  15443. // passing the tree produced by parsing the first file as
  15444. // `program` option in subsequent parses. This will add the
  15445. // toplevel forms of the parsed file to the `Program` (top) node
  15446. // of an existing parse tree.
  15447. program: null,
  15448. // When `locations` is on, you can pass this to record the source
  15449. // file in every node's `loc` object.
  15450. sourceFile: null,
  15451. // This value, if given, is stored in every node, whether
  15452. // `locations` is on or off.
  15453. directSourceFile: null,
  15454. // When enabled, parenthesized expressions are represented by
  15455. // (non-standard) ParenthesizedExpression nodes
  15456. preserveParens: false
  15457. };
  15458. // Interpret and default an options object
  15459. var warnedAboutEcmaVersion = false;
  15460. function getOptions(opts) {
  15461. var options = {};
  15462. for (var opt in defaultOptions)
  15463. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  15464. if (options.ecmaVersion === "latest") {
  15465. options.ecmaVersion = 1e8;
  15466. } else if (options.ecmaVersion == null) {
  15467. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  15468. warnedAboutEcmaVersion = true;
  15469. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  15470. }
  15471. options.ecmaVersion = 11;
  15472. } else if (options.ecmaVersion >= 2015) {
  15473. options.ecmaVersion -= 2009;
  15474. }
  15475. if (options.allowReserved == null)
  15476. { options.allowReserved = options.ecmaVersion < 5; }
  15477. if (isArray(options.onToken)) {
  15478. var tokens = options.onToken;
  15479. options.onToken = function (token) { return tokens.push(token); };
  15480. }
  15481. if (isArray(options.onComment))
  15482. { options.onComment = pushComment(options, options.onComment); }
  15483. return options
  15484. }
  15485. function pushComment(options, array) {
  15486. return function(block, text, start, end, startLoc, endLoc) {
  15487. var comment = {
  15488. type: block ? "Block" : "Line",
  15489. value: text,
  15490. start: start,
  15491. end: end
  15492. };
  15493. if (options.locations)
  15494. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  15495. if (options.ranges)
  15496. { comment.range = [start, end]; }
  15497. array.push(comment);
  15498. }
  15499. }
  15500. // Each scope gets a bitset that may contain these flags
  15501. var
  15502. SCOPE_TOP = 1,
  15503. SCOPE_FUNCTION = 2,
  15504. SCOPE_ASYNC = 4,
  15505. SCOPE_GENERATOR = 8,
  15506. SCOPE_ARROW = 16,
  15507. SCOPE_SIMPLE_CATCH = 32,
  15508. SCOPE_SUPER = 64,
  15509. SCOPE_DIRECT_SUPER = 128,
  15510. SCOPE_CLASS_STATIC_BLOCK = 256,
  15511. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  15512. function functionFlags(async, generator) {
  15513. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  15514. }
  15515. // Used in checkLVal* and declareName to determine the type of a binding
  15516. var
  15517. BIND_NONE = 0, // Not a binding
  15518. BIND_VAR = 1, // Var-style binding
  15519. BIND_LEXICAL = 2, // Let- or const-style binding
  15520. BIND_FUNCTION = 3, // Function declaration
  15521. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  15522. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  15523. var Parser = function Parser(options, input, startPos) {
  15524. this.options = options = getOptions(options);
  15525. this.sourceFile = options.sourceFile;
  15526. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  15527. var reserved = "";
  15528. if (options.allowReserved !== true) {
  15529. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  15530. if (options.sourceType === "module") { reserved += " await"; }
  15531. }
  15532. this.reservedWords = wordsRegexp(reserved);
  15533. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  15534. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  15535. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  15536. this.input = String(input);
  15537. // Used to signal to callers of `readWord1` whether the word
  15538. // contained any escape sequences. This is needed because words with
  15539. // escape sequences must not be interpreted as keywords.
  15540. this.containsEsc = false;
  15541. // Set up token state
  15542. // The current position of the tokenizer in the input.
  15543. if (startPos) {
  15544. this.pos = startPos;
  15545. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  15546. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  15547. } else {
  15548. this.pos = this.lineStart = 0;
  15549. this.curLine = 1;
  15550. }
  15551. // Properties of the current token:
  15552. // Its type
  15553. this.type = types$1.eof;
  15554. // For tokens that include more information than their type, the value
  15555. this.value = null;
  15556. // Its start and end offset
  15557. this.start = this.end = this.pos;
  15558. // And, if locations are used, the {line, column} object
  15559. // corresponding to those offsets
  15560. this.startLoc = this.endLoc = this.curPosition();
  15561. // Position information for the previous token
  15562. this.lastTokEndLoc = this.lastTokStartLoc = null;
  15563. this.lastTokStart = this.lastTokEnd = this.pos;
  15564. // The context stack is used to superficially track syntactic
  15565. // context to predict whether a regular expression is allowed in a
  15566. // given position.
  15567. this.context = this.initialContext();
  15568. this.exprAllowed = true;
  15569. // Figure out if it's a module code.
  15570. this.inModule = options.sourceType === "module";
  15571. this.strict = this.inModule || this.strictDirective(this.pos);
  15572. // Used to signify the start of a potential arrow function
  15573. this.potentialArrowAt = -1;
  15574. this.potentialArrowInForAwait = false;
  15575. // Positions to delayed-check that yield/await does not exist in default parameters.
  15576. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  15577. // Labels in scope.
  15578. this.labels = [];
  15579. // Thus-far undefined exports.
  15580. this.undefinedExports = Object.create(null);
  15581. // If enabled, skip leading hashbang line.
  15582. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  15583. { this.skipLineComment(2); }
  15584. // Scope tracking for duplicate variable names (see scope.js)
  15585. this.scopeStack = [];
  15586. this.enterScope(SCOPE_TOP);
  15587. // For RegExp validation
  15588. this.regexpState = null;
  15589. // The stack of private names.
  15590. // Each element has two properties: 'declared' and 'used'.
  15591. // When it exited from the outermost class definition, all used private names must be declared.
  15592. this.privateNameStack = [];
  15593. };
  15594. 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 } };
  15595. Parser.prototype.parse = function parse () {
  15596. var node = this.options.program || this.startNode();
  15597. this.nextToken();
  15598. return this.parseTopLevel(node)
  15599. };
  15600. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  15601. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  15602. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  15603. prototypeAccessors.canAwait.get = function () {
  15604. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  15605. var scope = this.scopeStack[i];
  15606. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  15607. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  15608. }
  15609. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  15610. };
  15611. prototypeAccessors.allowSuper.get = function () {
  15612. var ref = this.currentThisScope();
  15613. var flags = ref.flags;
  15614. var inClassFieldInit = ref.inClassFieldInit;
  15615. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  15616. };
  15617. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  15618. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  15619. prototypeAccessors.allowNewDotTarget.get = function () {
  15620. var ref = this.currentThisScope();
  15621. var flags = ref.flags;
  15622. var inClassFieldInit = ref.inClassFieldInit;
  15623. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  15624. };
  15625. prototypeAccessors.inClassStaticBlock.get = function () {
  15626. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  15627. };
  15628. Parser.extend = function extend () {
  15629. var plugins = [], len = arguments.length;
  15630. while ( len-- ) plugins[ len ] = arguments[ len ];
  15631. var cls = this;
  15632. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  15633. return cls
  15634. };
  15635. Parser.parse = function parse (input, options) {
  15636. return new this(options, input).parse()
  15637. };
  15638. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  15639. var parser = new this(options, input, pos);
  15640. parser.nextToken();
  15641. return parser.parseExpression()
  15642. };
  15643. Parser.tokenizer = function tokenizer (input, options) {
  15644. return new this(options, input)
  15645. };
  15646. Object.defineProperties( Parser.prototype, prototypeAccessors );
  15647. var pp$9 = Parser.prototype;
  15648. // ## Parser utilities
  15649. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  15650. pp$9.strictDirective = function(start) {
  15651. if (this.options.ecmaVersion < 5) { return false }
  15652. for (;;) {
  15653. // Try to find string literal.
  15654. skipWhiteSpace.lastIndex = start;
  15655. start += skipWhiteSpace.exec(this.input)[0].length;
  15656. var match = literal.exec(this.input.slice(start));
  15657. if (!match) { return false }
  15658. if ((match[1] || match[2]) === "use strict") {
  15659. skipWhiteSpace.lastIndex = start + match[0].length;
  15660. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  15661. var next = this.input.charAt(end);
  15662. return next === ";" || next === "}" ||
  15663. (lineBreak.test(spaceAfter[0]) &&
  15664. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  15665. }
  15666. start += match[0].length;
  15667. // Skip semicolon, if any.
  15668. skipWhiteSpace.lastIndex = start;
  15669. start += skipWhiteSpace.exec(this.input)[0].length;
  15670. if (this.input[start] === ";")
  15671. { start++; }
  15672. }
  15673. };
  15674. // Predicate that tests whether the next token is of the given
  15675. // type, and if yes, consumes it as a side effect.
  15676. pp$9.eat = function(type) {
  15677. if (this.type === type) {
  15678. this.next();
  15679. return true
  15680. } else {
  15681. return false
  15682. }
  15683. };
  15684. // Tests whether parsed token is a contextual keyword.
  15685. pp$9.isContextual = function(name) {
  15686. return this.type === types$1.name && this.value === name && !this.containsEsc
  15687. };
  15688. // Consumes contextual keyword if possible.
  15689. pp$9.eatContextual = function(name) {
  15690. if (!this.isContextual(name)) { return false }
  15691. this.next();
  15692. return true
  15693. };
  15694. // Asserts that following token is given contextual keyword.
  15695. pp$9.expectContextual = function(name) {
  15696. if (!this.eatContextual(name)) { this.unexpected(); }
  15697. };
  15698. // Test whether a semicolon can be inserted at the current position.
  15699. pp$9.canInsertSemicolon = function() {
  15700. return this.type === types$1.eof ||
  15701. this.type === types$1.braceR ||
  15702. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15703. };
  15704. pp$9.insertSemicolon = function() {
  15705. if (this.canInsertSemicolon()) {
  15706. if (this.options.onInsertedSemicolon)
  15707. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  15708. return true
  15709. }
  15710. };
  15711. // Consume a semicolon, or, failing that, see if we are allowed to
  15712. // pretend that there is a semicolon at this position.
  15713. pp$9.semicolon = function() {
  15714. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  15715. };
  15716. pp$9.afterTrailingComma = function(tokType, notNext) {
  15717. if (this.type === tokType) {
  15718. if (this.options.onTrailingComma)
  15719. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  15720. if (!notNext)
  15721. { this.next(); }
  15722. return true
  15723. }
  15724. };
  15725. // Expect a token of a given type. If found, consume it, otherwise,
  15726. // raise an unexpected token error.
  15727. pp$9.expect = function(type) {
  15728. this.eat(type) || this.unexpected();
  15729. };
  15730. // Raise an unexpected token error.
  15731. pp$9.unexpected = function(pos) {
  15732. this.raise(pos != null ? pos : this.start, "Unexpected token");
  15733. };
  15734. var DestructuringErrors = function DestructuringErrors() {
  15735. this.shorthandAssign =
  15736. this.trailingComma =
  15737. this.parenthesizedAssign =
  15738. this.parenthesizedBind =
  15739. this.doubleProto =
  15740. -1;
  15741. };
  15742. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  15743. if (!refDestructuringErrors) { return }
  15744. if (refDestructuringErrors.trailingComma > -1)
  15745. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  15746. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  15747. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  15748. };
  15749. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  15750. if (!refDestructuringErrors) { return false }
  15751. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  15752. var doubleProto = refDestructuringErrors.doubleProto;
  15753. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  15754. if (shorthandAssign >= 0)
  15755. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  15756. if (doubleProto >= 0)
  15757. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  15758. };
  15759. pp$9.checkYieldAwaitInDefaultParams = function() {
  15760. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  15761. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  15762. if (this.awaitPos)
  15763. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  15764. };
  15765. pp$9.isSimpleAssignTarget = function(expr) {
  15766. if (expr.type === "ParenthesizedExpression")
  15767. { return this.isSimpleAssignTarget(expr.expression) }
  15768. return expr.type === "Identifier" || expr.type === "MemberExpression"
  15769. };
  15770. var pp$8 = Parser.prototype;
  15771. // ### Statement parsing
  15772. // Parse a program. Initializes the parser, reads any number of
  15773. // statements, and wraps them in a Program node. Optionally takes a
  15774. // `program` argument. If present, the statements will be appended
  15775. // to its body instead of creating a new node.
  15776. pp$8.parseTopLevel = function(node) {
  15777. var exports = Object.create(null);
  15778. if (!node.body) { node.body = []; }
  15779. while (this.type !== types$1.eof) {
  15780. var stmt = this.parseStatement(null, true, exports);
  15781. node.body.push(stmt);
  15782. }
  15783. if (this.inModule)
  15784. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  15785. {
  15786. var name = list[i];
  15787. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  15788. } }
  15789. this.adaptDirectivePrologue(node.body);
  15790. this.next();
  15791. node.sourceType = this.options.sourceType;
  15792. return this.finishNode(node, "Program")
  15793. };
  15794. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  15795. pp$8.isLet = function(context) {
  15796. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  15797. skipWhiteSpace.lastIndex = this.pos;
  15798. var skip = skipWhiteSpace.exec(this.input);
  15799. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15800. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  15801. // Statement) is allowed here. If context is not empty then only a Statement
  15802. // is allowed. However, `let [` is an explicit negative lookahead for
  15803. // ExpressionStatement, so special-case it first.
  15804. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  15805. if (context) { return false }
  15806. if (nextCh === 123) { return true } // '{'
  15807. if (isIdentifierStart(nextCh, true)) {
  15808. var pos = next + 1;
  15809. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  15810. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  15811. var ident = this.input.slice(next, pos);
  15812. if (!keywordRelationalOperator.test(ident)) { return true }
  15813. }
  15814. return false
  15815. };
  15816. // check 'async [no LineTerminator here] function'
  15817. // - 'async /*foo*/ function' is OK.
  15818. // - 'async /*\n*/ function' is invalid.
  15819. pp$8.isAsyncFunction = function() {
  15820. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  15821. { return false }
  15822. skipWhiteSpace.lastIndex = this.pos;
  15823. var skip = skipWhiteSpace.exec(this.input);
  15824. var next = this.pos + skip[0].length, after;
  15825. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  15826. this.input.slice(next, next + 8) === "function" &&
  15827. (next + 8 === this.input.length ||
  15828. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  15829. };
  15830. // Parse a single statement.
  15831. //
  15832. // If expecting a statement and finding a slash operator, parse a
  15833. // regular expression literal. This is to handle cases like
  15834. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  15835. // does not help.
  15836. pp$8.parseStatement = function(context, topLevel, exports) {
  15837. var starttype = this.type, node = this.startNode(), kind;
  15838. if (this.isLet(context)) {
  15839. starttype = types$1._var;
  15840. kind = "let";
  15841. }
  15842. // Most types of statements are recognized by the keyword they
  15843. // start with. Many are trivial to parse, some require a bit of
  15844. // complexity.
  15845. switch (starttype) {
  15846. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  15847. case types$1._debugger: return this.parseDebuggerStatement(node)
  15848. case types$1._do: return this.parseDoStatement(node)
  15849. case types$1._for: return this.parseForStatement(node)
  15850. case types$1._function:
  15851. // Function as sole body of either an if statement or a labeled statement
  15852. // works, but not when it is part of a labeled statement that is the sole
  15853. // body of an if statement.
  15854. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  15855. return this.parseFunctionStatement(node, false, !context)
  15856. case types$1._class:
  15857. if (context) { this.unexpected(); }
  15858. return this.parseClass(node, true)
  15859. case types$1._if: return this.parseIfStatement(node)
  15860. case types$1._return: return this.parseReturnStatement(node)
  15861. case types$1._switch: return this.parseSwitchStatement(node)
  15862. case types$1._throw: return this.parseThrowStatement(node)
  15863. case types$1._try: return this.parseTryStatement(node)
  15864. case types$1._const: case types$1._var:
  15865. kind = kind || this.value;
  15866. if (context && kind !== "var") { this.unexpected(); }
  15867. return this.parseVarStatement(node, kind)
  15868. case types$1._while: return this.parseWhileStatement(node)
  15869. case types$1._with: return this.parseWithStatement(node)
  15870. case types$1.braceL: return this.parseBlock(true, node)
  15871. case types$1.semi: return this.parseEmptyStatement(node)
  15872. case types$1._export:
  15873. case types$1._import:
  15874. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  15875. skipWhiteSpace.lastIndex = this.pos;
  15876. var skip = skipWhiteSpace.exec(this.input);
  15877. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15878. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  15879. { return this.parseExpressionStatement(node, this.parseExpression()) }
  15880. }
  15881. if (!this.options.allowImportExportEverywhere) {
  15882. if (!topLevel)
  15883. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  15884. if (!this.inModule)
  15885. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  15886. }
  15887. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  15888. // If the statement does not start with a statement keyword or a
  15889. // brace, it's an ExpressionStatement or LabeledStatement. We
  15890. // simply start parsing an expression, and afterwards, if the
  15891. // next token is a colon and the expression was a simple
  15892. // Identifier node, we switch to interpreting it as a label.
  15893. default:
  15894. if (this.isAsyncFunction()) {
  15895. if (context) { this.unexpected(); }
  15896. this.next();
  15897. return this.parseFunctionStatement(node, true, !context)
  15898. }
  15899. var maybeName = this.value, expr = this.parseExpression();
  15900. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  15901. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  15902. else { return this.parseExpressionStatement(node, expr) }
  15903. }
  15904. };
  15905. pp$8.parseBreakContinueStatement = function(node, keyword) {
  15906. var isBreak = keyword === "break";
  15907. this.next();
  15908. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  15909. else if (this.type !== types$1.name) { this.unexpected(); }
  15910. else {
  15911. node.label = this.parseIdent();
  15912. this.semicolon();
  15913. }
  15914. // Verify that there is an actual destination to break or
  15915. // continue to.
  15916. var i = 0;
  15917. for (; i < this.labels.length; ++i) {
  15918. var lab = this.labels[i];
  15919. if (node.label == null || lab.name === node.label.name) {
  15920. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  15921. if (node.label && isBreak) { break }
  15922. }
  15923. }
  15924. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  15925. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  15926. };
  15927. pp$8.parseDebuggerStatement = function(node) {
  15928. this.next();
  15929. this.semicolon();
  15930. return this.finishNode(node, "DebuggerStatement")
  15931. };
  15932. pp$8.parseDoStatement = function(node) {
  15933. this.next();
  15934. this.labels.push(loopLabel);
  15935. node.body = this.parseStatement("do");
  15936. this.labels.pop();
  15937. this.expect(types$1._while);
  15938. node.test = this.parseParenExpression();
  15939. if (this.options.ecmaVersion >= 6)
  15940. { this.eat(types$1.semi); }
  15941. else
  15942. { this.semicolon(); }
  15943. return this.finishNode(node, "DoWhileStatement")
  15944. };
  15945. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  15946. // loop is non-trivial. Basically, we have to parse the init `var`
  15947. // statement or expression, disallowing the `in` operator (see
  15948. // the second parameter to `parseExpression`), and then check
  15949. // whether the next token is `in` or `of`. When there is no init
  15950. // part (semicolon immediately after the opening parenthesis), it
  15951. // is a regular `for` loop.
  15952. pp$8.parseForStatement = function(node) {
  15953. this.next();
  15954. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  15955. this.labels.push(loopLabel);
  15956. this.enterScope(0);
  15957. this.expect(types$1.parenL);
  15958. if (this.type === types$1.semi) {
  15959. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15960. return this.parseFor(node, null)
  15961. }
  15962. var isLet = this.isLet();
  15963. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  15964. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  15965. this.next();
  15966. this.parseVar(init$1, true, kind);
  15967. this.finishNode(init$1, "VariableDeclaration");
  15968. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  15969. if (this.options.ecmaVersion >= 9) {
  15970. if (this.type === types$1._in) {
  15971. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15972. } else { node.await = awaitAt > -1; }
  15973. }
  15974. return this.parseForIn(node, init$1)
  15975. }
  15976. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15977. return this.parseFor(node, init$1)
  15978. }
  15979. var startsWithLet = this.isContextual("let"), isForOf = false;
  15980. var refDestructuringErrors = new DestructuringErrors;
  15981. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  15982. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  15983. if (this.options.ecmaVersion >= 9) {
  15984. if (this.type === types$1._in) {
  15985. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15986. } else { node.await = awaitAt > -1; }
  15987. }
  15988. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  15989. this.toAssignable(init, false, refDestructuringErrors);
  15990. this.checkLValPattern(init);
  15991. return this.parseForIn(node, init)
  15992. } else {
  15993. this.checkExpressionErrors(refDestructuringErrors, true);
  15994. }
  15995. if (awaitAt > -1) { this.unexpected(awaitAt); }
  15996. return this.parseFor(node, init)
  15997. };
  15998. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  15999. this.next();
  16000. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  16001. };
  16002. pp$8.parseIfStatement = function(node) {
  16003. this.next();
  16004. node.test = this.parseParenExpression();
  16005. // allow function declarations in branches, but only in non-strict mode
  16006. node.consequent = this.parseStatement("if");
  16007. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  16008. return this.finishNode(node, "IfStatement")
  16009. };
  16010. pp$8.parseReturnStatement = function(node) {
  16011. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  16012. { this.raise(this.start, "'return' outside of function"); }
  16013. this.next();
  16014. // In `return` (and `break`/`continue`), the keywords with
  16015. // optional arguments, we eagerly look for a semicolon or the
  16016. // possibility to insert one.
  16017. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  16018. else { node.argument = this.parseExpression(); this.semicolon(); }
  16019. return this.finishNode(node, "ReturnStatement")
  16020. };
  16021. pp$8.parseSwitchStatement = function(node) {
  16022. this.next();
  16023. node.discriminant = this.parseParenExpression();
  16024. node.cases = [];
  16025. this.expect(types$1.braceL);
  16026. this.labels.push(switchLabel);
  16027. this.enterScope(0);
  16028. // Statements under must be grouped (by label) in SwitchCase
  16029. // nodes. `cur` is used to keep the node that we are currently
  16030. // adding statements to.
  16031. var cur;
  16032. for (var sawDefault = false; this.type !== types$1.braceR;) {
  16033. if (this.type === types$1._case || this.type === types$1._default) {
  16034. var isCase = this.type === types$1._case;
  16035. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16036. node.cases.push(cur = this.startNode());
  16037. cur.consequent = [];
  16038. this.next();
  16039. if (isCase) {
  16040. cur.test = this.parseExpression();
  16041. } else {
  16042. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  16043. sawDefault = true;
  16044. cur.test = null;
  16045. }
  16046. this.expect(types$1.colon);
  16047. } else {
  16048. if (!cur) { this.unexpected(); }
  16049. cur.consequent.push(this.parseStatement(null));
  16050. }
  16051. }
  16052. this.exitScope();
  16053. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16054. this.next(); // Closing brace
  16055. this.labels.pop();
  16056. return this.finishNode(node, "SwitchStatement")
  16057. };
  16058. pp$8.parseThrowStatement = function(node) {
  16059. this.next();
  16060. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  16061. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  16062. node.argument = this.parseExpression();
  16063. this.semicolon();
  16064. return this.finishNode(node, "ThrowStatement")
  16065. };
  16066. // Reused empty array added for node fields that are always empty.
  16067. var empty$1 = [];
  16068. pp$8.parseTryStatement = function(node) {
  16069. this.next();
  16070. node.block = this.parseBlock();
  16071. node.handler = null;
  16072. if (this.type === types$1._catch) {
  16073. var clause = this.startNode();
  16074. this.next();
  16075. if (this.eat(types$1.parenL)) {
  16076. clause.param = this.parseBindingAtom();
  16077. var simple = clause.param.type === "Identifier";
  16078. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  16079. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  16080. this.expect(types$1.parenR);
  16081. } else {
  16082. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  16083. clause.param = null;
  16084. this.enterScope(0);
  16085. }
  16086. clause.body = this.parseBlock(false);
  16087. this.exitScope();
  16088. node.handler = this.finishNode(clause, "CatchClause");
  16089. }
  16090. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  16091. if (!node.handler && !node.finalizer)
  16092. { this.raise(node.start, "Missing catch or finally clause"); }
  16093. return this.finishNode(node, "TryStatement")
  16094. };
  16095. pp$8.parseVarStatement = function(node, kind) {
  16096. this.next();
  16097. this.parseVar(node, false, kind);
  16098. this.semicolon();
  16099. return this.finishNode(node, "VariableDeclaration")
  16100. };
  16101. pp$8.parseWhileStatement = function(node) {
  16102. this.next();
  16103. node.test = this.parseParenExpression();
  16104. this.labels.push(loopLabel);
  16105. node.body = this.parseStatement("while");
  16106. this.labels.pop();
  16107. return this.finishNode(node, "WhileStatement")
  16108. };
  16109. pp$8.parseWithStatement = function(node) {
  16110. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  16111. this.next();
  16112. node.object = this.parseParenExpression();
  16113. node.body = this.parseStatement("with");
  16114. return this.finishNode(node, "WithStatement")
  16115. };
  16116. pp$8.parseEmptyStatement = function(node) {
  16117. this.next();
  16118. return this.finishNode(node, "EmptyStatement")
  16119. };
  16120. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  16121. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  16122. {
  16123. var label = list[i$1];
  16124. if (label.name === maybeName)
  16125. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  16126. } }
  16127. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  16128. for (var i = this.labels.length - 1; i >= 0; i--) {
  16129. var label$1 = this.labels[i];
  16130. if (label$1.statementStart === node.start) {
  16131. // Update information about previous labels on this node
  16132. label$1.statementStart = this.start;
  16133. label$1.kind = kind;
  16134. } else { break }
  16135. }
  16136. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  16137. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  16138. this.labels.pop();
  16139. node.label = expr;
  16140. return this.finishNode(node, "LabeledStatement")
  16141. };
  16142. pp$8.parseExpressionStatement = function(node, expr) {
  16143. node.expression = expr;
  16144. this.semicolon();
  16145. return this.finishNode(node, "ExpressionStatement")
  16146. };
  16147. // Parse a semicolon-enclosed block of statements, handling `"use
  16148. // strict"` declarations when `allowStrict` is true (used for
  16149. // function bodies).
  16150. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  16151. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  16152. if ( node === void 0 ) node = this.startNode();
  16153. node.body = [];
  16154. this.expect(types$1.braceL);
  16155. if (createNewLexicalScope) { this.enterScope(0); }
  16156. while (this.type !== types$1.braceR) {
  16157. var stmt = this.parseStatement(null);
  16158. node.body.push(stmt);
  16159. }
  16160. if (exitStrict) { this.strict = false; }
  16161. this.next();
  16162. if (createNewLexicalScope) { this.exitScope(); }
  16163. return this.finishNode(node, "BlockStatement")
  16164. };
  16165. // Parse a regular `for` loop. The disambiguation code in
  16166. // `parseStatement` will already have parsed the init statement or
  16167. // expression.
  16168. pp$8.parseFor = function(node, init) {
  16169. node.init = init;
  16170. this.expect(types$1.semi);
  16171. node.test = this.type === types$1.semi ? null : this.parseExpression();
  16172. this.expect(types$1.semi);
  16173. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  16174. this.expect(types$1.parenR);
  16175. node.body = this.parseStatement("for");
  16176. this.exitScope();
  16177. this.labels.pop();
  16178. return this.finishNode(node, "ForStatement")
  16179. };
  16180. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  16181. // same from parser's perspective.
  16182. pp$8.parseForIn = function(node, init) {
  16183. var isForIn = this.type === types$1._in;
  16184. this.next();
  16185. if (
  16186. init.type === "VariableDeclaration" &&
  16187. init.declarations[0].init != null &&
  16188. (
  16189. !isForIn ||
  16190. this.options.ecmaVersion < 8 ||
  16191. this.strict ||
  16192. init.kind !== "var" ||
  16193. init.declarations[0].id.type !== "Identifier"
  16194. )
  16195. ) {
  16196. this.raise(
  16197. init.start,
  16198. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  16199. );
  16200. }
  16201. node.left = init;
  16202. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  16203. this.expect(types$1.parenR);
  16204. node.body = this.parseStatement("for");
  16205. this.exitScope();
  16206. this.labels.pop();
  16207. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  16208. };
  16209. // Parse a list of variable declarations.
  16210. pp$8.parseVar = function(node, isFor, kind) {
  16211. node.declarations = [];
  16212. node.kind = kind;
  16213. for (;;) {
  16214. var decl = this.startNode();
  16215. this.parseVarId(decl, kind);
  16216. if (this.eat(types$1.eq)) {
  16217. decl.init = this.parseMaybeAssign(isFor);
  16218. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  16219. this.unexpected();
  16220. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  16221. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  16222. } else {
  16223. decl.init = null;
  16224. }
  16225. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  16226. if (!this.eat(types$1.comma)) { break }
  16227. }
  16228. return node
  16229. };
  16230. pp$8.parseVarId = function(decl, kind) {
  16231. decl.id = this.parseBindingAtom();
  16232. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  16233. };
  16234. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  16235. // Parse a function declaration or literal (depending on the
  16236. // `statement & FUNC_STATEMENT`).
  16237. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  16238. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  16239. this.initFunction(node);
  16240. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  16241. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  16242. { this.unexpected(); }
  16243. node.generator = this.eat(types$1.star);
  16244. }
  16245. if (this.options.ecmaVersion >= 8)
  16246. { node.async = !!isAsync; }
  16247. if (statement & FUNC_STATEMENT) {
  16248. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  16249. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  16250. // If it is a regular function declaration in sloppy mode, then it is
  16251. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  16252. // mode depends on properties of the current scope (see
  16253. // treatFunctionsAsVar).
  16254. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  16255. }
  16256. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  16257. this.yieldPos = 0;
  16258. this.awaitPos = 0;
  16259. this.awaitIdentPos = 0;
  16260. this.enterScope(functionFlags(node.async, node.generator));
  16261. if (!(statement & FUNC_STATEMENT))
  16262. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  16263. this.parseFunctionParams(node);
  16264. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  16265. this.yieldPos = oldYieldPos;
  16266. this.awaitPos = oldAwaitPos;
  16267. this.awaitIdentPos = oldAwaitIdentPos;
  16268. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  16269. };
  16270. pp$8.parseFunctionParams = function(node) {
  16271. this.expect(types$1.parenL);
  16272. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  16273. this.checkYieldAwaitInDefaultParams();
  16274. };
  16275. // Parse a class declaration or literal (depending on the
  16276. // `isStatement` parameter).
  16277. pp$8.parseClass = function(node, isStatement) {
  16278. this.next();
  16279. // ecma-262 14.6 Class Definitions
  16280. // A class definition is always strict mode code.
  16281. var oldStrict = this.strict;
  16282. this.strict = true;
  16283. this.parseClassId(node, isStatement);
  16284. this.parseClassSuper(node);
  16285. var privateNameMap = this.enterClassBody();
  16286. var classBody = this.startNode();
  16287. var hadConstructor = false;
  16288. classBody.body = [];
  16289. this.expect(types$1.braceL);
  16290. while (this.type !== types$1.braceR) {
  16291. var element = this.parseClassElement(node.superClass !== null);
  16292. if (element) {
  16293. classBody.body.push(element);
  16294. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  16295. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  16296. hadConstructor = true;
  16297. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  16298. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  16299. }
  16300. }
  16301. }
  16302. this.strict = oldStrict;
  16303. this.next();
  16304. node.body = this.finishNode(classBody, "ClassBody");
  16305. this.exitClassBody();
  16306. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  16307. };
  16308. pp$8.parseClassElement = function(constructorAllowsSuper) {
  16309. if (this.eat(types$1.semi)) { return null }
  16310. var ecmaVersion = this.options.ecmaVersion;
  16311. var node = this.startNode();
  16312. var keyName = "";
  16313. var isGenerator = false;
  16314. var isAsync = false;
  16315. var kind = "method";
  16316. var isStatic = false;
  16317. if (this.eatContextual("static")) {
  16318. // Parse static init block
  16319. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  16320. this.parseClassStaticBlock(node);
  16321. return node
  16322. }
  16323. if (this.isClassElementNameStart() || this.type === types$1.star) {
  16324. isStatic = true;
  16325. } else {
  16326. keyName = "static";
  16327. }
  16328. }
  16329. node.static = isStatic;
  16330. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  16331. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  16332. isAsync = true;
  16333. } else {
  16334. keyName = "async";
  16335. }
  16336. }
  16337. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  16338. isGenerator = true;
  16339. }
  16340. if (!keyName && !isAsync && !isGenerator) {
  16341. var lastValue = this.value;
  16342. if (this.eatContextual("get") || this.eatContextual("set")) {
  16343. if (this.isClassElementNameStart()) {
  16344. kind = lastValue;
  16345. } else {
  16346. keyName = lastValue;
  16347. }
  16348. }
  16349. }
  16350. // Parse element name
  16351. if (keyName) {
  16352. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  16353. // The last token is any of those. Make it the element name.
  16354. node.computed = false;
  16355. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  16356. node.key.name = keyName;
  16357. this.finishNode(node.key, "Identifier");
  16358. } else {
  16359. this.parseClassElementName(node);
  16360. }
  16361. // Parse element value
  16362. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  16363. var isConstructor = !node.static && checkKeyName(node, "constructor");
  16364. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  16365. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  16366. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  16367. node.kind = isConstructor ? "constructor" : kind;
  16368. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  16369. } else {
  16370. this.parseClassField(node);
  16371. }
  16372. return node
  16373. };
  16374. pp$8.isClassElementNameStart = function() {
  16375. return (
  16376. this.type === types$1.name ||
  16377. this.type === types$1.privateId ||
  16378. this.type === types$1.num ||
  16379. this.type === types$1.string ||
  16380. this.type === types$1.bracketL ||
  16381. this.type.keyword
  16382. )
  16383. };
  16384. pp$8.parseClassElementName = function(element) {
  16385. if (this.type === types$1.privateId) {
  16386. if (this.value === "constructor") {
  16387. this.raise(this.start, "Classes can't have an element named '#constructor'");
  16388. }
  16389. element.computed = false;
  16390. element.key = this.parsePrivateIdent();
  16391. } else {
  16392. this.parsePropertyName(element);
  16393. }
  16394. };
  16395. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  16396. // Check key and flags
  16397. var key = method.key;
  16398. if (method.kind === "constructor") {
  16399. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  16400. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  16401. } else if (method.static && checkKeyName(method, "prototype")) {
  16402. this.raise(key.start, "Classes may not have a static property named prototype");
  16403. }
  16404. // Parse value
  16405. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  16406. // Check value
  16407. if (method.kind === "get" && value.params.length !== 0)
  16408. { this.raiseRecoverable(value.start, "getter should have no params"); }
  16409. if (method.kind === "set" && value.params.length !== 1)
  16410. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  16411. if (method.kind === "set" && value.params[0].type === "RestElement")
  16412. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  16413. return this.finishNode(method, "MethodDefinition")
  16414. };
  16415. pp$8.parseClassField = function(field) {
  16416. if (checkKeyName(field, "constructor")) {
  16417. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  16418. } else if (field.static && checkKeyName(field, "prototype")) {
  16419. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  16420. }
  16421. if (this.eat(types$1.eq)) {
  16422. // To raise SyntaxError if 'arguments' exists in the initializer.
  16423. var scope = this.currentThisScope();
  16424. var inClassFieldInit = scope.inClassFieldInit;
  16425. scope.inClassFieldInit = true;
  16426. field.value = this.parseMaybeAssign();
  16427. scope.inClassFieldInit = inClassFieldInit;
  16428. } else {
  16429. field.value = null;
  16430. }
  16431. this.semicolon();
  16432. return this.finishNode(field, "PropertyDefinition")
  16433. };
  16434. pp$8.parseClassStaticBlock = function(node) {
  16435. node.body = [];
  16436. var oldLabels = this.labels;
  16437. this.labels = [];
  16438. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  16439. while (this.type !== types$1.braceR) {
  16440. var stmt = this.parseStatement(null);
  16441. node.body.push(stmt);
  16442. }
  16443. this.next();
  16444. this.exitScope();
  16445. this.labels = oldLabels;
  16446. return this.finishNode(node, "StaticBlock")
  16447. };
  16448. pp$8.parseClassId = function(node, isStatement) {
  16449. if (this.type === types$1.name) {
  16450. node.id = this.parseIdent();
  16451. if (isStatement)
  16452. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  16453. } else {
  16454. if (isStatement === true)
  16455. { this.unexpected(); }
  16456. node.id = null;
  16457. }
  16458. };
  16459. pp$8.parseClassSuper = function(node) {
  16460. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  16461. };
  16462. pp$8.enterClassBody = function() {
  16463. var element = {declared: Object.create(null), used: []};
  16464. this.privateNameStack.push(element);
  16465. return element.declared
  16466. };
  16467. pp$8.exitClassBody = function() {
  16468. var ref = this.privateNameStack.pop();
  16469. var declared = ref.declared;
  16470. var used = ref.used;
  16471. var len = this.privateNameStack.length;
  16472. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  16473. for (var i = 0; i < used.length; ++i) {
  16474. var id = used[i];
  16475. if (!hasOwn(declared, id.name)) {
  16476. if (parent) {
  16477. parent.used.push(id);
  16478. } else {
  16479. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  16480. }
  16481. }
  16482. }
  16483. };
  16484. function isPrivateNameConflicted(privateNameMap, element) {
  16485. var name = element.key.name;
  16486. var curr = privateNameMap[name];
  16487. var next = "true";
  16488. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  16489. next = (element.static ? "s" : "i") + element.kind;
  16490. }
  16491. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  16492. if (
  16493. curr === "iget" && next === "iset" ||
  16494. curr === "iset" && next === "iget" ||
  16495. curr === "sget" && next === "sset" ||
  16496. curr === "sset" && next === "sget"
  16497. ) {
  16498. privateNameMap[name] = "true";
  16499. return false
  16500. } else if (!curr) {
  16501. privateNameMap[name] = next;
  16502. return false
  16503. } else {
  16504. return true
  16505. }
  16506. }
  16507. function checkKeyName(node, name) {
  16508. var computed = node.computed;
  16509. var key = node.key;
  16510. return !computed && (
  16511. key.type === "Identifier" && key.name === name ||
  16512. key.type === "Literal" && key.value === name
  16513. )
  16514. }
  16515. // Parses module export declaration.
  16516. pp$8.parseExport = function(node, exports) {
  16517. this.next();
  16518. // export * from '...'
  16519. if (this.eat(types$1.star)) {
  16520. if (this.options.ecmaVersion >= 11) {
  16521. if (this.eatContextual("as")) {
  16522. node.exported = this.parseModuleExportName();
  16523. this.checkExport(exports, node.exported, this.lastTokStart);
  16524. } else {
  16525. node.exported = null;
  16526. }
  16527. }
  16528. this.expectContextual("from");
  16529. if (this.type !== types$1.string) { this.unexpected(); }
  16530. node.source = this.parseExprAtom();
  16531. this.semicolon();
  16532. return this.finishNode(node, "ExportAllDeclaration")
  16533. }
  16534. if (this.eat(types$1._default)) { // export default ...
  16535. this.checkExport(exports, "default", this.lastTokStart);
  16536. var isAsync;
  16537. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  16538. var fNode = this.startNode();
  16539. this.next();
  16540. if (isAsync) { this.next(); }
  16541. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  16542. } else if (this.type === types$1._class) {
  16543. var cNode = this.startNode();
  16544. node.declaration = this.parseClass(cNode, "nullableID");
  16545. } else {
  16546. node.declaration = this.parseMaybeAssign();
  16547. this.semicolon();
  16548. }
  16549. return this.finishNode(node, "ExportDefaultDeclaration")
  16550. }
  16551. // export var|const|let|function|class ...
  16552. if (this.shouldParseExportStatement()) {
  16553. node.declaration = this.parseStatement(null);
  16554. if (node.declaration.type === "VariableDeclaration")
  16555. { this.checkVariableExport(exports, node.declaration.declarations); }
  16556. else
  16557. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  16558. node.specifiers = [];
  16559. node.source = null;
  16560. } else { // export { x, y as z } [from '...']
  16561. node.declaration = null;
  16562. node.specifiers = this.parseExportSpecifiers(exports);
  16563. if (this.eatContextual("from")) {
  16564. if (this.type !== types$1.string) { this.unexpected(); }
  16565. node.source = this.parseExprAtom();
  16566. } else {
  16567. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  16568. // check for keywords used as local names
  16569. var spec = list[i];
  16570. this.checkUnreserved(spec.local);
  16571. // check if export is defined
  16572. this.checkLocalExport(spec.local);
  16573. if (spec.local.type === "Literal") {
  16574. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  16575. }
  16576. }
  16577. node.source = null;
  16578. }
  16579. this.semicolon();
  16580. }
  16581. return this.finishNode(node, "ExportNamedDeclaration")
  16582. };
  16583. pp$8.checkExport = function(exports, name, pos) {
  16584. if (!exports) { return }
  16585. if (typeof name !== "string")
  16586. { name = name.type === "Identifier" ? name.name : name.value; }
  16587. if (hasOwn(exports, name))
  16588. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  16589. exports[name] = true;
  16590. };
  16591. pp$8.checkPatternExport = function(exports, pat) {
  16592. var type = pat.type;
  16593. if (type === "Identifier")
  16594. { this.checkExport(exports, pat, pat.start); }
  16595. else if (type === "ObjectPattern")
  16596. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  16597. {
  16598. var prop = list[i];
  16599. this.checkPatternExport(exports, prop);
  16600. } }
  16601. else if (type === "ArrayPattern")
  16602. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  16603. var elt = list$1[i$1];
  16604. if (elt) { this.checkPatternExport(exports, elt); }
  16605. } }
  16606. else if (type === "Property")
  16607. { this.checkPatternExport(exports, pat.value); }
  16608. else if (type === "AssignmentPattern")
  16609. { this.checkPatternExport(exports, pat.left); }
  16610. else if (type === "RestElement")
  16611. { this.checkPatternExport(exports, pat.argument); }
  16612. else if (type === "ParenthesizedExpression")
  16613. { this.checkPatternExport(exports, pat.expression); }
  16614. };
  16615. pp$8.checkVariableExport = function(exports, decls) {
  16616. if (!exports) { return }
  16617. for (var i = 0, list = decls; i < list.length; i += 1)
  16618. {
  16619. var decl = list[i];
  16620. this.checkPatternExport(exports, decl.id);
  16621. }
  16622. };
  16623. pp$8.shouldParseExportStatement = function() {
  16624. return this.type.keyword === "var" ||
  16625. this.type.keyword === "const" ||
  16626. this.type.keyword === "class" ||
  16627. this.type.keyword === "function" ||
  16628. this.isLet() ||
  16629. this.isAsyncFunction()
  16630. };
  16631. // Parses a comma-separated list of module exports.
  16632. pp$8.parseExportSpecifiers = function(exports) {
  16633. var nodes = [], first = true;
  16634. // export { x, y as z } [from '...']
  16635. this.expect(types$1.braceL);
  16636. while (!this.eat(types$1.braceR)) {
  16637. if (!first) {
  16638. this.expect(types$1.comma);
  16639. if (this.afterTrailingComma(types$1.braceR)) { break }
  16640. } else { first = false; }
  16641. var node = this.startNode();
  16642. node.local = this.parseModuleExportName();
  16643. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  16644. this.checkExport(
  16645. exports,
  16646. node.exported,
  16647. node.exported.start
  16648. );
  16649. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16650. }
  16651. return nodes
  16652. };
  16653. // Parses import declaration.
  16654. pp$8.parseImport = function(node) {
  16655. this.next();
  16656. // import '...'
  16657. if (this.type === types$1.string) {
  16658. node.specifiers = empty$1;
  16659. node.source = this.parseExprAtom();
  16660. } else {
  16661. node.specifiers = this.parseImportSpecifiers();
  16662. this.expectContextual("from");
  16663. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  16664. }
  16665. this.semicolon();
  16666. return this.finishNode(node, "ImportDeclaration")
  16667. };
  16668. // Parses a comma-separated list of module imports.
  16669. pp$8.parseImportSpecifiers = function() {
  16670. var nodes = [], first = true;
  16671. if (this.type === types$1.name) {
  16672. // import defaultObj, { x, y as z } from '...'
  16673. var node = this.startNode();
  16674. node.local = this.parseIdent();
  16675. this.checkLValSimple(node.local, BIND_LEXICAL);
  16676. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  16677. if (!this.eat(types$1.comma)) { return nodes }
  16678. }
  16679. if (this.type === types$1.star) {
  16680. var node$1 = this.startNode();
  16681. this.next();
  16682. this.expectContextual("as");
  16683. node$1.local = this.parseIdent();
  16684. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  16685. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  16686. return nodes
  16687. }
  16688. this.expect(types$1.braceL);
  16689. while (!this.eat(types$1.braceR)) {
  16690. if (!first) {
  16691. this.expect(types$1.comma);
  16692. if (this.afterTrailingComma(types$1.braceR)) { break }
  16693. } else { first = false; }
  16694. var node$2 = this.startNode();
  16695. node$2.imported = this.parseModuleExportName();
  16696. if (this.eatContextual("as")) {
  16697. node$2.local = this.parseIdent();
  16698. } else {
  16699. this.checkUnreserved(node$2.imported);
  16700. node$2.local = node$2.imported;
  16701. }
  16702. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  16703. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  16704. }
  16705. return nodes
  16706. };
  16707. pp$8.parseModuleExportName = function() {
  16708. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  16709. var stringLiteral = this.parseLiteral(this.value);
  16710. if (loneSurrogate.test(stringLiteral.value)) {
  16711. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  16712. }
  16713. return stringLiteral
  16714. }
  16715. return this.parseIdent(true)
  16716. };
  16717. // Set `ExpressionStatement#directive` property for directive prologues.
  16718. pp$8.adaptDirectivePrologue = function(statements) {
  16719. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  16720. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  16721. }
  16722. };
  16723. pp$8.isDirectiveCandidate = function(statement) {
  16724. return (
  16725. statement.type === "ExpressionStatement" &&
  16726. statement.expression.type === "Literal" &&
  16727. typeof statement.expression.value === "string" &&
  16728. // Reject parenthesized strings.
  16729. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  16730. )
  16731. };
  16732. var pp$7 = Parser.prototype;
  16733. // Convert existing expression atom to assignable pattern
  16734. // if possible.
  16735. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  16736. if (this.options.ecmaVersion >= 6 && node) {
  16737. switch (node.type) {
  16738. case "Identifier":
  16739. if (this.inAsync && node.name === "await")
  16740. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  16741. break
  16742. case "ObjectPattern":
  16743. case "ArrayPattern":
  16744. case "AssignmentPattern":
  16745. case "RestElement":
  16746. break
  16747. case "ObjectExpression":
  16748. node.type = "ObjectPattern";
  16749. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16750. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  16751. var prop = list[i];
  16752. this.toAssignable(prop, isBinding);
  16753. // Early error:
  16754. // AssignmentRestProperty[Yield, Await] :
  16755. // `...` DestructuringAssignmentTarget[Yield, Await]
  16756. //
  16757. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  16758. if (
  16759. prop.type === "RestElement" &&
  16760. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  16761. ) {
  16762. this.raise(prop.argument.start, "Unexpected token");
  16763. }
  16764. }
  16765. break
  16766. case "Property":
  16767. // AssignmentProperty has type === "Property"
  16768. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  16769. this.toAssignable(node.value, isBinding);
  16770. break
  16771. case "ArrayExpression":
  16772. node.type = "ArrayPattern";
  16773. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16774. this.toAssignableList(node.elements, isBinding);
  16775. break
  16776. case "SpreadElement":
  16777. node.type = "RestElement";
  16778. this.toAssignable(node.argument, isBinding);
  16779. if (node.argument.type === "AssignmentPattern")
  16780. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  16781. break
  16782. case "AssignmentExpression":
  16783. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  16784. node.type = "AssignmentPattern";
  16785. delete node.operator;
  16786. this.toAssignable(node.left, isBinding);
  16787. break
  16788. case "ParenthesizedExpression":
  16789. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  16790. break
  16791. case "ChainExpression":
  16792. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  16793. break
  16794. case "MemberExpression":
  16795. if (!isBinding) { break }
  16796. default:
  16797. this.raise(node.start, "Assigning to rvalue");
  16798. }
  16799. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16800. return node
  16801. };
  16802. // Convert list of expression atoms to binding list.
  16803. pp$7.toAssignableList = function(exprList, isBinding) {
  16804. var end = exprList.length;
  16805. for (var i = 0; i < end; i++) {
  16806. var elt = exprList[i];
  16807. if (elt) { this.toAssignable(elt, isBinding); }
  16808. }
  16809. if (end) {
  16810. var last = exprList[end - 1];
  16811. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  16812. { this.unexpected(last.argument.start); }
  16813. }
  16814. return exprList
  16815. };
  16816. // Parses spread element.
  16817. pp$7.parseSpread = function(refDestructuringErrors) {
  16818. var node = this.startNode();
  16819. this.next();
  16820. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  16821. return this.finishNode(node, "SpreadElement")
  16822. };
  16823. pp$7.parseRestBinding = function() {
  16824. var node = this.startNode();
  16825. this.next();
  16826. // RestElement inside of a function parameter must be an identifier
  16827. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  16828. { this.unexpected(); }
  16829. node.argument = this.parseBindingAtom();
  16830. return this.finishNode(node, "RestElement")
  16831. };
  16832. // Parses lvalue (assignable) atom.
  16833. pp$7.parseBindingAtom = function() {
  16834. if (this.options.ecmaVersion >= 6) {
  16835. switch (this.type) {
  16836. case types$1.bracketL:
  16837. var node = this.startNode();
  16838. this.next();
  16839. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  16840. return this.finishNode(node, "ArrayPattern")
  16841. case types$1.braceL:
  16842. return this.parseObj(true)
  16843. }
  16844. }
  16845. return this.parseIdent()
  16846. };
  16847. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  16848. var elts = [], first = true;
  16849. while (!this.eat(close)) {
  16850. if (first) { first = false; }
  16851. else { this.expect(types$1.comma); }
  16852. if (allowEmpty && this.type === types$1.comma) {
  16853. elts.push(null);
  16854. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  16855. break
  16856. } else if (this.type === types$1.ellipsis) {
  16857. var rest = this.parseRestBinding();
  16858. this.parseBindingListItem(rest);
  16859. elts.push(rest);
  16860. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  16861. this.expect(close);
  16862. break
  16863. } else {
  16864. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  16865. this.parseBindingListItem(elem);
  16866. elts.push(elem);
  16867. }
  16868. }
  16869. return elts
  16870. };
  16871. pp$7.parseBindingListItem = function(param) {
  16872. return param
  16873. };
  16874. // Parses assignment pattern around given atom if possible.
  16875. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  16876. left = left || this.parseBindingAtom();
  16877. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  16878. var node = this.startNodeAt(startPos, startLoc);
  16879. node.left = left;
  16880. node.right = this.parseMaybeAssign();
  16881. return this.finishNode(node, "AssignmentPattern")
  16882. };
  16883. // The following three functions all verify that a node is an lvalue —
  16884. // something that can be bound, or assigned to. In order to do so, they perform
  16885. // a variety of checks:
  16886. //
  16887. // - Check that none of the bound/assigned-to identifiers are reserved words.
  16888. // - Record name declarations for bindings in the appropriate scope.
  16889. // - Check duplicate argument names, if checkClashes is set.
  16890. //
  16891. // If a complex binding pattern is encountered (e.g., object and array
  16892. // destructuring), the entire pattern is recursively checked.
  16893. //
  16894. // There are three versions of checkLVal*() appropriate for different
  16895. // circumstances:
  16896. //
  16897. // - checkLValSimple() shall be used if the syntactic construct supports
  16898. // nothing other than identifiers and member expressions. Parenthesized
  16899. // expressions are also correctly handled. This is generally appropriate for
  16900. // constructs for which the spec says
  16901. //
  16902. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  16903. // > simple.
  16904. //
  16905. // It is also appropriate for checking if an identifier is valid and not
  16906. // defined elsewhere, like import declarations or function/class identifiers.
  16907. //
  16908. // Examples where this is used include:
  16909. // a += …;
  16910. // import a from '…';
  16911. // where a is the node to be checked.
  16912. //
  16913. // - checkLValPattern() shall be used if the syntactic construct supports
  16914. // anything checkLValSimple() supports, as well as object and array
  16915. // destructuring patterns. This is generally appropriate for constructs for
  16916. // which the spec says
  16917. //
  16918. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  16919. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  16920. // > simple.
  16921. //
  16922. // Examples where this is used include:
  16923. // (a = …);
  16924. // const a = …;
  16925. // try { … } catch (a) { … }
  16926. // where a is the node to be checked.
  16927. //
  16928. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  16929. // anything checkLValPattern() supports, as well as default assignment
  16930. // patterns, rest elements, and other constructs that may appear within an
  16931. // object or array destructuring pattern.
  16932. //
  16933. // As a special case, function parameters also use checkLValInnerPattern(),
  16934. // as they also support defaults and rest constructs.
  16935. //
  16936. // These functions deliberately support both assignment and binding constructs,
  16937. // as the logic for both is exceedingly similar. If the node is the target of
  16938. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  16939. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  16940. // BIND_LEXICAL.
  16941. //
  16942. // If the function is called with a non-BIND_NONE bindingType, then
  16943. // additionally a checkClashes object may be specified to allow checking for
  16944. // duplicate argument names. checkClashes is ignored if the provided construct
  16945. // is an assignment (i.e., bindingType is BIND_NONE).
  16946. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  16947. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  16948. var isBind = bindingType !== BIND_NONE;
  16949. switch (expr.type) {
  16950. case "Identifier":
  16951. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  16952. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  16953. if (isBind) {
  16954. if (bindingType === BIND_LEXICAL && expr.name === "let")
  16955. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  16956. if (checkClashes) {
  16957. if (hasOwn(checkClashes, expr.name))
  16958. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  16959. checkClashes[expr.name] = true;
  16960. }
  16961. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  16962. }
  16963. break
  16964. case "ChainExpression":
  16965. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  16966. break
  16967. case "MemberExpression":
  16968. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  16969. break
  16970. case "ParenthesizedExpression":
  16971. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  16972. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  16973. default:
  16974. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  16975. }
  16976. };
  16977. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  16978. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  16979. switch (expr.type) {
  16980. case "ObjectPattern":
  16981. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  16982. var prop = list[i];
  16983. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  16984. }
  16985. break
  16986. case "ArrayPattern":
  16987. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  16988. var elem = list$1[i$1];
  16989. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  16990. }
  16991. break
  16992. default:
  16993. this.checkLValSimple(expr, bindingType, checkClashes);
  16994. }
  16995. };
  16996. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  16997. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  16998. switch (expr.type) {
  16999. case "Property":
  17000. // AssignmentProperty has type === "Property"
  17001. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  17002. break
  17003. case "AssignmentPattern":
  17004. this.checkLValPattern(expr.left, bindingType, checkClashes);
  17005. break
  17006. case "RestElement":
  17007. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  17008. break
  17009. default:
  17010. this.checkLValPattern(expr, bindingType, checkClashes);
  17011. }
  17012. };
  17013. // The algorithm used to determine whether a regexp can appear at a
  17014. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  17015. this.token = token;
  17016. this.isExpr = !!isExpr;
  17017. this.preserveSpace = !!preserveSpace;
  17018. this.override = override;
  17019. this.generator = !!generator;
  17020. };
  17021. var types = {
  17022. b_stat: new TokContext("{", false),
  17023. b_expr: new TokContext("{", true),
  17024. b_tmpl: new TokContext("${", false),
  17025. p_stat: new TokContext("(", false),
  17026. p_expr: new TokContext("(", true),
  17027. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  17028. f_stat: new TokContext("function", false),
  17029. f_expr: new TokContext("function", true),
  17030. f_expr_gen: new TokContext("function", true, false, null, true),
  17031. f_gen: new TokContext("function", false, false, null, true)
  17032. };
  17033. var pp$6 = Parser.prototype;
  17034. pp$6.initialContext = function() {
  17035. return [types.b_stat]
  17036. };
  17037. pp$6.curContext = function() {
  17038. return this.context[this.context.length - 1]
  17039. };
  17040. pp$6.braceIsBlock = function(prevType) {
  17041. var parent = this.curContext();
  17042. if (parent === types.f_expr || parent === types.f_stat)
  17043. { return true }
  17044. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  17045. { return !parent.isExpr }
  17046. // The check for `tt.name && exprAllowed` detects whether we are
  17047. // after a `yield` or `of` construct. See the `updateContext` for
  17048. // `tt.name`.
  17049. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  17050. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  17051. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  17052. { return true }
  17053. if (prevType === types$1.braceL)
  17054. { return parent === types.b_stat }
  17055. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  17056. { return false }
  17057. return !this.exprAllowed
  17058. };
  17059. pp$6.inGeneratorContext = function() {
  17060. for (var i = this.context.length - 1; i >= 1; i--) {
  17061. var context = this.context[i];
  17062. if (context.token === "function")
  17063. { return context.generator }
  17064. }
  17065. return false
  17066. };
  17067. pp$6.updateContext = function(prevType) {
  17068. var update, type = this.type;
  17069. if (type.keyword && prevType === types$1.dot)
  17070. { this.exprAllowed = false; }
  17071. else if (update = type.updateContext)
  17072. { update.call(this, prevType); }
  17073. else
  17074. { this.exprAllowed = type.beforeExpr; }
  17075. };
  17076. // Used to handle egde case when token context could not be inferred correctly in tokenize phase
  17077. pp$6.overrideContext = function(tokenCtx) {
  17078. if (this.curContext() !== tokenCtx) {
  17079. this.context[this.context.length - 1] = tokenCtx;
  17080. }
  17081. };
  17082. // Token-specific context update code
  17083. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  17084. if (this.context.length === 1) {
  17085. this.exprAllowed = true;
  17086. return
  17087. }
  17088. var out = this.context.pop();
  17089. if (out === types.b_stat && this.curContext().token === "function") {
  17090. out = this.context.pop();
  17091. }
  17092. this.exprAllowed = !out.isExpr;
  17093. };
  17094. types$1.braceL.updateContext = function(prevType) {
  17095. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  17096. this.exprAllowed = true;
  17097. };
  17098. types$1.dollarBraceL.updateContext = function() {
  17099. this.context.push(types.b_tmpl);
  17100. this.exprAllowed = true;
  17101. };
  17102. types$1.parenL.updateContext = function(prevType) {
  17103. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  17104. this.context.push(statementParens ? types.p_stat : types.p_expr);
  17105. this.exprAllowed = true;
  17106. };
  17107. types$1.incDec.updateContext = function() {
  17108. // tokExprAllowed stays unchanged
  17109. };
  17110. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  17111. if (prevType.beforeExpr && prevType !== types$1._else &&
  17112. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  17113. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  17114. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  17115. { this.context.push(types.f_expr); }
  17116. else
  17117. { this.context.push(types.f_stat); }
  17118. this.exprAllowed = false;
  17119. };
  17120. types$1.backQuote.updateContext = function() {
  17121. if (this.curContext() === types.q_tmpl)
  17122. { this.context.pop(); }
  17123. else
  17124. { this.context.push(types.q_tmpl); }
  17125. this.exprAllowed = false;
  17126. };
  17127. types$1.star.updateContext = function(prevType) {
  17128. if (prevType === types$1._function) {
  17129. var index = this.context.length - 1;
  17130. if (this.context[index] === types.f_expr)
  17131. { this.context[index] = types.f_expr_gen; }
  17132. else
  17133. { this.context[index] = types.f_gen; }
  17134. }
  17135. this.exprAllowed = true;
  17136. };
  17137. types$1.name.updateContext = function(prevType) {
  17138. var allowed = false;
  17139. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  17140. if (this.value === "of" && !this.exprAllowed ||
  17141. this.value === "yield" && this.inGeneratorContext())
  17142. { allowed = true; }
  17143. }
  17144. this.exprAllowed = allowed;
  17145. };
  17146. // A recursive descent parser operates by defining functions for all
  17147. var pp$5 = Parser.prototype;
  17148. // Check if property name clashes with already added.
  17149. // Object/class getters and setters are not allowed to clash —
  17150. // either with each other or with an init property — and in
  17151. // strict mode, init properties are also not allowed to be repeated.
  17152. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  17153. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  17154. { return }
  17155. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  17156. { return }
  17157. var key = prop.key;
  17158. var name;
  17159. switch (key.type) {
  17160. case "Identifier": name = key.name; break
  17161. case "Literal": name = String(key.value); break
  17162. default: return
  17163. }
  17164. var kind = prop.kind;
  17165. if (this.options.ecmaVersion >= 6) {
  17166. if (name === "__proto__" && kind === "init") {
  17167. if (propHash.proto) {
  17168. if (refDestructuringErrors) {
  17169. if (refDestructuringErrors.doubleProto < 0) {
  17170. refDestructuringErrors.doubleProto = key.start;
  17171. }
  17172. } else {
  17173. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  17174. }
  17175. }
  17176. propHash.proto = true;
  17177. }
  17178. return
  17179. }
  17180. name = "$" + name;
  17181. var other = propHash[name];
  17182. if (other) {
  17183. var redefinition;
  17184. if (kind === "init") {
  17185. redefinition = this.strict && other.init || other.get || other.set;
  17186. } else {
  17187. redefinition = other.init || other[kind];
  17188. }
  17189. if (redefinition)
  17190. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  17191. } else {
  17192. other = propHash[name] = {
  17193. init: false,
  17194. get: false,
  17195. set: false
  17196. };
  17197. }
  17198. other[kind] = true;
  17199. };
  17200. // ### Expression parsing
  17201. // These nest, from the most general expression type at the top to
  17202. // 'atomic', nondivisible expression types at the bottom. Most of
  17203. // the functions will simply let the function(s) below them parse,
  17204. // and, *if* the syntactic construct they handle is present, wrap
  17205. // the AST node that the inner parser gave them in another node.
  17206. // Parse a full expression. The optional arguments are used to
  17207. // forbid the `in` operator (in for loops initalization expressions)
  17208. // and provide reference for storing '=' operator inside shorthand
  17209. // property assignment in contexts where both object expression
  17210. // and object pattern might appear (so it's possible to raise
  17211. // delayed syntax error at correct position).
  17212. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  17213. var startPos = this.start, startLoc = this.startLoc;
  17214. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  17215. if (this.type === types$1.comma) {
  17216. var node = this.startNodeAt(startPos, startLoc);
  17217. node.expressions = [expr];
  17218. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  17219. return this.finishNode(node, "SequenceExpression")
  17220. }
  17221. return expr
  17222. };
  17223. // Parse an assignment expression. This includes applications of
  17224. // operators like `+=`.
  17225. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  17226. if (this.isContextual("yield")) {
  17227. if (this.inGenerator) { return this.parseYield(forInit) }
  17228. // The tokenizer will assume an expression is allowed after
  17229. // `yield`, but this isn't that kind of yield
  17230. else { this.exprAllowed = false; }
  17231. }
  17232. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  17233. if (refDestructuringErrors) {
  17234. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  17235. oldTrailingComma = refDestructuringErrors.trailingComma;
  17236. oldDoubleProto = refDestructuringErrors.doubleProto;
  17237. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  17238. } else {
  17239. refDestructuringErrors = new DestructuringErrors;
  17240. ownDestructuringErrors = true;
  17241. }
  17242. var startPos = this.start, startLoc = this.startLoc;
  17243. if (this.type === types$1.parenL || this.type === types$1.name) {
  17244. this.potentialArrowAt = this.start;
  17245. this.potentialArrowInForAwait = forInit === "await";
  17246. }
  17247. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  17248. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  17249. if (this.type.isAssign) {
  17250. var node = this.startNodeAt(startPos, startLoc);
  17251. node.operator = this.value;
  17252. if (this.type === types$1.eq)
  17253. { left = this.toAssignable(left, false, refDestructuringErrors); }
  17254. if (!ownDestructuringErrors) {
  17255. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  17256. }
  17257. if (refDestructuringErrors.shorthandAssign >= left.start)
  17258. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  17259. if (this.type === types$1.eq)
  17260. { this.checkLValPattern(left); }
  17261. else
  17262. { this.checkLValSimple(left); }
  17263. node.left = left;
  17264. this.next();
  17265. node.right = this.parseMaybeAssign(forInit);
  17266. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  17267. return this.finishNode(node, "AssignmentExpression")
  17268. } else {
  17269. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  17270. }
  17271. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  17272. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  17273. return left
  17274. };
  17275. // Parse a ternary conditional (`?:`) operator.
  17276. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  17277. var startPos = this.start, startLoc = this.startLoc;
  17278. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  17279. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17280. if (this.eat(types$1.question)) {
  17281. var node = this.startNodeAt(startPos, startLoc);
  17282. node.test = expr;
  17283. node.consequent = this.parseMaybeAssign();
  17284. this.expect(types$1.colon);
  17285. node.alternate = this.parseMaybeAssign(forInit);
  17286. return this.finishNode(node, "ConditionalExpression")
  17287. }
  17288. return expr
  17289. };
  17290. // Start the precedence parser.
  17291. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  17292. var startPos = this.start, startLoc = this.startLoc;
  17293. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  17294. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17295. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  17296. };
  17297. // Parse binary operators with the operator precedence parsing
  17298. // algorithm. `left` is the left-hand side of the operator.
  17299. // `minPrec` provides context that allows the function to stop and
  17300. // defer further parser to one of its callers when it encounters an
  17301. // operator that has a lower precedence than the set it is parsing.
  17302. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  17303. var prec = this.type.binop;
  17304. if (prec != null && (!forInit || this.type !== types$1._in)) {
  17305. if (prec > minPrec) {
  17306. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  17307. var coalesce = this.type === types$1.coalesce;
  17308. if (coalesce) {
  17309. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  17310. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  17311. prec = types$1.logicalAND.binop;
  17312. }
  17313. var op = this.value;
  17314. this.next();
  17315. var startPos = this.start, startLoc = this.startLoc;
  17316. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  17317. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  17318. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  17319. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  17320. }
  17321. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  17322. }
  17323. }
  17324. return left
  17325. };
  17326. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  17327. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  17328. var node = this.startNodeAt(startPos, startLoc);
  17329. node.left = left;
  17330. node.operator = op;
  17331. node.right = right;
  17332. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  17333. };
  17334. // Parse unary operators, both prefix and postfix.
  17335. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  17336. var startPos = this.start, startLoc = this.startLoc, expr;
  17337. if (this.isContextual("await") && this.canAwait) {
  17338. expr = this.parseAwait(forInit);
  17339. sawUnary = true;
  17340. } else if (this.type.prefix) {
  17341. var node = this.startNode(), update = this.type === types$1.incDec;
  17342. node.operator = this.value;
  17343. node.prefix = true;
  17344. this.next();
  17345. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  17346. this.checkExpressionErrors(refDestructuringErrors, true);
  17347. if (update) { this.checkLValSimple(node.argument); }
  17348. else if (this.strict && node.operator === "delete" &&
  17349. node.argument.type === "Identifier")
  17350. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  17351. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  17352. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  17353. else { sawUnary = true; }
  17354. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  17355. } else if (!sawUnary && this.type === types$1.privateId) {
  17356. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  17357. expr = this.parsePrivateIdent();
  17358. // only could be private fields in 'in', such as #x in obj
  17359. if (this.type !== types$1._in) { this.unexpected(); }
  17360. } else {
  17361. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  17362. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17363. while (this.type.postfix && !this.canInsertSemicolon()) {
  17364. var node$1 = this.startNodeAt(startPos, startLoc);
  17365. node$1.operator = this.value;
  17366. node$1.prefix = false;
  17367. node$1.argument = expr;
  17368. this.checkLValSimple(expr);
  17369. this.next();
  17370. expr = this.finishNode(node$1, "UpdateExpression");
  17371. }
  17372. }
  17373. if (!incDec && this.eat(types$1.starstar)) {
  17374. if (sawUnary)
  17375. { this.unexpected(this.lastTokStart); }
  17376. else
  17377. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  17378. } else {
  17379. return expr
  17380. }
  17381. };
  17382. function isPrivateFieldAccess(node) {
  17383. return (
  17384. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  17385. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  17386. )
  17387. }
  17388. // Parse call, dot, and `[]`-subscript expressions.
  17389. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  17390. var startPos = this.start, startLoc = this.startLoc;
  17391. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  17392. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  17393. { return expr }
  17394. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  17395. if (refDestructuringErrors && result.type === "MemberExpression") {
  17396. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  17397. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  17398. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  17399. }
  17400. return result
  17401. };
  17402. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  17403. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  17404. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  17405. this.potentialArrowAt === base.start;
  17406. var optionalChained = false;
  17407. while (true) {
  17408. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  17409. if (element.optional) { optionalChained = true; }
  17410. if (element === base || element.type === "ArrowFunctionExpression") {
  17411. if (optionalChained) {
  17412. var chainNode = this.startNodeAt(startPos, startLoc);
  17413. chainNode.expression = element;
  17414. element = this.finishNode(chainNode, "ChainExpression");
  17415. }
  17416. return element
  17417. }
  17418. base = element;
  17419. }
  17420. };
  17421. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  17422. var optionalSupported = this.options.ecmaVersion >= 11;
  17423. var optional = optionalSupported && this.eat(types$1.questionDot);
  17424. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  17425. var computed = this.eat(types$1.bracketL);
  17426. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  17427. var node = this.startNodeAt(startPos, startLoc);
  17428. node.object = base;
  17429. if (computed) {
  17430. node.property = this.parseExpression();
  17431. this.expect(types$1.bracketR);
  17432. } else if (this.type === types$1.privateId && base.type !== "Super") {
  17433. node.property = this.parsePrivateIdent();
  17434. } else {
  17435. node.property = this.parseIdent(this.options.allowReserved !== "never");
  17436. }
  17437. node.computed = !!computed;
  17438. if (optionalSupported) {
  17439. node.optional = optional;
  17440. }
  17441. base = this.finishNode(node, "MemberExpression");
  17442. } else if (!noCalls && this.eat(types$1.parenL)) {
  17443. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17444. this.yieldPos = 0;
  17445. this.awaitPos = 0;
  17446. this.awaitIdentPos = 0;
  17447. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  17448. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17449. this.checkPatternErrors(refDestructuringErrors, false);
  17450. this.checkYieldAwaitInDefaultParams();
  17451. if (this.awaitIdentPos > 0)
  17452. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  17453. this.yieldPos = oldYieldPos;
  17454. this.awaitPos = oldAwaitPos;
  17455. this.awaitIdentPos = oldAwaitIdentPos;
  17456. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  17457. }
  17458. this.checkExpressionErrors(refDestructuringErrors, true);
  17459. this.yieldPos = oldYieldPos || this.yieldPos;
  17460. this.awaitPos = oldAwaitPos || this.awaitPos;
  17461. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  17462. var node$1 = this.startNodeAt(startPos, startLoc);
  17463. node$1.callee = base;
  17464. node$1.arguments = exprList;
  17465. if (optionalSupported) {
  17466. node$1.optional = optional;
  17467. }
  17468. base = this.finishNode(node$1, "CallExpression");
  17469. } else if (this.type === types$1.backQuote) {
  17470. if (optional || optionalChained) {
  17471. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  17472. }
  17473. var node$2 = this.startNodeAt(startPos, startLoc);
  17474. node$2.tag = base;
  17475. node$2.quasi = this.parseTemplate({isTagged: true});
  17476. base = this.finishNode(node$2, "TaggedTemplateExpression");
  17477. }
  17478. return base
  17479. };
  17480. // Parse an atomic expression — either a single token that is an
  17481. // expression, an expression started by a keyword like `function` or
  17482. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  17483. // or `{}`.
  17484. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  17485. // If a division operator appears in an expression position, the
  17486. // tokenizer got confused, and we force it to read a regexp instead.
  17487. if (this.type === types$1.slash) { this.readRegexp(); }
  17488. var node, canBeArrow = this.potentialArrowAt === this.start;
  17489. switch (this.type) {
  17490. case types$1._super:
  17491. if (!this.allowSuper)
  17492. { this.raise(this.start, "'super' keyword outside a method"); }
  17493. node = this.startNode();
  17494. this.next();
  17495. if (this.type === types$1.parenL && !this.allowDirectSuper)
  17496. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  17497. // The `super` keyword can appear at below:
  17498. // SuperProperty:
  17499. // super [ Expression ]
  17500. // super . IdentifierName
  17501. // SuperCall:
  17502. // super ( Arguments )
  17503. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  17504. { this.unexpected(); }
  17505. return this.finishNode(node, "Super")
  17506. case types$1._this:
  17507. node = this.startNode();
  17508. this.next();
  17509. return this.finishNode(node, "ThisExpression")
  17510. case types$1.name:
  17511. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  17512. var id = this.parseIdent(false);
  17513. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  17514. this.overrideContext(types.f_expr);
  17515. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  17516. }
  17517. if (canBeArrow && !this.canInsertSemicolon()) {
  17518. if (this.eat(types$1.arrow))
  17519. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  17520. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  17521. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  17522. id = this.parseIdent(false);
  17523. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  17524. { this.unexpected(); }
  17525. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  17526. }
  17527. }
  17528. return id
  17529. case types$1.regexp:
  17530. var value = this.value;
  17531. node = this.parseLiteral(value.value);
  17532. node.regex = {pattern: value.pattern, flags: value.flags};
  17533. return node
  17534. case types$1.num: case types$1.string:
  17535. return this.parseLiteral(this.value)
  17536. case types$1._null: case types$1._true: case types$1._false:
  17537. node = this.startNode();
  17538. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  17539. node.raw = this.type.keyword;
  17540. this.next();
  17541. return this.finishNode(node, "Literal")
  17542. case types$1.parenL:
  17543. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  17544. if (refDestructuringErrors) {
  17545. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  17546. { refDestructuringErrors.parenthesizedAssign = start; }
  17547. if (refDestructuringErrors.parenthesizedBind < 0)
  17548. { refDestructuringErrors.parenthesizedBind = start; }
  17549. }
  17550. return expr
  17551. case types$1.bracketL:
  17552. node = this.startNode();
  17553. this.next();
  17554. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  17555. return this.finishNode(node, "ArrayExpression")
  17556. case types$1.braceL:
  17557. this.overrideContext(types.b_expr);
  17558. return this.parseObj(false, refDestructuringErrors)
  17559. case types$1._function:
  17560. node = this.startNode();
  17561. this.next();
  17562. return this.parseFunction(node, 0)
  17563. case types$1._class:
  17564. return this.parseClass(this.startNode(), false)
  17565. case types$1._new:
  17566. return this.parseNew()
  17567. case types$1.backQuote:
  17568. return this.parseTemplate()
  17569. case types$1._import:
  17570. if (this.options.ecmaVersion >= 11) {
  17571. return this.parseExprImport()
  17572. } else {
  17573. return this.unexpected()
  17574. }
  17575. default:
  17576. this.unexpected();
  17577. }
  17578. };
  17579. pp$5.parseExprImport = function() {
  17580. var node = this.startNode();
  17581. // Consume `import` as an identifier for `import.meta`.
  17582. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  17583. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  17584. var meta = this.parseIdent(true);
  17585. switch (this.type) {
  17586. case types$1.parenL:
  17587. return this.parseDynamicImport(node)
  17588. case types$1.dot:
  17589. node.meta = meta;
  17590. return this.parseImportMeta(node)
  17591. default:
  17592. this.unexpected();
  17593. }
  17594. };
  17595. pp$5.parseDynamicImport = function(node) {
  17596. this.next(); // skip `(`
  17597. // Parse node.source.
  17598. node.source = this.parseMaybeAssign();
  17599. // Verify ending.
  17600. if (!this.eat(types$1.parenR)) {
  17601. var errorPos = this.start;
  17602. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  17603. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  17604. } else {
  17605. this.unexpected(errorPos);
  17606. }
  17607. }
  17608. return this.finishNode(node, "ImportExpression")
  17609. };
  17610. pp$5.parseImportMeta = function(node) {
  17611. this.next(); // skip `.`
  17612. var containsEsc = this.containsEsc;
  17613. node.property = this.parseIdent(true);
  17614. if (node.property.name !== "meta")
  17615. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  17616. if (containsEsc)
  17617. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  17618. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  17619. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  17620. return this.finishNode(node, "MetaProperty")
  17621. };
  17622. pp$5.parseLiteral = function(value) {
  17623. var node = this.startNode();
  17624. node.value = value;
  17625. node.raw = this.input.slice(this.start, this.end);
  17626. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  17627. this.next();
  17628. return this.finishNode(node, "Literal")
  17629. };
  17630. pp$5.parseParenExpression = function() {
  17631. this.expect(types$1.parenL);
  17632. var val = this.parseExpression();
  17633. this.expect(types$1.parenR);
  17634. return val
  17635. };
  17636. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  17637. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  17638. if (this.options.ecmaVersion >= 6) {
  17639. this.next();
  17640. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  17641. var exprList = [], first = true, lastIsComma = false;
  17642. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  17643. this.yieldPos = 0;
  17644. this.awaitPos = 0;
  17645. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  17646. while (this.type !== types$1.parenR) {
  17647. first ? first = false : this.expect(types$1.comma);
  17648. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  17649. lastIsComma = true;
  17650. break
  17651. } else if (this.type === types$1.ellipsis) {
  17652. spreadStart = this.start;
  17653. exprList.push(this.parseParenItem(this.parseRestBinding()));
  17654. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17655. break
  17656. } else {
  17657. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  17658. }
  17659. }
  17660. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  17661. this.expect(types$1.parenR);
  17662. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17663. this.checkPatternErrors(refDestructuringErrors, false);
  17664. this.checkYieldAwaitInDefaultParams();
  17665. this.yieldPos = oldYieldPos;
  17666. this.awaitPos = oldAwaitPos;
  17667. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  17668. }
  17669. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  17670. if (spreadStart) { this.unexpected(spreadStart); }
  17671. this.checkExpressionErrors(refDestructuringErrors, true);
  17672. this.yieldPos = oldYieldPos || this.yieldPos;
  17673. this.awaitPos = oldAwaitPos || this.awaitPos;
  17674. if (exprList.length > 1) {
  17675. val = this.startNodeAt(innerStartPos, innerStartLoc);
  17676. val.expressions = exprList;
  17677. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  17678. } else {
  17679. val = exprList[0];
  17680. }
  17681. } else {
  17682. val = this.parseParenExpression();
  17683. }
  17684. if (this.options.preserveParens) {
  17685. var par = this.startNodeAt(startPos, startLoc);
  17686. par.expression = val;
  17687. return this.finishNode(par, "ParenthesizedExpression")
  17688. } else {
  17689. return val
  17690. }
  17691. };
  17692. pp$5.parseParenItem = function(item) {
  17693. return item
  17694. };
  17695. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  17696. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  17697. };
  17698. // New's precedence is slightly tricky. It must allow its argument to
  17699. // be a `[]` or dot subscript expression, but not a call — at least,
  17700. // not without wrapping it in parentheses. Thus, it uses the noCalls
  17701. // argument to parseSubscripts to prevent it from consuming the
  17702. // argument list.
  17703. var empty = [];
  17704. pp$5.parseNew = function() {
  17705. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  17706. var node = this.startNode();
  17707. var meta = this.parseIdent(true);
  17708. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  17709. node.meta = meta;
  17710. var containsEsc = this.containsEsc;
  17711. node.property = this.parseIdent(true);
  17712. if (node.property.name !== "target")
  17713. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  17714. if (containsEsc)
  17715. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  17716. if (!this.allowNewDotTarget)
  17717. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  17718. return this.finishNode(node, "MetaProperty")
  17719. }
  17720. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  17721. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  17722. if (isImport && node.callee.type === "ImportExpression") {
  17723. this.raise(startPos, "Cannot use new with import()");
  17724. }
  17725. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  17726. else { node.arguments = empty; }
  17727. return this.finishNode(node, "NewExpression")
  17728. };
  17729. // Parse template expression.
  17730. pp$5.parseTemplateElement = function(ref) {
  17731. var isTagged = ref.isTagged;
  17732. var elem = this.startNode();
  17733. if (this.type === types$1.invalidTemplate) {
  17734. if (!isTagged) {
  17735. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  17736. }
  17737. elem.value = {
  17738. raw: this.value,
  17739. cooked: null
  17740. };
  17741. } else {
  17742. elem.value = {
  17743. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  17744. cooked: this.value
  17745. };
  17746. }
  17747. this.next();
  17748. elem.tail = this.type === types$1.backQuote;
  17749. return this.finishNode(elem, "TemplateElement")
  17750. };
  17751. pp$5.parseTemplate = function(ref) {
  17752. if ( ref === void 0 ) ref = {};
  17753. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  17754. var node = this.startNode();
  17755. this.next();
  17756. node.expressions = [];
  17757. var curElt = this.parseTemplateElement({isTagged: isTagged});
  17758. node.quasis = [curElt];
  17759. while (!curElt.tail) {
  17760. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  17761. this.expect(types$1.dollarBraceL);
  17762. node.expressions.push(this.parseExpression());
  17763. this.expect(types$1.braceR);
  17764. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  17765. }
  17766. this.next();
  17767. return this.finishNode(node, "TemplateLiteral")
  17768. };
  17769. pp$5.isAsyncProp = function(prop) {
  17770. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  17771. (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)) &&
  17772. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17773. };
  17774. // Parse an object literal or binding pattern.
  17775. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  17776. var node = this.startNode(), first = true, propHash = {};
  17777. node.properties = [];
  17778. this.next();
  17779. while (!this.eat(types$1.braceR)) {
  17780. if (!first) {
  17781. this.expect(types$1.comma);
  17782. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  17783. } else { first = false; }
  17784. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  17785. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  17786. node.properties.push(prop);
  17787. }
  17788. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  17789. };
  17790. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  17791. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  17792. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  17793. if (isPattern) {
  17794. prop.argument = this.parseIdent(false);
  17795. if (this.type === types$1.comma) {
  17796. this.raise(this.start, "Comma is not permitted after the rest element");
  17797. }
  17798. return this.finishNode(prop, "RestElement")
  17799. }
  17800. // To disallow parenthesized identifier via `this.toAssignable()`.
  17801. if (this.type === types$1.parenL && refDestructuringErrors) {
  17802. if (refDestructuringErrors.parenthesizedAssign < 0) {
  17803. refDestructuringErrors.parenthesizedAssign = this.start;
  17804. }
  17805. if (refDestructuringErrors.parenthesizedBind < 0) {
  17806. refDestructuringErrors.parenthesizedBind = this.start;
  17807. }
  17808. }
  17809. // Parse argument.
  17810. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  17811. // To disallow trailing comma via `this.toAssignable()`.
  17812. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  17813. refDestructuringErrors.trailingComma = this.start;
  17814. }
  17815. // Finish
  17816. return this.finishNode(prop, "SpreadElement")
  17817. }
  17818. if (this.options.ecmaVersion >= 6) {
  17819. prop.method = false;
  17820. prop.shorthand = false;
  17821. if (isPattern || refDestructuringErrors) {
  17822. startPos = this.start;
  17823. startLoc = this.startLoc;
  17824. }
  17825. if (!isPattern)
  17826. { isGenerator = this.eat(types$1.star); }
  17827. }
  17828. var containsEsc = this.containsEsc;
  17829. this.parsePropertyName(prop);
  17830. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  17831. isAsync = true;
  17832. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  17833. this.parsePropertyName(prop, refDestructuringErrors);
  17834. } else {
  17835. isAsync = false;
  17836. }
  17837. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  17838. return this.finishNode(prop, "Property")
  17839. };
  17840. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  17841. if ((isGenerator || isAsync) && this.type === types$1.colon)
  17842. { this.unexpected(); }
  17843. if (this.eat(types$1.colon)) {
  17844. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  17845. prop.kind = "init";
  17846. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  17847. if (isPattern) { this.unexpected(); }
  17848. prop.kind = "init";
  17849. prop.method = true;
  17850. prop.value = this.parseMethod(isGenerator, isAsync);
  17851. } else if (!isPattern && !containsEsc &&
  17852. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  17853. (prop.key.name === "get" || prop.key.name === "set") &&
  17854. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  17855. if (isGenerator || isAsync) { this.unexpected(); }
  17856. prop.kind = prop.key.name;
  17857. this.parsePropertyName(prop);
  17858. prop.value = this.parseMethod(false);
  17859. var paramCount = prop.kind === "get" ? 0 : 1;
  17860. if (prop.value.params.length !== paramCount) {
  17861. var start = prop.value.start;
  17862. if (prop.kind === "get")
  17863. { this.raiseRecoverable(start, "getter should have no params"); }
  17864. else
  17865. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  17866. } else {
  17867. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  17868. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  17869. }
  17870. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  17871. if (isGenerator || isAsync) { this.unexpected(); }
  17872. this.checkUnreserved(prop.key);
  17873. if (prop.key.name === "await" && !this.awaitIdentPos)
  17874. { this.awaitIdentPos = startPos; }
  17875. prop.kind = "init";
  17876. if (isPattern) {
  17877. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  17878. } else if (this.type === types$1.eq && refDestructuringErrors) {
  17879. if (refDestructuringErrors.shorthandAssign < 0)
  17880. { refDestructuringErrors.shorthandAssign = this.start; }
  17881. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  17882. } else {
  17883. prop.value = this.copyNode(prop.key);
  17884. }
  17885. prop.shorthand = true;
  17886. } else { this.unexpected(); }
  17887. };
  17888. pp$5.parsePropertyName = function(prop) {
  17889. if (this.options.ecmaVersion >= 6) {
  17890. if (this.eat(types$1.bracketL)) {
  17891. prop.computed = true;
  17892. prop.key = this.parseMaybeAssign();
  17893. this.expect(types$1.bracketR);
  17894. return prop.key
  17895. } else {
  17896. prop.computed = false;
  17897. }
  17898. }
  17899. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  17900. };
  17901. // Initialize empty function node.
  17902. pp$5.initFunction = function(node) {
  17903. node.id = null;
  17904. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  17905. if (this.options.ecmaVersion >= 8) { node.async = false; }
  17906. };
  17907. // Parse object or class method.
  17908. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  17909. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17910. this.initFunction(node);
  17911. if (this.options.ecmaVersion >= 6)
  17912. { node.generator = isGenerator; }
  17913. if (this.options.ecmaVersion >= 8)
  17914. { node.async = !!isAsync; }
  17915. this.yieldPos = 0;
  17916. this.awaitPos = 0;
  17917. this.awaitIdentPos = 0;
  17918. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  17919. this.expect(types$1.parenL);
  17920. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  17921. this.checkYieldAwaitInDefaultParams();
  17922. this.parseFunctionBody(node, false, true, false);
  17923. this.yieldPos = oldYieldPos;
  17924. this.awaitPos = oldAwaitPos;
  17925. this.awaitIdentPos = oldAwaitIdentPos;
  17926. return this.finishNode(node, "FunctionExpression")
  17927. };
  17928. // Parse arrow function expression with given parameters.
  17929. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  17930. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17931. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  17932. this.initFunction(node);
  17933. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  17934. this.yieldPos = 0;
  17935. this.awaitPos = 0;
  17936. this.awaitIdentPos = 0;
  17937. node.params = this.toAssignableList(params, true);
  17938. this.parseFunctionBody(node, true, false, forInit);
  17939. this.yieldPos = oldYieldPos;
  17940. this.awaitPos = oldAwaitPos;
  17941. this.awaitIdentPos = oldAwaitIdentPos;
  17942. return this.finishNode(node, "ArrowFunctionExpression")
  17943. };
  17944. // Parse function body and check parameters.
  17945. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  17946. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  17947. var oldStrict = this.strict, useStrict = false;
  17948. if (isExpression) {
  17949. node.body = this.parseMaybeAssign(forInit);
  17950. node.expression = true;
  17951. this.checkParams(node, false);
  17952. } else {
  17953. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  17954. if (!oldStrict || nonSimple) {
  17955. useStrict = this.strictDirective(this.end);
  17956. // If this is a strict mode function, verify that argument names
  17957. // are not repeated, and it does not try to bind the words `eval`
  17958. // or `arguments`.
  17959. if (useStrict && nonSimple)
  17960. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  17961. }
  17962. // Start a new scope with regard to labels and the `inFunction`
  17963. // flag (restore them to their old value afterwards).
  17964. var oldLabels = this.labels;
  17965. this.labels = [];
  17966. if (useStrict) { this.strict = true; }
  17967. // Add the params to varDeclaredNames to ensure that an error is thrown
  17968. // if a let/const declaration in the function clashes with one of the params.
  17969. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  17970. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  17971. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  17972. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  17973. node.expression = false;
  17974. this.adaptDirectivePrologue(node.body.body);
  17975. this.labels = oldLabels;
  17976. }
  17977. this.exitScope();
  17978. };
  17979. pp$5.isSimpleParamList = function(params) {
  17980. for (var i = 0, list = params; i < list.length; i += 1)
  17981. {
  17982. var param = list[i];
  17983. if (param.type !== "Identifier") { return false
  17984. } }
  17985. return true
  17986. };
  17987. // Checks function params for various disallowed patterns such as using "eval"
  17988. // or "arguments" and duplicate parameters.
  17989. pp$5.checkParams = function(node, allowDuplicates) {
  17990. var nameHash = Object.create(null);
  17991. for (var i = 0, list = node.params; i < list.length; i += 1)
  17992. {
  17993. var param = list[i];
  17994. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  17995. }
  17996. };
  17997. // Parses a comma-separated list of expressions, and returns them as
  17998. // an array. `close` is the token type that ends the list, and
  17999. // `allowEmpty` can be turned on to allow subsequent commas with
  18000. // nothing in between them to be parsed as `null` (which is needed
  18001. // for array literals).
  18002. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  18003. var elts = [], first = true;
  18004. while (!this.eat(close)) {
  18005. if (!first) {
  18006. this.expect(types$1.comma);
  18007. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  18008. } else { first = false; }
  18009. var elt = (void 0);
  18010. if (allowEmpty && this.type === types$1.comma)
  18011. { elt = null; }
  18012. else if (this.type === types$1.ellipsis) {
  18013. elt = this.parseSpread(refDestructuringErrors);
  18014. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  18015. { refDestructuringErrors.trailingComma = this.start; }
  18016. } else {
  18017. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  18018. }
  18019. elts.push(elt);
  18020. }
  18021. return elts
  18022. };
  18023. pp$5.checkUnreserved = function(ref) {
  18024. var start = ref.start;
  18025. var end = ref.end;
  18026. var name = ref.name;
  18027. if (this.inGenerator && name === "yield")
  18028. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  18029. if (this.inAsync && name === "await")
  18030. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  18031. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  18032. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  18033. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  18034. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  18035. if (this.keywords.test(name))
  18036. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  18037. if (this.options.ecmaVersion < 6 &&
  18038. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  18039. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  18040. if (re.test(name)) {
  18041. if (!this.inAsync && name === "await")
  18042. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  18043. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  18044. }
  18045. };
  18046. // Parse the next token as an identifier. If `liberal` is true (used
  18047. // when parsing properties), it will also convert keywords into
  18048. // identifiers.
  18049. pp$5.parseIdent = function(liberal, isBinding) {
  18050. var node = this.startNode();
  18051. if (this.type === types$1.name) {
  18052. node.name = this.value;
  18053. } else if (this.type.keyword) {
  18054. node.name = this.type.keyword;
  18055. // To fix https://github.com/acornjs/acorn/issues/575
  18056. // `class` and `function` keywords push new context into this.context.
  18057. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  18058. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  18059. if ((node.name === "class" || node.name === "function") &&
  18060. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  18061. this.context.pop();
  18062. }
  18063. } else {
  18064. this.unexpected();
  18065. }
  18066. this.next(!!liberal);
  18067. this.finishNode(node, "Identifier");
  18068. if (!liberal) {
  18069. this.checkUnreserved(node);
  18070. if (node.name === "await" && !this.awaitIdentPos)
  18071. { this.awaitIdentPos = node.start; }
  18072. }
  18073. return node
  18074. };
  18075. pp$5.parsePrivateIdent = function() {
  18076. var node = this.startNode();
  18077. if (this.type === types$1.privateId) {
  18078. node.name = this.value;
  18079. } else {
  18080. this.unexpected();
  18081. }
  18082. this.next();
  18083. this.finishNode(node, "PrivateIdentifier");
  18084. // For validating existence
  18085. if (this.privateNameStack.length === 0) {
  18086. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  18087. } else {
  18088. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  18089. }
  18090. return node
  18091. };
  18092. // Parses yield expression inside generator.
  18093. pp$5.parseYield = function(forInit) {
  18094. if (!this.yieldPos) { this.yieldPos = this.start; }
  18095. var node = this.startNode();
  18096. this.next();
  18097. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  18098. node.delegate = false;
  18099. node.argument = null;
  18100. } else {
  18101. node.delegate = this.eat(types$1.star);
  18102. node.argument = this.parseMaybeAssign(forInit);
  18103. }
  18104. return this.finishNode(node, "YieldExpression")
  18105. };
  18106. pp$5.parseAwait = function(forInit) {
  18107. if (!this.awaitPos) { this.awaitPos = this.start; }
  18108. var node = this.startNode();
  18109. this.next();
  18110. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  18111. return this.finishNode(node, "AwaitExpression")
  18112. };
  18113. var pp$4 = Parser.prototype;
  18114. // This function is used to raise exceptions on parse errors. It
  18115. // takes an offset integer (into the current `input`) to indicate
  18116. // the location of the error, attaches the position to the end
  18117. // of the error message, and then raises a `SyntaxError` with that
  18118. // message.
  18119. pp$4.raise = function(pos, message) {
  18120. var loc = getLineInfo(this.input, pos);
  18121. message += " (" + loc.line + ":" + loc.column + ")";
  18122. var err = new SyntaxError(message);
  18123. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  18124. throw err
  18125. };
  18126. pp$4.raiseRecoverable = pp$4.raise;
  18127. pp$4.curPosition = function() {
  18128. if (this.options.locations) {
  18129. return new Position(this.curLine, this.pos - this.lineStart)
  18130. }
  18131. };
  18132. var pp$3 = Parser.prototype;
  18133. var Scope = function Scope(flags) {
  18134. this.flags = flags;
  18135. // A list of var-declared names in the current lexical scope
  18136. this.var = [];
  18137. // A list of lexically-declared names in the current lexical scope
  18138. this.lexical = [];
  18139. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  18140. this.functions = [];
  18141. // A switch to disallow the identifier reference 'arguments'
  18142. this.inClassFieldInit = false;
  18143. };
  18144. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  18145. pp$3.enterScope = function(flags) {
  18146. this.scopeStack.push(new Scope(flags));
  18147. };
  18148. pp$3.exitScope = function() {
  18149. this.scopeStack.pop();
  18150. };
  18151. // The spec says:
  18152. // > At the top level of a function, or script, function declarations are
  18153. // > treated like var declarations rather than like lexical declarations.
  18154. pp$3.treatFunctionsAsVarInScope = function(scope) {
  18155. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  18156. };
  18157. pp$3.declareName = function(name, bindingType, pos) {
  18158. var redeclared = false;
  18159. if (bindingType === BIND_LEXICAL) {
  18160. var scope = this.currentScope();
  18161. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  18162. scope.lexical.push(name);
  18163. if (this.inModule && (scope.flags & SCOPE_TOP))
  18164. { delete this.undefinedExports[name]; }
  18165. } else if (bindingType === BIND_SIMPLE_CATCH) {
  18166. var scope$1 = this.currentScope();
  18167. scope$1.lexical.push(name);
  18168. } else if (bindingType === BIND_FUNCTION) {
  18169. var scope$2 = this.currentScope();
  18170. if (this.treatFunctionsAsVar)
  18171. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  18172. else
  18173. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  18174. scope$2.functions.push(name);
  18175. } else {
  18176. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  18177. var scope$3 = this.scopeStack[i];
  18178. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  18179. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  18180. redeclared = true;
  18181. break
  18182. }
  18183. scope$3.var.push(name);
  18184. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  18185. { delete this.undefinedExports[name]; }
  18186. if (scope$3.flags & SCOPE_VAR) { break }
  18187. }
  18188. }
  18189. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  18190. };
  18191. pp$3.checkLocalExport = function(id) {
  18192. // scope.functions must be empty as Module code is always strict.
  18193. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  18194. this.scopeStack[0].var.indexOf(id.name) === -1) {
  18195. this.undefinedExports[id.name] = id;
  18196. }
  18197. };
  18198. pp$3.currentScope = function() {
  18199. return this.scopeStack[this.scopeStack.length - 1]
  18200. };
  18201. pp$3.currentVarScope = function() {
  18202. for (var i = this.scopeStack.length - 1;; i--) {
  18203. var scope = this.scopeStack[i];
  18204. if (scope.flags & SCOPE_VAR) { return scope }
  18205. }
  18206. };
  18207. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  18208. pp$3.currentThisScope = function() {
  18209. for (var i = this.scopeStack.length - 1;; i--) {
  18210. var scope = this.scopeStack[i];
  18211. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  18212. }
  18213. };
  18214. var Node = function Node(parser, pos, loc) {
  18215. this.type = "";
  18216. this.start = pos;
  18217. this.end = 0;
  18218. if (parser.options.locations)
  18219. { this.loc = new SourceLocation(parser, loc); }
  18220. if (parser.options.directSourceFile)
  18221. { this.sourceFile = parser.options.directSourceFile; }
  18222. if (parser.options.ranges)
  18223. { this.range = [pos, 0]; }
  18224. };
  18225. // Start an AST node, attaching a start offset.
  18226. var pp$2 = Parser.prototype;
  18227. pp$2.startNode = function() {
  18228. return new Node(this, this.start, this.startLoc)
  18229. };
  18230. pp$2.startNodeAt = function(pos, loc) {
  18231. return new Node(this, pos, loc)
  18232. };
  18233. // Finish an AST node, adding `type` and `end` properties.
  18234. function finishNodeAt(node, type, pos, loc) {
  18235. node.type = type;
  18236. node.end = pos;
  18237. if (this.options.locations)
  18238. { node.loc.end = loc; }
  18239. if (this.options.ranges)
  18240. { node.range[1] = pos; }
  18241. return node
  18242. }
  18243. pp$2.finishNode = function(node, type) {
  18244. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  18245. };
  18246. // Finish node at given position
  18247. pp$2.finishNodeAt = function(node, type, pos, loc) {
  18248. return finishNodeAt.call(this, node, type, pos, loc)
  18249. };
  18250. pp$2.copyNode = function(node) {
  18251. var newNode = new Node(this, node.start, this.startLoc);
  18252. for (var prop in node) { newNode[prop] = node[prop]; }
  18253. return newNode
  18254. };
  18255. // This file contains Unicode properties extracted from the ECMAScript
  18256. // specification. The lists are extracted like so:
  18257. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  18258. // #table-binary-unicode-properties
  18259. 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";
  18260. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  18261. var ecma11BinaryProperties = ecma10BinaryProperties;
  18262. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  18263. var ecma13BinaryProperties = ecma12BinaryProperties;
  18264. var unicodeBinaryProperties = {
  18265. 9: ecma9BinaryProperties,
  18266. 10: ecma10BinaryProperties,
  18267. 11: ecma11BinaryProperties,
  18268. 12: ecma12BinaryProperties,
  18269. 13: ecma13BinaryProperties
  18270. };
  18271. // #table-unicode-general-category-values
  18272. 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";
  18273. // #table-unicode-script-values
  18274. 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";
  18275. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  18276. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  18277. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  18278. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  18279. var unicodeScriptValues = {
  18280. 9: ecma9ScriptValues,
  18281. 10: ecma10ScriptValues,
  18282. 11: ecma11ScriptValues,
  18283. 12: ecma12ScriptValues,
  18284. 13: ecma13ScriptValues
  18285. };
  18286. var data = {};
  18287. function buildUnicodeData(ecmaVersion) {
  18288. var d = data[ecmaVersion] = {
  18289. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  18290. nonBinary: {
  18291. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  18292. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  18293. }
  18294. };
  18295. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  18296. d.nonBinary.gc = d.nonBinary.General_Category;
  18297. d.nonBinary.sc = d.nonBinary.Script;
  18298. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  18299. }
  18300. for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
  18301. var ecmaVersion = list[i];
  18302. buildUnicodeData(ecmaVersion);
  18303. }
  18304. var pp$1 = Parser.prototype;
  18305. var RegExpValidationState = function RegExpValidationState(parser) {
  18306. this.parser = parser;
  18307. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  18308. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  18309. this.source = "";
  18310. this.flags = "";
  18311. this.start = 0;
  18312. this.switchU = false;
  18313. this.switchN = false;
  18314. this.pos = 0;
  18315. this.lastIntValue = 0;
  18316. this.lastStringValue = "";
  18317. this.lastAssertionIsQuantifiable = false;
  18318. this.numCapturingParens = 0;
  18319. this.maxBackReference = 0;
  18320. this.groupNames = [];
  18321. this.backReferenceNames = [];
  18322. };
  18323. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  18324. var unicode = flags.indexOf("u") !== -1;
  18325. this.start = start | 0;
  18326. this.source = pattern + "";
  18327. this.flags = flags;
  18328. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  18329. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  18330. };
  18331. RegExpValidationState.prototype.raise = function raise (message) {
  18332. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  18333. };
  18334. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  18335. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  18336. RegExpValidationState.prototype.at = function at (i, forceU) {
  18337. if ( forceU === void 0 ) forceU = false;
  18338. var s = this.source;
  18339. var l = s.length;
  18340. if (i >= l) {
  18341. return -1
  18342. }
  18343. var c = s.charCodeAt(i);
  18344. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  18345. return c
  18346. }
  18347. var next = s.charCodeAt(i + 1);
  18348. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  18349. };
  18350. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  18351. if ( forceU === void 0 ) forceU = false;
  18352. var s = this.source;
  18353. var l = s.length;
  18354. if (i >= l) {
  18355. return l
  18356. }
  18357. var c = s.charCodeAt(i), next;
  18358. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  18359. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  18360. return i + 1
  18361. }
  18362. return i + 2
  18363. };
  18364. RegExpValidationState.prototype.current = function current (forceU) {
  18365. if ( forceU === void 0 ) forceU = false;
  18366. return this.at(this.pos, forceU)
  18367. };
  18368. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  18369. if ( forceU === void 0 ) forceU = false;
  18370. return this.at(this.nextIndex(this.pos, forceU), forceU)
  18371. };
  18372. RegExpValidationState.prototype.advance = function advance (forceU) {
  18373. if ( forceU === void 0 ) forceU = false;
  18374. this.pos = this.nextIndex(this.pos, forceU);
  18375. };
  18376. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  18377. if ( forceU === void 0 ) forceU = false;
  18378. if (this.current(forceU) === ch) {
  18379. this.advance(forceU);
  18380. return true
  18381. }
  18382. return false
  18383. };
  18384. /**
  18385. * Validate the flags part of a given RegExpLiteral.
  18386. *
  18387. * @param {RegExpValidationState} state The state to validate RegExp.
  18388. * @returns {void}
  18389. */
  18390. pp$1.validateRegExpFlags = function(state) {
  18391. var validFlags = state.validFlags;
  18392. var flags = state.flags;
  18393. for (var i = 0; i < flags.length; i++) {
  18394. var flag = flags.charAt(i);
  18395. if (validFlags.indexOf(flag) === -1) {
  18396. this.raise(state.start, "Invalid regular expression flag");
  18397. }
  18398. if (flags.indexOf(flag, i + 1) > -1) {
  18399. this.raise(state.start, "Duplicate regular expression flag");
  18400. }
  18401. }
  18402. };
  18403. /**
  18404. * Validate the pattern part of a given RegExpLiteral.
  18405. *
  18406. * @param {RegExpValidationState} state The state to validate RegExp.
  18407. * @returns {void}
  18408. */
  18409. pp$1.validateRegExpPattern = function(state) {
  18410. this.regexp_pattern(state);
  18411. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  18412. // parsing contains a |GroupName|, reparse with the goal symbol
  18413. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  18414. // exception if _P_ did not conform to the grammar, if any elements of _P_
  18415. // were not matched by the parse, or if any Early Error conditions exist.
  18416. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  18417. state.switchN = true;
  18418. this.regexp_pattern(state);
  18419. }
  18420. };
  18421. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  18422. pp$1.regexp_pattern = function(state) {
  18423. state.pos = 0;
  18424. state.lastIntValue = 0;
  18425. state.lastStringValue = "";
  18426. state.lastAssertionIsQuantifiable = false;
  18427. state.numCapturingParens = 0;
  18428. state.maxBackReference = 0;
  18429. state.groupNames.length = 0;
  18430. state.backReferenceNames.length = 0;
  18431. this.regexp_disjunction(state);
  18432. if (state.pos !== state.source.length) {
  18433. // Make the same messages as V8.
  18434. if (state.eat(0x29 /* ) */)) {
  18435. state.raise("Unmatched ')'");
  18436. }
  18437. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  18438. state.raise("Lone quantifier brackets");
  18439. }
  18440. }
  18441. if (state.maxBackReference > state.numCapturingParens) {
  18442. state.raise("Invalid escape");
  18443. }
  18444. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  18445. var name = list[i];
  18446. if (state.groupNames.indexOf(name) === -1) {
  18447. state.raise("Invalid named capture referenced");
  18448. }
  18449. }
  18450. };
  18451. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  18452. pp$1.regexp_disjunction = function(state) {
  18453. this.regexp_alternative(state);
  18454. while (state.eat(0x7C /* | */)) {
  18455. this.regexp_alternative(state);
  18456. }
  18457. // Make the same message as V8.
  18458. if (this.regexp_eatQuantifier(state, true)) {
  18459. state.raise("Nothing to repeat");
  18460. }
  18461. if (state.eat(0x7B /* { */)) {
  18462. state.raise("Lone quantifier brackets");
  18463. }
  18464. };
  18465. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  18466. pp$1.regexp_alternative = function(state) {
  18467. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  18468. { }
  18469. };
  18470. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  18471. pp$1.regexp_eatTerm = function(state) {
  18472. if (this.regexp_eatAssertion(state)) {
  18473. // Handle `QuantifiableAssertion Quantifier` alternative.
  18474. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  18475. // is a QuantifiableAssertion.
  18476. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  18477. // Make the same message as V8.
  18478. if (state.switchU) {
  18479. state.raise("Invalid quantifier");
  18480. }
  18481. }
  18482. return true
  18483. }
  18484. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  18485. this.regexp_eatQuantifier(state);
  18486. return true
  18487. }
  18488. return false
  18489. };
  18490. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  18491. pp$1.regexp_eatAssertion = function(state) {
  18492. var start = state.pos;
  18493. state.lastAssertionIsQuantifiable = false;
  18494. // ^, $
  18495. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  18496. return true
  18497. }
  18498. // \b \B
  18499. if (state.eat(0x5C /* \ */)) {
  18500. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  18501. return true
  18502. }
  18503. state.pos = start;
  18504. }
  18505. // Lookahead / Lookbehind
  18506. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  18507. var lookbehind = false;
  18508. if (this.options.ecmaVersion >= 9) {
  18509. lookbehind = state.eat(0x3C /* < */);
  18510. }
  18511. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  18512. this.regexp_disjunction(state);
  18513. if (!state.eat(0x29 /* ) */)) {
  18514. state.raise("Unterminated group");
  18515. }
  18516. state.lastAssertionIsQuantifiable = !lookbehind;
  18517. return true
  18518. }
  18519. }
  18520. state.pos = start;
  18521. return false
  18522. };
  18523. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  18524. pp$1.regexp_eatQuantifier = function(state, noError) {
  18525. if ( noError === void 0 ) noError = false;
  18526. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  18527. state.eat(0x3F /* ? */);
  18528. return true
  18529. }
  18530. return false
  18531. };
  18532. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  18533. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  18534. return (
  18535. state.eat(0x2A /* * */) ||
  18536. state.eat(0x2B /* + */) ||
  18537. state.eat(0x3F /* ? */) ||
  18538. this.regexp_eatBracedQuantifier(state, noError)
  18539. )
  18540. };
  18541. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  18542. var start = state.pos;
  18543. if (state.eat(0x7B /* { */)) {
  18544. var min = 0, max = -1;
  18545. if (this.regexp_eatDecimalDigits(state)) {
  18546. min = state.lastIntValue;
  18547. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  18548. max = state.lastIntValue;
  18549. }
  18550. if (state.eat(0x7D /* } */)) {
  18551. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  18552. if (max !== -1 && max < min && !noError) {
  18553. state.raise("numbers out of order in {} quantifier");
  18554. }
  18555. return true
  18556. }
  18557. }
  18558. if (state.switchU && !noError) {
  18559. state.raise("Incomplete quantifier");
  18560. }
  18561. state.pos = start;
  18562. }
  18563. return false
  18564. };
  18565. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  18566. pp$1.regexp_eatAtom = function(state) {
  18567. return (
  18568. this.regexp_eatPatternCharacters(state) ||
  18569. state.eat(0x2E /* . */) ||
  18570. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18571. this.regexp_eatCharacterClass(state) ||
  18572. this.regexp_eatUncapturingGroup(state) ||
  18573. this.regexp_eatCapturingGroup(state)
  18574. )
  18575. };
  18576. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  18577. var start = state.pos;
  18578. if (state.eat(0x5C /* \ */)) {
  18579. if (this.regexp_eatAtomEscape(state)) {
  18580. return true
  18581. }
  18582. state.pos = start;
  18583. }
  18584. return false
  18585. };
  18586. pp$1.regexp_eatUncapturingGroup = function(state) {
  18587. var start = state.pos;
  18588. if (state.eat(0x28 /* ( */)) {
  18589. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  18590. this.regexp_disjunction(state);
  18591. if (state.eat(0x29 /* ) */)) {
  18592. return true
  18593. }
  18594. state.raise("Unterminated group");
  18595. }
  18596. state.pos = start;
  18597. }
  18598. return false
  18599. };
  18600. pp$1.regexp_eatCapturingGroup = function(state) {
  18601. if (state.eat(0x28 /* ( */)) {
  18602. if (this.options.ecmaVersion >= 9) {
  18603. this.regexp_groupSpecifier(state);
  18604. } else if (state.current() === 0x3F /* ? */) {
  18605. state.raise("Invalid group");
  18606. }
  18607. this.regexp_disjunction(state);
  18608. if (state.eat(0x29 /* ) */)) {
  18609. state.numCapturingParens += 1;
  18610. return true
  18611. }
  18612. state.raise("Unterminated group");
  18613. }
  18614. return false
  18615. };
  18616. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  18617. pp$1.regexp_eatExtendedAtom = function(state) {
  18618. return (
  18619. state.eat(0x2E /* . */) ||
  18620. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18621. this.regexp_eatCharacterClass(state) ||
  18622. this.regexp_eatUncapturingGroup(state) ||
  18623. this.regexp_eatCapturingGroup(state) ||
  18624. this.regexp_eatInvalidBracedQuantifier(state) ||
  18625. this.regexp_eatExtendedPatternCharacter(state)
  18626. )
  18627. };
  18628. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  18629. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  18630. if (this.regexp_eatBracedQuantifier(state, true)) {
  18631. state.raise("Nothing to repeat");
  18632. }
  18633. return false
  18634. };
  18635. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  18636. pp$1.regexp_eatSyntaxCharacter = function(state) {
  18637. var ch = state.current();
  18638. if (isSyntaxCharacter(ch)) {
  18639. state.lastIntValue = ch;
  18640. state.advance();
  18641. return true
  18642. }
  18643. return false
  18644. };
  18645. function isSyntaxCharacter(ch) {
  18646. return (
  18647. ch === 0x24 /* $ */ ||
  18648. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  18649. ch === 0x2E /* . */ ||
  18650. ch === 0x3F /* ? */ ||
  18651. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  18652. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  18653. )
  18654. }
  18655. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  18656. // But eat eager.
  18657. pp$1.regexp_eatPatternCharacters = function(state) {
  18658. var start = state.pos;
  18659. var ch = 0;
  18660. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  18661. state.advance();
  18662. }
  18663. return state.pos !== start
  18664. };
  18665. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  18666. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  18667. var ch = state.current();
  18668. if (
  18669. ch !== -1 &&
  18670. ch !== 0x24 /* $ */ &&
  18671. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  18672. ch !== 0x2E /* . */ &&
  18673. ch !== 0x3F /* ? */ &&
  18674. ch !== 0x5B /* [ */ &&
  18675. ch !== 0x5E /* ^ */ &&
  18676. ch !== 0x7C /* | */
  18677. ) {
  18678. state.advance();
  18679. return true
  18680. }
  18681. return false
  18682. };
  18683. // GroupSpecifier ::
  18684. // [empty]
  18685. // `?` GroupName
  18686. pp$1.regexp_groupSpecifier = function(state) {
  18687. if (state.eat(0x3F /* ? */)) {
  18688. if (this.regexp_eatGroupName(state)) {
  18689. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  18690. state.raise("Duplicate capture group name");
  18691. }
  18692. state.groupNames.push(state.lastStringValue);
  18693. return
  18694. }
  18695. state.raise("Invalid group");
  18696. }
  18697. };
  18698. // GroupName ::
  18699. // `<` RegExpIdentifierName `>`
  18700. // Note: this updates `state.lastStringValue` property with the eaten name.
  18701. pp$1.regexp_eatGroupName = function(state) {
  18702. state.lastStringValue = "";
  18703. if (state.eat(0x3C /* < */)) {
  18704. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  18705. return true
  18706. }
  18707. state.raise("Invalid capture group name");
  18708. }
  18709. return false
  18710. };
  18711. // RegExpIdentifierName ::
  18712. // RegExpIdentifierStart
  18713. // RegExpIdentifierName RegExpIdentifierPart
  18714. // Note: this updates `state.lastStringValue` property with the eaten name.
  18715. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  18716. state.lastStringValue = "";
  18717. if (this.regexp_eatRegExpIdentifierStart(state)) {
  18718. state.lastStringValue += codePointToString(state.lastIntValue);
  18719. while (this.regexp_eatRegExpIdentifierPart(state)) {
  18720. state.lastStringValue += codePointToString(state.lastIntValue);
  18721. }
  18722. return true
  18723. }
  18724. return false
  18725. };
  18726. // RegExpIdentifierStart ::
  18727. // UnicodeIDStart
  18728. // `$`
  18729. // `_`
  18730. // `\` RegExpUnicodeEscapeSequence[+U]
  18731. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  18732. var start = state.pos;
  18733. var forceU = this.options.ecmaVersion >= 11;
  18734. var ch = state.current(forceU);
  18735. state.advance(forceU);
  18736. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18737. ch = state.lastIntValue;
  18738. }
  18739. if (isRegExpIdentifierStart(ch)) {
  18740. state.lastIntValue = ch;
  18741. return true
  18742. }
  18743. state.pos = start;
  18744. return false
  18745. };
  18746. function isRegExpIdentifierStart(ch) {
  18747. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  18748. }
  18749. // RegExpIdentifierPart ::
  18750. // UnicodeIDContinue
  18751. // `$`
  18752. // `_`
  18753. // `\` RegExpUnicodeEscapeSequence[+U]
  18754. // <ZWNJ>
  18755. // <ZWJ>
  18756. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  18757. var start = state.pos;
  18758. var forceU = this.options.ecmaVersion >= 11;
  18759. var ch = state.current(forceU);
  18760. state.advance(forceU);
  18761. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18762. ch = state.lastIntValue;
  18763. }
  18764. if (isRegExpIdentifierPart(ch)) {
  18765. state.lastIntValue = ch;
  18766. return true
  18767. }
  18768. state.pos = start;
  18769. return false
  18770. };
  18771. function isRegExpIdentifierPart(ch) {
  18772. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  18773. }
  18774. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  18775. pp$1.regexp_eatAtomEscape = function(state) {
  18776. if (
  18777. this.regexp_eatBackReference(state) ||
  18778. this.regexp_eatCharacterClassEscape(state) ||
  18779. this.regexp_eatCharacterEscape(state) ||
  18780. (state.switchN && this.regexp_eatKGroupName(state))
  18781. ) {
  18782. return true
  18783. }
  18784. if (state.switchU) {
  18785. // Make the same message as V8.
  18786. if (state.current() === 0x63 /* c */) {
  18787. state.raise("Invalid unicode escape");
  18788. }
  18789. state.raise("Invalid escape");
  18790. }
  18791. return false
  18792. };
  18793. pp$1.regexp_eatBackReference = function(state) {
  18794. var start = state.pos;
  18795. if (this.regexp_eatDecimalEscape(state)) {
  18796. var n = state.lastIntValue;
  18797. if (state.switchU) {
  18798. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  18799. if (n > state.maxBackReference) {
  18800. state.maxBackReference = n;
  18801. }
  18802. return true
  18803. }
  18804. if (n <= state.numCapturingParens) {
  18805. return true
  18806. }
  18807. state.pos = start;
  18808. }
  18809. return false
  18810. };
  18811. pp$1.regexp_eatKGroupName = function(state) {
  18812. if (state.eat(0x6B /* k */)) {
  18813. if (this.regexp_eatGroupName(state)) {
  18814. state.backReferenceNames.push(state.lastStringValue);
  18815. return true
  18816. }
  18817. state.raise("Invalid named reference");
  18818. }
  18819. return false
  18820. };
  18821. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  18822. pp$1.regexp_eatCharacterEscape = function(state) {
  18823. return (
  18824. this.regexp_eatControlEscape(state) ||
  18825. this.regexp_eatCControlLetter(state) ||
  18826. this.regexp_eatZero(state) ||
  18827. this.regexp_eatHexEscapeSequence(state) ||
  18828. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  18829. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  18830. this.regexp_eatIdentityEscape(state)
  18831. )
  18832. };
  18833. pp$1.regexp_eatCControlLetter = function(state) {
  18834. var start = state.pos;
  18835. if (state.eat(0x63 /* c */)) {
  18836. if (this.regexp_eatControlLetter(state)) {
  18837. return true
  18838. }
  18839. state.pos = start;
  18840. }
  18841. return false
  18842. };
  18843. pp$1.regexp_eatZero = function(state) {
  18844. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  18845. state.lastIntValue = 0;
  18846. state.advance();
  18847. return true
  18848. }
  18849. return false
  18850. };
  18851. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  18852. pp$1.regexp_eatControlEscape = function(state) {
  18853. var ch = state.current();
  18854. if (ch === 0x74 /* t */) {
  18855. state.lastIntValue = 0x09; /* \t */
  18856. state.advance();
  18857. return true
  18858. }
  18859. if (ch === 0x6E /* n */) {
  18860. state.lastIntValue = 0x0A; /* \n */
  18861. state.advance();
  18862. return true
  18863. }
  18864. if (ch === 0x76 /* v */) {
  18865. state.lastIntValue = 0x0B; /* \v */
  18866. state.advance();
  18867. return true
  18868. }
  18869. if (ch === 0x66 /* f */) {
  18870. state.lastIntValue = 0x0C; /* \f */
  18871. state.advance();
  18872. return true
  18873. }
  18874. if (ch === 0x72 /* r */) {
  18875. state.lastIntValue = 0x0D; /* \r */
  18876. state.advance();
  18877. return true
  18878. }
  18879. return false
  18880. };
  18881. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  18882. pp$1.regexp_eatControlLetter = function(state) {
  18883. var ch = state.current();
  18884. if (isControlLetter(ch)) {
  18885. state.lastIntValue = ch % 0x20;
  18886. state.advance();
  18887. return true
  18888. }
  18889. return false
  18890. };
  18891. function isControlLetter(ch) {
  18892. return (
  18893. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  18894. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  18895. )
  18896. }
  18897. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  18898. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  18899. if ( forceU === void 0 ) forceU = false;
  18900. var start = state.pos;
  18901. var switchU = forceU || state.switchU;
  18902. if (state.eat(0x75 /* u */)) {
  18903. if (this.regexp_eatFixedHexDigits(state, 4)) {
  18904. var lead = state.lastIntValue;
  18905. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  18906. var leadSurrogateEnd = state.pos;
  18907. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  18908. var trail = state.lastIntValue;
  18909. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  18910. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  18911. return true
  18912. }
  18913. }
  18914. state.pos = leadSurrogateEnd;
  18915. state.lastIntValue = lead;
  18916. }
  18917. return true
  18918. }
  18919. if (
  18920. switchU &&
  18921. state.eat(0x7B /* { */) &&
  18922. this.regexp_eatHexDigits(state) &&
  18923. state.eat(0x7D /* } */) &&
  18924. isValidUnicode(state.lastIntValue)
  18925. ) {
  18926. return true
  18927. }
  18928. if (switchU) {
  18929. state.raise("Invalid unicode escape");
  18930. }
  18931. state.pos = start;
  18932. }
  18933. return false
  18934. };
  18935. function isValidUnicode(ch) {
  18936. return ch >= 0 && ch <= 0x10FFFF
  18937. }
  18938. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  18939. pp$1.regexp_eatIdentityEscape = function(state) {
  18940. if (state.switchU) {
  18941. if (this.regexp_eatSyntaxCharacter(state)) {
  18942. return true
  18943. }
  18944. if (state.eat(0x2F /* / */)) {
  18945. state.lastIntValue = 0x2F; /* / */
  18946. return true
  18947. }
  18948. return false
  18949. }
  18950. var ch = state.current();
  18951. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  18952. state.lastIntValue = ch;
  18953. state.advance();
  18954. return true
  18955. }
  18956. return false
  18957. };
  18958. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  18959. pp$1.regexp_eatDecimalEscape = function(state) {
  18960. state.lastIntValue = 0;
  18961. var ch = state.current();
  18962. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  18963. do {
  18964. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  18965. state.advance();
  18966. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  18967. return true
  18968. }
  18969. return false
  18970. };
  18971. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  18972. pp$1.regexp_eatCharacterClassEscape = function(state) {
  18973. var ch = state.current();
  18974. if (isCharacterClassEscape(ch)) {
  18975. state.lastIntValue = -1;
  18976. state.advance();
  18977. return true
  18978. }
  18979. if (
  18980. state.switchU &&
  18981. this.options.ecmaVersion >= 9 &&
  18982. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  18983. ) {
  18984. state.lastIntValue = -1;
  18985. state.advance();
  18986. if (
  18987. state.eat(0x7B /* { */) &&
  18988. this.regexp_eatUnicodePropertyValueExpression(state) &&
  18989. state.eat(0x7D /* } */)
  18990. ) {
  18991. return true
  18992. }
  18993. state.raise("Invalid property name");
  18994. }
  18995. return false
  18996. };
  18997. function isCharacterClassEscape(ch) {
  18998. return (
  18999. ch === 0x64 /* d */ ||
  19000. ch === 0x44 /* D */ ||
  19001. ch === 0x73 /* s */ ||
  19002. ch === 0x53 /* S */ ||
  19003. ch === 0x77 /* w */ ||
  19004. ch === 0x57 /* W */
  19005. )
  19006. }
  19007. // UnicodePropertyValueExpression ::
  19008. // UnicodePropertyName `=` UnicodePropertyValue
  19009. // LoneUnicodePropertyNameOrValue
  19010. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  19011. var start = state.pos;
  19012. // UnicodePropertyName `=` UnicodePropertyValue
  19013. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  19014. var name = state.lastStringValue;
  19015. if (this.regexp_eatUnicodePropertyValue(state)) {
  19016. var value = state.lastStringValue;
  19017. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  19018. return true
  19019. }
  19020. }
  19021. state.pos = start;
  19022. // LoneUnicodePropertyNameOrValue
  19023. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  19024. var nameOrValue = state.lastStringValue;
  19025. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  19026. return true
  19027. }
  19028. return false
  19029. };
  19030. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  19031. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  19032. { state.raise("Invalid property name"); }
  19033. if (!state.unicodeProperties.nonBinary[name].test(value))
  19034. { state.raise("Invalid property value"); }
  19035. };
  19036. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  19037. if (!state.unicodeProperties.binary.test(nameOrValue))
  19038. { state.raise("Invalid property name"); }
  19039. };
  19040. // UnicodePropertyName ::
  19041. // UnicodePropertyNameCharacters
  19042. pp$1.regexp_eatUnicodePropertyName = function(state) {
  19043. var ch = 0;
  19044. state.lastStringValue = "";
  19045. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  19046. state.lastStringValue += codePointToString(ch);
  19047. state.advance();
  19048. }
  19049. return state.lastStringValue !== ""
  19050. };
  19051. function isUnicodePropertyNameCharacter(ch) {
  19052. return isControlLetter(ch) || ch === 0x5F /* _ */
  19053. }
  19054. // UnicodePropertyValue ::
  19055. // UnicodePropertyValueCharacters
  19056. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  19057. var ch = 0;
  19058. state.lastStringValue = "";
  19059. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  19060. state.lastStringValue += codePointToString(ch);
  19061. state.advance();
  19062. }
  19063. return state.lastStringValue !== ""
  19064. };
  19065. function isUnicodePropertyValueCharacter(ch) {
  19066. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  19067. }
  19068. // LoneUnicodePropertyNameOrValue ::
  19069. // UnicodePropertyValueCharacters
  19070. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  19071. return this.regexp_eatUnicodePropertyValue(state)
  19072. };
  19073. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  19074. pp$1.regexp_eatCharacterClass = function(state) {
  19075. if (state.eat(0x5B /* [ */)) {
  19076. state.eat(0x5E /* ^ */);
  19077. this.regexp_classRanges(state);
  19078. if (state.eat(0x5D /* ] */)) {
  19079. return true
  19080. }
  19081. // Unreachable since it threw "unterminated regular expression" error before.
  19082. state.raise("Unterminated character class");
  19083. }
  19084. return false
  19085. };
  19086. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  19087. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  19088. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  19089. pp$1.regexp_classRanges = function(state) {
  19090. while (this.regexp_eatClassAtom(state)) {
  19091. var left = state.lastIntValue;
  19092. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  19093. var right = state.lastIntValue;
  19094. if (state.switchU && (left === -1 || right === -1)) {
  19095. state.raise("Invalid character class");
  19096. }
  19097. if (left !== -1 && right !== -1 && left > right) {
  19098. state.raise("Range out of order in character class");
  19099. }
  19100. }
  19101. }
  19102. };
  19103. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  19104. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  19105. pp$1.regexp_eatClassAtom = function(state) {
  19106. var start = state.pos;
  19107. if (state.eat(0x5C /* \ */)) {
  19108. if (this.regexp_eatClassEscape(state)) {
  19109. return true
  19110. }
  19111. if (state.switchU) {
  19112. // Make the same message as V8.
  19113. var ch$1 = state.current();
  19114. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  19115. state.raise("Invalid class escape");
  19116. }
  19117. state.raise("Invalid escape");
  19118. }
  19119. state.pos = start;
  19120. }
  19121. var ch = state.current();
  19122. if (ch !== 0x5D /* ] */) {
  19123. state.lastIntValue = ch;
  19124. state.advance();
  19125. return true
  19126. }
  19127. return false
  19128. };
  19129. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  19130. pp$1.regexp_eatClassEscape = function(state) {
  19131. var start = state.pos;
  19132. if (state.eat(0x62 /* b */)) {
  19133. state.lastIntValue = 0x08; /* <BS> */
  19134. return true
  19135. }
  19136. if (state.switchU && state.eat(0x2D /* - */)) {
  19137. state.lastIntValue = 0x2D; /* - */
  19138. return true
  19139. }
  19140. if (!state.switchU && state.eat(0x63 /* c */)) {
  19141. if (this.regexp_eatClassControlLetter(state)) {
  19142. return true
  19143. }
  19144. state.pos = start;
  19145. }
  19146. return (
  19147. this.regexp_eatCharacterClassEscape(state) ||
  19148. this.regexp_eatCharacterEscape(state)
  19149. )
  19150. };
  19151. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  19152. pp$1.regexp_eatClassControlLetter = function(state) {
  19153. var ch = state.current();
  19154. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  19155. state.lastIntValue = ch % 0x20;
  19156. state.advance();
  19157. return true
  19158. }
  19159. return false
  19160. };
  19161. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19162. pp$1.regexp_eatHexEscapeSequence = function(state) {
  19163. var start = state.pos;
  19164. if (state.eat(0x78 /* x */)) {
  19165. if (this.regexp_eatFixedHexDigits(state, 2)) {
  19166. return true
  19167. }
  19168. if (state.switchU) {
  19169. state.raise("Invalid escape");
  19170. }
  19171. state.pos = start;
  19172. }
  19173. return false
  19174. };
  19175. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  19176. pp$1.regexp_eatDecimalDigits = function(state) {
  19177. var start = state.pos;
  19178. var ch = 0;
  19179. state.lastIntValue = 0;
  19180. while (isDecimalDigit(ch = state.current())) {
  19181. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19182. state.advance();
  19183. }
  19184. return state.pos !== start
  19185. };
  19186. function isDecimalDigit(ch) {
  19187. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  19188. }
  19189. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  19190. pp$1.regexp_eatHexDigits = function(state) {
  19191. var start = state.pos;
  19192. var ch = 0;
  19193. state.lastIntValue = 0;
  19194. while (isHexDigit(ch = state.current())) {
  19195. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19196. state.advance();
  19197. }
  19198. return state.pos !== start
  19199. };
  19200. function isHexDigit(ch) {
  19201. return (
  19202. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  19203. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  19204. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  19205. )
  19206. }
  19207. function hexToInt(ch) {
  19208. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  19209. return 10 + (ch - 0x41 /* A */)
  19210. }
  19211. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  19212. return 10 + (ch - 0x61 /* a */)
  19213. }
  19214. return ch - 0x30 /* 0 */
  19215. }
  19216. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  19217. // Allows only 0-377(octal) i.e. 0-255(decimal).
  19218. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  19219. if (this.regexp_eatOctalDigit(state)) {
  19220. var n1 = state.lastIntValue;
  19221. if (this.regexp_eatOctalDigit(state)) {
  19222. var n2 = state.lastIntValue;
  19223. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  19224. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  19225. } else {
  19226. state.lastIntValue = n1 * 8 + n2;
  19227. }
  19228. } else {
  19229. state.lastIntValue = n1;
  19230. }
  19231. return true
  19232. }
  19233. return false
  19234. };
  19235. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  19236. pp$1.regexp_eatOctalDigit = function(state) {
  19237. var ch = state.current();
  19238. if (isOctalDigit(ch)) {
  19239. state.lastIntValue = ch - 0x30; /* 0 */
  19240. state.advance();
  19241. return true
  19242. }
  19243. state.lastIntValue = 0;
  19244. return false
  19245. };
  19246. function isOctalDigit(ch) {
  19247. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  19248. }
  19249. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  19250. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  19251. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19252. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  19253. var start = state.pos;
  19254. state.lastIntValue = 0;
  19255. for (var i = 0; i < length; ++i) {
  19256. var ch = state.current();
  19257. if (!isHexDigit(ch)) {
  19258. state.pos = start;
  19259. return false
  19260. }
  19261. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19262. state.advance();
  19263. }
  19264. return true
  19265. };
  19266. // Object type used to represent tokens. Note that normally, tokens
  19267. // simply exist as properties on the parser object. This is only
  19268. // used for the onToken callback and the external tokenizer.
  19269. var Token = function Token(p) {
  19270. this.type = p.type;
  19271. this.value = p.value;
  19272. this.start = p.start;
  19273. this.end = p.end;
  19274. if (p.options.locations)
  19275. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  19276. if (p.options.ranges)
  19277. { this.range = [p.start, p.end]; }
  19278. };
  19279. // ## Tokenizer
  19280. var pp = Parser.prototype;
  19281. // Move to the next token
  19282. pp.next = function(ignoreEscapeSequenceInKeyword) {
  19283. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  19284. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  19285. if (this.options.onToken)
  19286. { this.options.onToken(new Token(this)); }
  19287. this.lastTokEnd = this.end;
  19288. this.lastTokStart = this.start;
  19289. this.lastTokEndLoc = this.endLoc;
  19290. this.lastTokStartLoc = this.startLoc;
  19291. this.nextToken();
  19292. };
  19293. pp.getToken = function() {
  19294. this.next();
  19295. return new Token(this)
  19296. };
  19297. // If we're in an ES6 environment, make parsers iterable
  19298. if (typeof Symbol !== "undefined")
  19299. { pp[Symbol.iterator] = function() {
  19300. var this$1$1 = this;
  19301. return {
  19302. next: function () {
  19303. var token = this$1$1.getToken();
  19304. return {
  19305. done: token.type === types$1.eof,
  19306. value: token
  19307. }
  19308. }
  19309. }
  19310. }; }
  19311. // Toggle strict mode. Re-reads the next number or string to please
  19312. // pedantic tests (`"use strict"; 010;` should fail).
  19313. // Read a single token, updating the parser object's token-related
  19314. // properties.
  19315. pp.nextToken = function() {
  19316. var curContext = this.curContext();
  19317. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  19318. this.start = this.pos;
  19319. if (this.options.locations) { this.startLoc = this.curPosition(); }
  19320. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  19321. if (curContext.override) { return curContext.override(this) }
  19322. else { this.readToken(this.fullCharCodeAtPos()); }
  19323. };
  19324. pp.readToken = function(code) {
  19325. // Identifier or keyword. '\uXXXX' sequences are allowed in
  19326. // identifiers, so '\' also dispatches to that.
  19327. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  19328. { return this.readWord() }
  19329. return this.getTokenFromCode(code)
  19330. };
  19331. pp.fullCharCodeAtPos = function() {
  19332. var code = this.input.charCodeAt(this.pos);
  19333. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  19334. var next = this.input.charCodeAt(this.pos + 1);
  19335. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  19336. };
  19337. pp.skipBlockComment = function() {
  19338. var startLoc = this.options.onComment && this.curPosition();
  19339. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  19340. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  19341. this.pos = end + 2;
  19342. if (this.options.locations) {
  19343. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  19344. ++this.curLine;
  19345. pos = this.lineStart = nextBreak;
  19346. }
  19347. }
  19348. if (this.options.onComment)
  19349. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  19350. startLoc, this.curPosition()); }
  19351. };
  19352. pp.skipLineComment = function(startSkip) {
  19353. var start = this.pos;
  19354. var startLoc = this.options.onComment && this.curPosition();
  19355. var ch = this.input.charCodeAt(this.pos += startSkip);
  19356. while (this.pos < this.input.length && !isNewLine(ch)) {
  19357. ch = this.input.charCodeAt(++this.pos);
  19358. }
  19359. if (this.options.onComment)
  19360. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  19361. startLoc, this.curPosition()); }
  19362. };
  19363. // Called at the start of the parse and after every token. Skips
  19364. // whitespace and comments, and.
  19365. pp.skipSpace = function() {
  19366. loop: while (this.pos < this.input.length) {
  19367. var ch = this.input.charCodeAt(this.pos);
  19368. switch (ch) {
  19369. case 32: case 160: // ' '
  19370. ++this.pos;
  19371. break
  19372. case 13:
  19373. if (this.input.charCodeAt(this.pos + 1) === 10) {
  19374. ++this.pos;
  19375. }
  19376. case 10: case 8232: case 8233:
  19377. ++this.pos;
  19378. if (this.options.locations) {
  19379. ++this.curLine;
  19380. this.lineStart = this.pos;
  19381. }
  19382. break
  19383. case 47: // '/'
  19384. switch (this.input.charCodeAt(this.pos + 1)) {
  19385. case 42: // '*'
  19386. this.skipBlockComment();
  19387. break
  19388. case 47:
  19389. this.skipLineComment(2);
  19390. break
  19391. default:
  19392. break loop
  19393. }
  19394. break
  19395. default:
  19396. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  19397. ++this.pos;
  19398. } else {
  19399. break loop
  19400. }
  19401. }
  19402. }
  19403. };
  19404. // Called at the end of every token. Sets `end`, `val`, and
  19405. // maintains `context` and `exprAllowed`, and skips the space after
  19406. // the token, so that the next one's `start` will point at the
  19407. // right position.
  19408. pp.finishToken = function(type, val) {
  19409. this.end = this.pos;
  19410. if (this.options.locations) { this.endLoc = this.curPosition(); }
  19411. var prevType = this.type;
  19412. this.type = type;
  19413. this.value = val;
  19414. this.updateContext(prevType);
  19415. };
  19416. // ### Token reading
  19417. // This is the function that is called to fetch the next token. It
  19418. // is somewhat obscure, because it works in character codes rather
  19419. // than characters, and because operator parsing has been inlined
  19420. // into it.
  19421. //
  19422. // All in the name of speed.
  19423. //
  19424. pp.readToken_dot = function() {
  19425. var next = this.input.charCodeAt(this.pos + 1);
  19426. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  19427. var next2 = this.input.charCodeAt(this.pos + 2);
  19428. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  19429. this.pos += 3;
  19430. return this.finishToken(types$1.ellipsis)
  19431. } else {
  19432. ++this.pos;
  19433. return this.finishToken(types$1.dot)
  19434. }
  19435. };
  19436. pp.readToken_slash = function() { // '/'
  19437. var next = this.input.charCodeAt(this.pos + 1);
  19438. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  19439. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19440. return this.finishOp(types$1.slash, 1)
  19441. };
  19442. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  19443. var next = this.input.charCodeAt(this.pos + 1);
  19444. var size = 1;
  19445. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  19446. // exponentiation operator ** and **=
  19447. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  19448. ++size;
  19449. tokentype = types$1.starstar;
  19450. next = this.input.charCodeAt(this.pos + 2);
  19451. }
  19452. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  19453. return this.finishOp(tokentype, size)
  19454. };
  19455. pp.readToken_pipe_amp = function(code) { // '|&'
  19456. var next = this.input.charCodeAt(this.pos + 1);
  19457. if (next === code) {
  19458. if (this.options.ecmaVersion >= 12) {
  19459. var next2 = this.input.charCodeAt(this.pos + 2);
  19460. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  19461. }
  19462. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  19463. }
  19464. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19465. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  19466. };
  19467. pp.readToken_caret = function() { // '^'
  19468. var next = this.input.charCodeAt(this.pos + 1);
  19469. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19470. return this.finishOp(types$1.bitwiseXOR, 1)
  19471. };
  19472. pp.readToken_plus_min = function(code) { // '+-'
  19473. var next = this.input.charCodeAt(this.pos + 1);
  19474. if (next === code) {
  19475. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  19476. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  19477. // A `-->` line comment
  19478. this.skipLineComment(3);
  19479. this.skipSpace();
  19480. return this.nextToken()
  19481. }
  19482. return this.finishOp(types$1.incDec, 2)
  19483. }
  19484. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19485. return this.finishOp(types$1.plusMin, 1)
  19486. };
  19487. pp.readToken_lt_gt = function(code) { // '<>'
  19488. var next = this.input.charCodeAt(this.pos + 1);
  19489. var size = 1;
  19490. if (next === code) {
  19491. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  19492. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  19493. return this.finishOp(types$1.bitShift, size)
  19494. }
  19495. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  19496. this.input.charCodeAt(this.pos + 3) === 45) {
  19497. // `<!--`, an XML-style comment that should be interpreted as a line comment
  19498. this.skipLineComment(4);
  19499. this.skipSpace();
  19500. return this.nextToken()
  19501. }
  19502. if (next === 61) { size = 2; }
  19503. return this.finishOp(types$1.relational, size)
  19504. };
  19505. pp.readToken_eq_excl = function(code) { // '=!'
  19506. var next = this.input.charCodeAt(this.pos + 1);
  19507. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  19508. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  19509. this.pos += 2;
  19510. return this.finishToken(types$1.arrow)
  19511. }
  19512. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  19513. };
  19514. pp.readToken_question = function() { // '?'
  19515. var ecmaVersion = this.options.ecmaVersion;
  19516. if (ecmaVersion >= 11) {
  19517. var next = this.input.charCodeAt(this.pos + 1);
  19518. if (next === 46) {
  19519. var next2 = this.input.charCodeAt(this.pos + 2);
  19520. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  19521. }
  19522. if (next === 63) {
  19523. if (ecmaVersion >= 12) {
  19524. var next2$1 = this.input.charCodeAt(this.pos + 2);
  19525. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  19526. }
  19527. return this.finishOp(types$1.coalesce, 2)
  19528. }
  19529. }
  19530. return this.finishOp(types$1.question, 1)
  19531. };
  19532. pp.readToken_numberSign = function() { // '#'
  19533. var ecmaVersion = this.options.ecmaVersion;
  19534. var code = 35; // '#'
  19535. if (ecmaVersion >= 13) {
  19536. ++this.pos;
  19537. code = this.fullCharCodeAtPos();
  19538. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  19539. return this.finishToken(types$1.privateId, this.readWord1())
  19540. }
  19541. }
  19542. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19543. };
  19544. pp.getTokenFromCode = function(code) {
  19545. switch (code) {
  19546. // The interpretation of a dot depends on whether it is followed
  19547. // by a digit or another two dots.
  19548. case 46: // '.'
  19549. return this.readToken_dot()
  19550. // Punctuation tokens.
  19551. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  19552. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  19553. case 59: ++this.pos; return this.finishToken(types$1.semi)
  19554. case 44: ++this.pos; return this.finishToken(types$1.comma)
  19555. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  19556. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  19557. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  19558. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  19559. case 58: ++this.pos; return this.finishToken(types$1.colon)
  19560. case 96: // '`'
  19561. if (this.options.ecmaVersion < 6) { break }
  19562. ++this.pos;
  19563. return this.finishToken(types$1.backQuote)
  19564. case 48: // '0'
  19565. var next = this.input.charCodeAt(this.pos + 1);
  19566. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  19567. if (this.options.ecmaVersion >= 6) {
  19568. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  19569. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  19570. }
  19571. // Anything else beginning with a digit is an integer, octal
  19572. // number, or float.
  19573. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  19574. return this.readNumber(false)
  19575. // Quotes produce strings.
  19576. case 34: case 39: // '"', "'"
  19577. return this.readString(code)
  19578. // Operators are parsed inline in tiny state machines. '=' (61) is
  19579. // often referred to. `finishOp` simply skips the amount of
  19580. // characters it is given as second argument, and returns a token
  19581. // of the type given by its first argument.
  19582. case 47: // '/'
  19583. return this.readToken_slash()
  19584. case 37: case 42: // '%*'
  19585. return this.readToken_mult_modulo_exp(code)
  19586. case 124: case 38: // '|&'
  19587. return this.readToken_pipe_amp(code)
  19588. case 94: // '^'
  19589. return this.readToken_caret()
  19590. case 43: case 45: // '+-'
  19591. return this.readToken_plus_min(code)
  19592. case 60: case 62: // '<>'
  19593. return this.readToken_lt_gt(code)
  19594. case 61: case 33: // '=!'
  19595. return this.readToken_eq_excl(code)
  19596. case 63: // '?'
  19597. return this.readToken_question()
  19598. case 126: // '~'
  19599. return this.finishOp(types$1.prefix, 1)
  19600. case 35: // '#'
  19601. return this.readToken_numberSign()
  19602. }
  19603. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19604. };
  19605. pp.finishOp = function(type, size) {
  19606. var str = this.input.slice(this.pos, this.pos + size);
  19607. this.pos += size;
  19608. return this.finishToken(type, str)
  19609. };
  19610. pp.readRegexp = function() {
  19611. var escaped, inClass, start = this.pos;
  19612. for (;;) {
  19613. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  19614. var ch = this.input.charAt(this.pos);
  19615. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  19616. if (!escaped) {
  19617. if (ch === "[") { inClass = true; }
  19618. else if (ch === "]" && inClass) { inClass = false; }
  19619. else if (ch === "/" && !inClass) { break }
  19620. escaped = ch === "\\";
  19621. } else { escaped = false; }
  19622. ++this.pos;
  19623. }
  19624. var pattern = this.input.slice(start, this.pos);
  19625. ++this.pos;
  19626. var flagsStart = this.pos;
  19627. var flags = this.readWord1();
  19628. if (this.containsEsc) { this.unexpected(flagsStart); }
  19629. // Validate pattern
  19630. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  19631. state.reset(start, pattern, flags);
  19632. this.validateRegExpFlags(state);
  19633. this.validateRegExpPattern(state);
  19634. // Create Literal#value property value.
  19635. var value = null;
  19636. try {
  19637. value = new RegExp(pattern, flags);
  19638. } catch (e) {
  19639. // ESTree requires null if it failed to instantiate RegExp object.
  19640. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  19641. }
  19642. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  19643. };
  19644. // Read an integer in the given radix. Return null if zero digits
  19645. // were read, the integer value otherwise. When `len` is given, this
  19646. // will return `null` unless the integer has exactly `len` digits.
  19647. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  19648. // `len` is used for character escape sequences. In that case, disallow separators.
  19649. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  19650. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  19651. // and isn't fraction part nor exponent part. In that case, if the first digit
  19652. // is zero then disallow separators.
  19653. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  19654. var start = this.pos, total = 0, lastCode = 0;
  19655. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  19656. var code = this.input.charCodeAt(this.pos), val = (void 0);
  19657. if (allowSeparators && code === 95) {
  19658. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  19659. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  19660. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  19661. lastCode = code;
  19662. continue
  19663. }
  19664. if (code >= 97) { val = code - 97 + 10; } // a
  19665. else if (code >= 65) { val = code - 65 + 10; } // A
  19666. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  19667. else { val = Infinity; }
  19668. if (val >= radix) { break }
  19669. lastCode = code;
  19670. total = total * radix + val;
  19671. }
  19672. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  19673. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  19674. return total
  19675. };
  19676. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  19677. if (isLegacyOctalNumericLiteral) {
  19678. return parseInt(str, 8)
  19679. }
  19680. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  19681. return parseFloat(str.replace(/_/g, ""))
  19682. }
  19683. function stringToBigInt(str) {
  19684. if (typeof BigInt !== "function") {
  19685. return null
  19686. }
  19687. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  19688. return BigInt(str.replace(/_/g, ""))
  19689. }
  19690. pp.readRadixNumber = function(radix) {
  19691. var start = this.pos;
  19692. this.pos += 2; // 0x
  19693. var val = this.readInt(radix);
  19694. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  19695. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  19696. val = stringToBigInt(this.input.slice(start, this.pos));
  19697. ++this.pos;
  19698. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19699. return this.finishToken(types$1.num, val)
  19700. };
  19701. // Read an integer, octal integer, or floating-point number.
  19702. pp.readNumber = function(startsWithDot) {
  19703. var start = this.pos;
  19704. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  19705. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  19706. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  19707. var next = this.input.charCodeAt(this.pos);
  19708. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  19709. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  19710. ++this.pos;
  19711. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19712. return this.finishToken(types$1.num, val$1)
  19713. }
  19714. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  19715. if (next === 46 && !octal) { // '.'
  19716. ++this.pos;
  19717. this.readInt(10);
  19718. next = this.input.charCodeAt(this.pos);
  19719. }
  19720. if ((next === 69 || next === 101) && !octal) { // 'eE'
  19721. next = this.input.charCodeAt(++this.pos);
  19722. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  19723. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  19724. }
  19725. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19726. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  19727. return this.finishToken(types$1.num, val)
  19728. };
  19729. // Read a string value, interpreting backslash-escapes.
  19730. pp.readCodePoint = function() {
  19731. var ch = this.input.charCodeAt(this.pos), code;
  19732. if (ch === 123) { // '{'
  19733. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  19734. var codePos = ++this.pos;
  19735. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  19736. ++this.pos;
  19737. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  19738. } else {
  19739. code = this.readHexChar(4);
  19740. }
  19741. return code
  19742. };
  19743. pp.readString = function(quote) {
  19744. var out = "", chunkStart = ++this.pos;
  19745. for (;;) {
  19746. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  19747. var ch = this.input.charCodeAt(this.pos);
  19748. if (ch === quote) { break }
  19749. if (ch === 92) { // '\'
  19750. out += this.input.slice(chunkStart, this.pos);
  19751. out += this.readEscapedChar(false);
  19752. chunkStart = this.pos;
  19753. } else if (ch === 0x2028 || ch === 0x2029) {
  19754. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  19755. ++this.pos;
  19756. if (this.options.locations) {
  19757. this.curLine++;
  19758. this.lineStart = this.pos;
  19759. }
  19760. } else {
  19761. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  19762. ++this.pos;
  19763. }
  19764. }
  19765. out += this.input.slice(chunkStart, this.pos++);
  19766. return this.finishToken(types$1.string, out)
  19767. };
  19768. // Reads template string tokens.
  19769. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  19770. pp.tryReadTemplateToken = function() {
  19771. this.inTemplateElement = true;
  19772. try {
  19773. this.readTmplToken();
  19774. } catch (err) {
  19775. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  19776. this.readInvalidTemplateToken();
  19777. } else {
  19778. throw err
  19779. }
  19780. }
  19781. this.inTemplateElement = false;
  19782. };
  19783. pp.invalidStringToken = function(position, message) {
  19784. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  19785. throw INVALID_TEMPLATE_ESCAPE_ERROR
  19786. } else {
  19787. this.raise(position, message);
  19788. }
  19789. };
  19790. pp.readTmplToken = function() {
  19791. var out = "", chunkStart = this.pos;
  19792. for (;;) {
  19793. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  19794. var ch = this.input.charCodeAt(this.pos);
  19795. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  19796. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  19797. if (ch === 36) {
  19798. this.pos += 2;
  19799. return this.finishToken(types$1.dollarBraceL)
  19800. } else {
  19801. ++this.pos;
  19802. return this.finishToken(types$1.backQuote)
  19803. }
  19804. }
  19805. out += this.input.slice(chunkStart, this.pos);
  19806. return this.finishToken(types$1.template, out)
  19807. }
  19808. if (ch === 92) { // '\'
  19809. out += this.input.slice(chunkStart, this.pos);
  19810. out += this.readEscapedChar(true);
  19811. chunkStart = this.pos;
  19812. } else if (isNewLine(ch)) {
  19813. out += this.input.slice(chunkStart, this.pos);
  19814. ++this.pos;
  19815. switch (ch) {
  19816. case 13:
  19817. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  19818. case 10:
  19819. out += "\n";
  19820. break
  19821. default:
  19822. out += String.fromCharCode(ch);
  19823. break
  19824. }
  19825. if (this.options.locations) {
  19826. ++this.curLine;
  19827. this.lineStart = this.pos;
  19828. }
  19829. chunkStart = this.pos;
  19830. } else {
  19831. ++this.pos;
  19832. }
  19833. }
  19834. };
  19835. // Reads a template token to search for the end, without validating any escape sequences
  19836. pp.readInvalidTemplateToken = function() {
  19837. for (; this.pos < this.input.length; this.pos++) {
  19838. switch (this.input[this.pos]) {
  19839. case "\\":
  19840. ++this.pos;
  19841. break
  19842. case "$":
  19843. if (this.input[this.pos + 1] !== "{") {
  19844. break
  19845. }
  19846. // falls through
  19847. case "`":
  19848. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  19849. // no default
  19850. }
  19851. }
  19852. this.raise(this.start, "Unterminated template");
  19853. };
  19854. // Used to read escaped characters
  19855. pp.readEscapedChar = function(inTemplate) {
  19856. var ch = this.input.charCodeAt(++this.pos);
  19857. ++this.pos;
  19858. switch (ch) {
  19859. case 110: return "\n" // 'n' -> '\n'
  19860. case 114: return "\r" // 'r' -> '\r'
  19861. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  19862. case 117: return codePointToString(this.readCodePoint()) // 'u'
  19863. case 116: return "\t" // 't' -> '\t'
  19864. case 98: return "\b" // 'b' -> '\b'
  19865. case 118: return "\u000b" // 'v' -> '\u000b'
  19866. case 102: return "\f" // 'f' -> '\f'
  19867. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  19868. case 10: // ' \n'
  19869. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  19870. return ""
  19871. case 56:
  19872. case 57:
  19873. if (this.strict) {
  19874. this.invalidStringToken(
  19875. this.pos - 1,
  19876. "Invalid escape sequence"
  19877. );
  19878. }
  19879. if (inTemplate) {
  19880. var codePos = this.pos - 1;
  19881. this.invalidStringToken(
  19882. codePos,
  19883. "Invalid escape sequence in template string"
  19884. );
  19885. return null
  19886. }
  19887. default:
  19888. if (ch >= 48 && ch <= 55) {
  19889. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  19890. var octal = parseInt(octalStr, 8);
  19891. if (octal > 255) {
  19892. octalStr = octalStr.slice(0, -1);
  19893. octal = parseInt(octalStr, 8);
  19894. }
  19895. this.pos += octalStr.length - 1;
  19896. ch = this.input.charCodeAt(this.pos);
  19897. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  19898. this.invalidStringToken(
  19899. this.pos - 1 - octalStr.length,
  19900. inTemplate
  19901. ? "Octal literal in template string"
  19902. : "Octal literal in strict mode"
  19903. );
  19904. }
  19905. return String.fromCharCode(octal)
  19906. }
  19907. if (isNewLine(ch)) {
  19908. // Unicode new line characters after \ get removed from output in both
  19909. // template literals and strings
  19910. return ""
  19911. }
  19912. return String.fromCharCode(ch)
  19913. }
  19914. };
  19915. // Used to read character escape sequences ('\x', '\u', '\U').
  19916. pp.readHexChar = function(len) {
  19917. var codePos = this.pos;
  19918. var n = this.readInt(16, len);
  19919. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  19920. return n
  19921. };
  19922. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  19923. // to whether the word contained a '\u' escape.
  19924. //
  19925. // Incrementally adds only escaped chars, adding other chunks as-is
  19926. // as a micro-optimization.
  19927. pp.readWord1 = function() {
  19928. this.containsEsc = false;
  19929. var word = "", first = true, chunkStart = this.pos;
  19930. var astral = this.options.ecmaVersion >= 6;
  19931. while (this.pos < this.input.length) {
  19932. var ch = this.fullCharCodeAtPos();
  19933. if (isIdentifierChar(ch, astral)) {
  19934. this.pos += ch <= 0xffff ? 1 : 2;
  19935. } else if (ch === 92) { // "\"
  19936. this.containsEsc = true;
  19937. word += this.input.slice(chunkStart, this.pos);
  19938. var escStart = this.pos;
  19939. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  19940. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  19941. ++this.pos;
  19942. var esc = this.readCodePoint();
  19943. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  19944. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  19945. word += codePointToString(esc);
  19946. chunkStart = this.pos;
  19947. } else {
  19948. break
  19949. }
  19950. first = false;
  19951. }
  19952. return word + this.input.slice(chunkStart, this.pos)
  19953. };
  19954. // Read an identifier or keyword token. Will check for reserved
  19955. // words when necessary.
  19956. pp.readWord = function() {
  19957. var word = this.readWord1();
  19958. var type = types$1.name;
  19959. if (this.keywords.test(word)) {
  19960. type = keywords[word];
  19961. }
  19962. return this.finishToken(type, word)
  19963. };
  19964. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  19965. var version = "8.7.1";
  19966. Parser.acorn = {
  19967. Parser: Parser,
  19968. version: version,
  19969. defaultOptions: defaultOptions,
  19970. Position: Position,
  19971. SourceLocation: SourceLocation,
  19972. getLineInfo: getLineInfo,
  19973. Node: Node,
  19974. TokenType: TokenType,
  19975. tokTypes: types$1,
  19976. keywordTypes: keywords,
  19977. TokContext: TokContext,
  19978. tokContexts: types,
  19979. isIdentifierChar: isIdentifierChar,
  19980. isIdentifierStart: isIdentifierStart,
  19981. Token: Token,
  19982. isNewLine: isNewLine,
  19983. lineBreak: lineBreak,
  19984. lineBreakG: lineBreakG,
  19985. nonASCIIwhitespace: nonASCIIwhitespace
  19986. };
  19987. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  19988. let skipped = null;
  19989. let replaceContext = null;
  19990. if (skip) {
  19991. skipped = new Set();
  19992. for (const skippedCall of skip) {
  19993. if (source === skippedCall.source && importer === skippedCall.importer) {
  19994. skipped.add(skippedCall.plugin);
  19995. }
  19996. }
  19997. replaceContext = (pluginContext, plugin) => ({
  19998. ...pluginContext,
  19999. resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
  20000. return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20001. }
  20002. });
  20003. }
  20004. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
  20005. }
  20006. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20007. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
  20008. if (pluginResult != null)
  20009. return pluginResult;
  20010. // external modules (non-entry modules that start with neither '.' or '/')
  20011. // are skipped at this stage.
  20012. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  20013. return null;
  20014. // `resolve` processes paths from right to left, prepending them until an
  20015. // absolute path is created. Absolute importees therefore shortcircuit the
  20016. // resolve call and require no special handing on our part.
  20017. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20018. return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
  20019. }
  20020. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  20021. var _a, _b;
  20022. return ((_b = (_a = (await findFile(file, preserveSymlinks))) !== null && _a !== void 0 ? _a : (await findFile(file + '.mjs', preserveSymlinks))) !== null && _b !== void 0 ? _b : (await findFile(file + '.js', preserveSymlinks)));
  20023. }
  20024. async function findFile(file, preserveSymlinks) {
  20025. try {
  20026. const stats = await promises.lstat(file);
  20027. if (!preserveSymlinks && stats.isSymbolicLink())
  20028. return await findFile(await promises.realpath(file), preserveSymlinks);
  20029. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20030. // check case
  20031. const name = basename(file);
  20032. const files = await promises.readdir(dirname(file));
  20033. if (files.includes(name))
  20034. return file;
  20035. }
  20036. }
  20037. catch (_a) {
  20038. // suppress
  20039. }
  20040. }
  20041. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  20042. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  20043. function throwPluginError(err, plugin, { hook, id } = {}) {
  20044. if (typeof err === 'string')
  20045. err = { message: err };
  20046. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  20047. err.pluginCode = err.code;
  20048. }
  20049. err.code = Errors.PLUGIN_ERROR;
  20050. err.plugin = plugin;
  20051. if (hook) {
  20052. err.hook = hook;
  20053. }
  20054. if (id) {
  20055. err.id = id;
  20056. }
  20057. return error(err);
  20058. }
  20059. const deprecatedHooks = [
  20060. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  20061. ];
  20062. function warnDeprecatedHooks(plugins, options) {
  20063. for (const { active, deprecated, replacement } of deprecatedHooks) {
  20064. for (const plugin of plugins) {
  20065. if (deprecated in plugin) {
  20066. warnDeprecation({
  20067. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  20068. plugin: plugin.name
  20069. }, active, options);
  20070. }
  20071. }
  20072. }
  20073. }
  20074. function createPluginCache(cache) {
  20075. return {
  20076. delete(id) {
  20077. return delete cache[id];
  20078. },
  20079. get(id) {
  20080. const item = cache[id];
  20081. if (!item)
  20082. return undefined;
  20083. item[0] = 0;
  20084. return item[1];
  20085. },
  20086. has(id) {
  20087. const item = cache[id];
  20088. if (!item)
  20089. return false;
  20090. item[0] = 0;
  20091. return true;
  20092. },
  20093. set(id, value) {
  20094. cache[id] = [0, value];
  20095. }
  20096. };
  20097. }
  20098. function getTrackedPluginCache(pluginCache, onUse) {
  20099. return {
  20100. delete(id) {
  20101. onUse();
  20102. return pluginCache.delete(id);
  20103. },
  20104. get(id) {
  20105. onUse();
  20106. return pluginCache.get(id);
  20107. },
  20108. has(id) {
  20109. onUse();
  20110. return pluginCache.has(id);
  20111. },
  20112. set(id, value) {
  20113. onUse();
  20114. return pluginCache.set(id, value);
  20115. }
  20116. };
  20117. }
  20118. const NO_CACHE = {
  20119. delete() {
  20120. return false;
  20121. },
  20122. get() {
  20123. return undefined;
  20124. },
  20125. has() {
  20126. return false;
  20127. },
  20128. set() { }
  20129. };
  20130. function uncacheablePluginError(pluginName) {
  20131. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20132. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  20133. return error({
  20134. code: 'ANONYMOUS_PLUGIN_CACHE',
  20135. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  20136. });
  20137. }
  20138. return error({
  20139. code: 'DUPLICATE_PLUGIN_NAME',
  20140. message: `The plugin name ${pluginName} 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).`
  20141. });
  20142. }
  20143. function getCacheForUncacheablePlugin(pluginName) {
  20144. return {
  20145. delete() {
  20146. return uncacheablePluginError(pluginName);
  20147. },
  20148. get() {
  20149. return uncacheablePluginError(pluginName);
  20150. },
  20151. has() {
  20152. return uncacheablePluginError(pluginName);
  20153. },
  20154. set() {
  20155. return uncacheablePluginError(pluginName);
  20156. }
  20157. };
  20158. }
  20159. async function transform(source, module, pluginDriver, warn) {
  20160. const id = module.id;
  20161. const sourcemapChain = [];
  20162. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20163. const originalCode = source.code;
  20164. let ast = source.ast;
  20165. const transformDependencies = [];
  20166. const emittedFiles = [];
  20167. let customTransformCache = false;
  20168. const useCustomTransformCache = () => (customTransformCache = true);
  20169. let pluginName = '';
  20170. const curSource = source.code;
  20171. function transformReducer(previousCode, result, plugin) {
  20172. let code;
  20173. let map;
  20174. if (typeof result === 'string') {
  20175. code = result;
  20176. }
  20177. else if (result && typeof result === 'object') {
  20178. module.updateOptions(result);
  20179. if (result.code == null) {
  20180. if (result.map || result.ast) {
  20181. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  20182. }
  20183. return previousCode;
  20184. }
  20185. ({ code, map, ast } = result);
  20186. }
  20187. else {
  20188. return previousCode;
  20189. }
  20190. // strict null check allows 'null' maps to not be pushed to the chain,
  20191. // while 'undefined' gets the missing map warning
  20192. if (map !== null) {
  20193. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20194. missing: true,
  20195. plugin: plugin.name
  20196. });
  20197. }
  20198. return code;
  20199. }
  20200. let code;
  20201. try {
  20202. code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  20203. pluginName = plugin.name;
  20204. return {
  20205. ...pluginContext,
  20206. addWatchFile(id) {
  20207. transformDependencies.push(id);
  20208. pluginContext.addWatchFile(id);
  20209. },
  20210. cache: customTransformCache
  20211. ? pluginContext.cache
  20212. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20213. emitAsset(name, source) {
  20214. emittedFiles.push({ name, source, type: 'asset' });
  20215. return pluginContext.emitAsset(name, source);
  20216. },
  20217. emitChunk(id, options) {
  20218. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  20219. return pluginContext.emitChunk(id, options);
  20220. },
  20221. emitFile(emittedFile) {
  20222. emittedFiles.push(emittedFile);
  20223. return pluginDriver.emitFile(emittedFile);
  20224. },
  20225. error(err, pos) {
  20226. if (typeof err === 'string')
  20227. err = { message: err };
  20228. if (pos)
  20229. augmentCodeLocation(err, pos, curSource, id);
  20230. err.id = id;
  20231. err.hook = 'transform';
  20232. return pluginContext.error(err);
  20233. },
  20234. getCombinedSourcemap() {
  20235. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  20236. if (!combinedMap) {
  20237. const magicString = new MagicString(originalCode);
  20238. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20239. }
  20240. if (originalSourcemap !== combinedMap) {
  20241. originalSourcemap = combinedMap;
  20242. sourcemapChain.length = 0;
  20243. }
  20244. return new SourceMap({
  20245. ...combinedMap,
  20246. file: null,
  20247. sourcesContent: combinedMap.sourcesContent
  20248. });
  20249. },
  20250. setAssetSource() {
  20251. return this.error({
  20252. code: 'INVALID_SETASSETSOURCE',
  20253. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  20254. });
  20255. },
  20256. warn(warning, pos) {
  20257. if (typeof warning === 'string')
  20258. warning = { message: warning };
  20259. if (pos)
  20260. augmentCodeLocation(warning, pos, curSource, id);
  20261. warning.id = id;
  20262. warning.hook = 'transform';
  20263. pluginContext.warn(warning);
  20264. }
  20265. };
  20266. });
  20267. }
  20268. catch (err) {
  20269. throwPluginError(err, pluginName, { hook: 'transform', id });
  20270. }
  20271. if (!customTransformCache) {
  20272. // files emitted by a transform hook need to be emitted again if the hook is skipped
  20273. if (emittedFiles.length)
  20274. module.transformFiles = emittedFiles;
  20275. }
  20276. return {
  20277. ast,
  20278. code,
  20279. customTransformCache,
  20280. originalCode,
  20281. originalSourcemap,
  20282. sourcemapChain,
  20283. transformDependencies
  20284. };
  20285. }
  20286. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20287. class ModuleLoader {
  20288. constructor(graph, modulesById, options, pluginDriver) {
  20289. this.graph = graph;
  20290. this.modulesById = modulesById;
  20291. this.options = options;
  20292. this.pluginDriver = pluginDriver;
  20293. this.implicitEntryModules = new Set();
  20294. this.indexedEntryModules = [];
  20295. this.latestLoadModulesPromise = Promise.resolve();
  20296. this.moduleLoadPromises = new Map();
  20297. this.modulesWithLoadedDependencies = new Set();
  20298. this.nextChunkNamePriority = 0;
  20299. this.nextEntryModuleIndex = 0;
  20300. this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
  20301. return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20302. ? false
  20303. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
  20304. };
  20305. this.hasModuleSideEffects = options.treeshake
  20306. ? options.treeshake.moduleSideEffects
  20307. : () => true;
  20308. }
  20309. async addAdditionalModules(unresolvedModules) {
  20310. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  20311. await this.awaitLoadModulesPromise();
  20312. return result;
  20313. }
  20314. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20315. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20316. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20317. const firstChunkNamePriority = this.nextChunkNamePriority;
  20318. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20319. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20320. for (let index = 0; index < entryModules.length; index++) {
  20321. const entryModule = entryModules[index];
  20322. entryModule.isUserDefinedEntryPoint =
  20323. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20324. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20325. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20326. if (!existingIndexedModule) {
  20327. this.indexedEntryModules.push({
  20328. index: firstEntryModuleIndex + index,
  20329. module: entryModule
  20330. });
  20331. }
  20332. else {
  20333. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20334. }
  20335. }
  20336. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20337. return entryModules;
  20338. }));
  20339. await this.awaitLoadModulesPromise();
  20340. return {
  20341. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20342. implicitEntryModules: [...this.implicitEntryModules],
  20343. newEntryModules
  20344. };
  20345. }
  20346. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20347. const unresolvedModule = {
  20348. fileName: fileName || null,
  20349. id,
  20350. importer,
  20351. name: name || null
  20352. };
  20353. const module = implicitlyLoadedAfterOneOf
  20354. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20355. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20356. if (preserveSignature != null) {
  20357. module.preserveSignature = preserveSignature;
  20358. }
  20359. return module;
  20360. }
  20361. async preloadModule(resolvedId) {
  20362. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20363. return module.info;
  20364. }
  20365. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20366. const chunkNamePriority = this.nextChunkNamePriority++;
  20367. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20368. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20369. if (!entryModule.info.isEntry) {
  20370. this.implicitEntryModules.add(entryModule);
  20371. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20372. for (const module of implicitlyLoadedAfterModules) {
  20373. entryModule.implicitlyLoadedAfter.add(module);
  20374. }
  20375. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20376. dependant.implicitlyLoadedBefore.add(entryModule);
  20377. }
  20378. }
  20379. return entryModule;
  20380. }));
  20381. }
  20382. async addModuleSource(id, importer, module) {
  20383. timeStart('load modules', 3);
  20384. let source;
  20385. try {
  20386. source = await this.graph.fileOperationQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await promises.readFile(id, 'utf8')); });
  20387. }
  20388. catch (err) {
  20389. timeEnd('load modules', 3);
  20390. let msg = `Could not load ${id}`;
  20391. if (importer)
  20392. msg += ` (imported by ${relativeId(importer)})`;
  20393. msg += `: ${err.message}`;
  20394. err.message = msg;
  20395. throw err;
  20396. }
  20397. timeEnd('load modules', 3);
  20398. const sourceDescription = typeof source === 'string'
  20399. ? { code: source }
  20400. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20401. ? source
  20402. : error(errBadLoader(id));
  20403. const cachedModule = this.graph.cachedModules.get(id);
  20404. if (cachedModule &&
  20405. !cachedModule.customTransformCache &&
  20406. cachedModule.originalCode === sourceDescription.code &&
  20407. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20408. {
  20409. ast: cachedModule.ast,
  20410. code: cachedModule.code,
  20411. id: cachedModule.id,
  20412. meta: cachedModule.meta,
  20413. moduleSideEffects: cachedModule.moduleSideEffects,
  20414. resolvedSources: cachedModule.resolvedIds,
  20415. syntheticNamedExports: cachedModule.syntheticNamedExports
  20416. }
  20417. ]))) {
  20418. if (cachedModule.transformFiles) {
  20419. for (const emittedFile of cachedModule.transformFiles)
  20420. this.pluginDriver.emitFile(emittedFile);
  20421. }
  20422. module.setSource(cachedModule);
  20423. }
  20424. else {
  20425. module.updateOptions(sourceDescription);
  20426. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  20427. }
  20428. }
  20429. async awaitLoadModulesPromise() {
  20430. let startingPromise;
  20431. do {
  20432. startingPromise = this.latestLoadModulesPromise;
  20433. await startingPromise;
  20434. } while (startingPromise !== this.latestLoadModulesPromise);
  20435. }
  20436. extendLoadModulesPromise(loadNewModulesPromise) {
  20437. this.latestLoadModulesPromise = Promise.all([
  20438. loadNewModulesPromise,
  20439. this.latestLoadModulesPromise
  20440. ]);
  20441. this.latestLoadModulesPromise.catch(() => {
  20442. /* Avoid unhandled Promise rejections */
  20443. });
  20444. return loadNewModulesPromise;
  20445. }
  20446. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20447. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20448. if (resolvedId === null)
  20449. return null;
  20450. if (typeof resolvedId === 'string') {
  20451. dynamicImport.resolution = resolvedId;
  20452. return null;
  20453. }
  20454. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20455. })));
  20456. for (const dependency of dependencies) {
  20457. if (dependency) {
  20458. module.dynamicDependencies.add(dependency);
  20459. dependency.dynamicImporters.push(module.id);
  20460. }
  20461. }
  20462. }
  20463. // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
  20464. // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
  20465. // Otherwise it returns immediately.
  20466. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20467. const existingModule = this.modulesById.get(id);
  20468. if (existingModule instanceof Module) {
  20469. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20470. return existingModule;
  20471. }
  20472. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  20473. this.modulesById.set(id, module);
  20474. this.graph.watchFiles[id] = true;
  20475. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20476. this.getResolveStaticDependencyPromises(module),
  20477. this.getResolveDynamicImportPromises(module),
  20478. loadAndResolveDependenciesPromise
  20479. ]);
  20480. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20481. loadAndResolveDependenciesPromise.catch(() => {
  20482. /* avoid unhandled promise rejections */
  20483. });
  20484. this.moduleLoadPromises.set(module, loadPromise);
  20485. const resolveDependencyPromises = await loadPromise;
  20486. if (!isPreload) {
  20487. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20488. }
  20489. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20490. await loadAndResolveDependenciesPromise;
  20491. }
  20492. return module;
  20493. }
  20494. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20495. if (this.modulesWithLoadedDependencies.has(module)) {
  20496. return;
  20497. }
  20498. this.modulesWithLoadedDependencies.add(module);
  20499. await Promise.all([
  20500. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20501. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20502. ]);
  20503. module.linkImports();
  20504. // To handle errors when resolving dependencies or in moduleParsed
  20505. await loadAndResolveDependenciesPromise;
  20506. }
  20507. fetchResolvedDependency(source, importer, resolvedId) {
  20508. if (resolvedId.external) {
  20509. const { external, id, moduleSideEffects, meta } = resolvedId;
  20510. if (!this.modulesById.has(id)) {
  20511. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  20512. }
  20513. const externalModule = this.modulesById.get(id);
  20514. if (!(externalModule instanceof ExternalModule)) {
  20515. return error(errInternalIdCannotBeExternal(source, importer));
  20516. }
  20517. return Promise.resolve(externalModule);
  20518. }
  20519. return this.fetchModule(resolvedId, importer, false, false);
  20520. }
  20521. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20522. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20523. module.dependencies.add(dependency);
  20524. dependency.importers.push(module.id);
  20525. }
  20526. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20527. for (const dependency of module.dependencies) {
  20528. if (dependency instanceof Module) {
  20529. dependency.importedFromNotTreeshaken = true;
  20530. }
  20531. }
  20532. }
  20533. }
  20534. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20535. const { makeAbsoluteExternalsRelative } = this.options;
  20536. if (resolveIdResult) {
  20537. if (typeof resolveIdResult === 'object') {
  20538. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20539. return {
  20540. ...resolveIdResult,
  20541. external: external &&
  20542. (external === 'relative' ||
  20543. !isAbsolute(resolveIdResult.id) ||
  20544. (external === true &&
  20545. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20546. 'absolute')
  20547. };
  20548. }
  20549. const external = this.options.external(resolveIdResult, importer, true);
  20550. return {
  20551. external: external &&
  20552. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20553. 'absolute'),
  20554. id: external && makeAbsoluteExternalsRelative
  20555. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20556. : resolveIdResult
  20557. };
  20558. }
  20559. const id = makeAbsoluteExternalsRelative
  20560. ? normalizeRelativeExternalId(source, importer)
  20561. : source;
  20562. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20563. return null;
  20564. }
  20565. return {
  20566. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20567. id
  20568. };
  20569. }
  20570. getResolveDynamicImportPromises(module) {
  20571. return module.dynamicImports.map(async (dynamicImport) => {
  20572. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  20573. ? dynamicImport.argument
  20574. : dynamicImport.argument.esTreeNode, module.id);
  20575. if (resolvedId && typeof resolvedId === 'object') {
  20576. dynamicImport.id = resolvedId.id;
  20577. }
  20578. return [dynamicImport, resolvedId];
  20579. });
  20580. }
  20581. getResolveStaticDependencyPromises(module) {
  20582. return Array.from(module.sources, async (source) => [
  20583. source,
  20584. (module.resolvedIds[source] =
  20585. module.resolvedIds[source] ||
  20586. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
  20587. ]);
  20588. }
  20589. getResolvedIdWithDefaults(resolvedId) {
  20590. var _a, _b;
  20591. if (!resolvedId) {
  20592. return null;
  20593. }
  20594. const external = resolvedId.external || false;
  20595. return {
  20596. external,
  20597. id: resolvedId.id,
  20598. meta: resolvedId.meta || {},
  20599. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  20600. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  20601. };
  20602. }
  20603. async handleExistingModule(module, isEntry, isPreload) {
  20604. const loadPromise = this.moduleLoadPromises.get(module);
  20605. if (isPreload) {
  20606. return isPreload === RESOLVE_DEPENDENCIES
  20607. ? waitForDependencyResolution(loadPromise)
  20608. : loadPromise;
  20609. }
  20610. if (isEntry) {
  20611. module.info.isEntry = true;
  20612. this.implicitEntryModules.delete(module);
  20613. for (const dependant of module.implicitlyLoadedAfter) {
  20614. dependant.implicitlyLoadedBefore.delete(module);
  20615. }
  20616. module.implicitlyLoadedAfter.clear();
  20617. }
  20618. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20619. }
  20620. handleResolveId(resolvedId, source, importer) {
  20621. if (resolvedId === null) {
  20622. if (isRelative(source)) {
  20623. return error(errUnresolvedImport(source, importer));
  20624. }
  20625. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  20626. return {
  20627. external: true,
  20628. id: source,
  20629. meta: {},
  20630. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20631. syntheticNamedExports: false
  20632. };
  20633. }
  20634. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20635. this.options.onwarn(errExternalSyntheticExports(source, importer));
  20636. }
  20637. return resolvedId;
  20638. }
  20639. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  20640. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
  20641. if (resolveIdResult == null) {
  20642. return error(implicitlyLoadedBefore === null
  20643. ? errUnresolvedEntry(unresolvedId)
  20644. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20645. }
  20646. if (resolveIdResult === false ||
  20647. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  20648. return error(implicitlyLoadedBefore === null
  20649. ? errEntryCannotBeExternal(unresolvedId)
  20650. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20651. }
  20652. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20653. ? resolveIdResult
  20654. : { id: resolveIdResult }), undefined, isEntry, false);
  20655. }
  20656. async resolveDynamicImport(module, specifier, importer) {
  20657. var _a;
  20658. var _b;
  20659. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20660. specifier,
  20661. importer
  20662. ]);
  20663. if (typeof specifier !== 'string') {
  20664. if (typeof resolution === 'string') {
  20665. return resolution;
  20666. }
  20667. if (!resolution) {
  20668. return null;
  20669. }
  20670. return {
  20671. external: false,
  20672. moduleSideEffects: true,
  20673. ...resolution
  20674. };
  20675. }
  20676. if (resolution == null) {
  20677. return ((_a = (_b = module.resolvedIds)[specifier]) !== null && _a !== void 0 ? _a : (_b[specifier] = this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false), specifier, module.id)));
  20678. }
  20679. return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  20680. }
  20681. }
  20682. function normalizeRelativeExternalId(source, importer) {
  20683. return isRelative(source)
  20684. ? importer
  20685. ? resolve(importer, '..', source)
  20686. : resolve(source)
  20687. : source;
  20688. }
  20689. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20690. var _a;
  20691. if (fileName !== null) {
  20692. module.chunkFileNames.add(fileName);
  20693. }
  20694. else if (name !== null) {
  20695. // Always keep chunkNames sorted by priority
  20696. let namePosition = 0;
  20697. while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
  20698. namePosition++;
  20699. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20700. }
  20701. }
  20702. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20703. return (makeAbsoluteExternalsRelative === true ||
  20704. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20705. !isAbsolute(id));
  20706. }
  20707. async function waitForDependencyResolution(loadPromise) {
  20708. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20709. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20710. }
  20711. class GlobalScope extends Scope$1 {
  20712. constructor() {
  20713. super();
  20714. this.parent = null;
  20715. this.variables.set('undefined', new UndefinedVariable());
  20716. }
  20717. findVariable(name) {
  20718. let variable = this.variables.get(name);
  20719. if (!variable) {
  20720. variable = new GlobalVariable(name);
  20721. this.variables.set(name, variable);
  20722. }
  20723. return variable;
  20724. }
  20725. }
  20726. function generateAssetFileName(name, source, outputOptions, bundle) {
  20727. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  20728. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  20729. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  20730. : outputOptions.assetFileNames, 'output.assetFileNames', {
  20731. ext: () => extname(emittedName).substring(1),
  20732. extname: () => extname(emittedName),
  20733. hash() {
  20734. return createHash()
  20735. .update(emittedName)
  20736. .update(':')
  20737. .update(source)
  20738. .digest('hex')
  20739. .substring(0, 8);
  20740. },
  20741. name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
  20742. }), bundle);
  20743. }
  20744. function reserveFileNameInBundle(fileName, bundle, warn) {
  20745. const lowercaseFileName = fileName.toLowerCase();
  20746. if (bundle[lowercaseBundleKeys].has(lowercaseFileName)) {
  20747. warn(errFileNameConflict(fileName));
  20748. }
  20749. else {
  20750. bundle[fileName] = FILE_PLACEHOLDER;
  20751. }
  20752. }
  20753. function hasValidType(emittedFile) {
  20754. return Boolean(emittedFile &&
  20755. (emittedFile.type === 'asset' ||
  20756. emittedFile.type === 'chunk'));
  20757. }
  20758. function hasValidName(emittedFile) {
  20759. const validatedName = emittedFile.fileName || emittedFile.name;
  20760. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  20761. }
  20762. function getValidSource(source, emittedFile, fileReferenceId) {
  20763. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  20764. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  20765. return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  20766. }
  20767. return source;
  20768. }
  20769. function getAssetFileName(file, referenceId) {
  20770. if (typeof file.fileName !== 'string') {
  20771. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  20772. }
  20773. return file.fileName;
  20774. }
  20775. function getChunkFileName(file, facadeChunkByModule) {
  20776. var _a;
  20777. const fileName = file.fileName || (file.module && ((_a = facadeChunkByModule === null || facadeChunkByModule === void 0 ? void 0 : facadeChunkByModule.get(file.module)) === null || _a === void 0 ? void 0 : _a.id));
  20778. if (!fileName)
  20779. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  20780. return fileName;
  20781. }
  20782. class FileEmitter {
  20783. constructor(graph, options, baseFileEmitter) {
  20784. this.graph = graph;
  20785. this.options = options;
  20786. this.bundle = null;
  20787. this.facadeChunkByModule = null;
  20788. this.outputOptions = null;
  20789. this.assertAssetsFinalized = () => {
  20790. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  20791. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  20792. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  20793. }
  20794. };
  20795. this.emitFile = (emittedFile) => {
  20796. if (!hasValidType(emittedFile)) {
  20797. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  20798. }
  20799. if (!hasValidName(emittedFile)) {
  20800. return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  20801. }
  20802. if (emittedFile.type === 'chunk') {
  20803. return this.emitChunk(emittedFile);
  20804. }
  20805. return this.emitAsset(emittedFile);
  20806. };
  20807. this.getFileName = (fileReferenceId) => {
  20808. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  20809. if (!emittedFile)
  20810. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  20811. if (emittedFile.type === 'chunk') {
  20812. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  20813. }
  20814. return getAssetFileName(emittedFile, fileReferenceId);
  20815. };
  20816. this.setAssetSource = (referenceId, requestedSource) => {
  20817. const consumedFile = this.filesByReferenceId.get(referenceId);
  20818. if (!consumedFile)
  20819. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  20820. if (consumedFile.type !== 'asset') {
  20821. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  20822. }
  20823. if (consumedFile.source !== undefined) {
  20824. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  20825. }
  20826. const source = getValidSource(requestedSource, consumedFile, referenceId);
  20827. if (this.bundle) {
  20828. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  20829. }
  20830. else {
  20831. consumedFile.source = source;
  20832. }
  20833. };
  20834. this.setOutputBundle = (bundle, outputOptions, facadeChunkByModule) => {
  20835. this.outputOptions = outputOptions;
  20836. this.bundle = bundle;
  20837. this.facadeChunkByModule = facadeChunkByModule;
  20838. for (const { fileName } of this.filesByReferenceId.values()) {
  20839. if (fileName) {
  20840. reserveFileNameInBundle(fileName, bundle, this.options.onwarn);
  20841. }
  20842. }
  20843. for (const [referenceId, consumedFile] of this.filesByReferenceId) {
  20844. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  20845. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, bundle);
  20846. }
  20847. }
  20848. };
  20849. this.filesByReferenceId = baseFileEmitter
  20850. ? new Map(baseFileEmitter.filesByReferenceId)
  20851. : new Map();
  20852. }
  20853. assignReferenceId(file, idBase) {
  20854. let referenceId;
  20855. do {
  20856. referenceId = createHash()
  20857. .update(referenceId || idBase)
  20858. .digest('hex')
  20859. .substring(0, 8);
  20860. } while (this.filesByReferenceId.has(referenceId));
  20861. this.filesByReferenceId.set(referenceId, file);
  20862. return referenceId;
  20863. }
  20864. emitAsset(emittedAsset) {
  20865. const source = typeof emittedAsset.source !== 'undefined'
  20866. ? getValidSource(emittedAsset.source, emittedAsset, null)
  20867. : undefined;
  20868. const consumedAsset = {
  20869. fileName: emittedAsset.fileName,
  20870. name: emittedAsset.name,
  20871. source,
  20872. type: 'asset'
  20873. };
  20874. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  20875. if (this.bundle) {
  20876. if (emittedAsset.fileName) {
  20877. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  20878. }
  20879. if (source !== undefined) {
  20880. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  20881. }
  20882. }
  20883. return referenceId;
  20884. }
  20885. emitChunk(emittedChunk) {
  20886. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  20887. return error(errInvalidRollupPhaseForChunkEmission());
  20888. }
  20889. if (typeof emittedChunk.id !== 'string') {
  20890. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  20891. }
  20892. const consumedChunk = {
  20893. fileName: emittedChunk.fileName,
  20894. module: null,
  20895. name: emittedChunk.name || emittedChunk.id,
  20896. type: 'chunk'
  20897. };
  20898. this.graph.moduleLoader
  20899. .emitChunk(emittedChunk)
  20900. .then(module => (consumedChunk.module = module))
  20901. .catch(() => {
  20902. // Avoid unhandled Promise rejection as the error will be thrown later
  20903. // once module loading has finished
  20904. });
  20905. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  20906. }
  20907. finalizeAsset(consumedFile, source, referenceId, bundle) {
  20908. const fileName = consumedFile.fileName ||
  20909. findExistingAssetFileNameWithSource(bundle, source) ||
  20910. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  20911. // We must not modify the original assets to avoid interaction between outputs
  20912. const assetWithFileName = { ...consumedFile, fileName, source };
  20913. this.filesByReferenceId.set(referenceId, assetWithFileName);
  20914. const { options } = this;
  20915. bundle[fileName] = {
  20916. fileName,
  20917. get isAsset() {
  20918. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  20919. return true;
  20920. },
  20921. name: consumedFile.name,
  20922. source,
  20923. type: 'asset'
  20924. };
  20925. }
  20926. }
  20927. // TODO This can lead to a performance problem when many assets are emitted.
  20928. // Instead, we should only deduplicate string assets and use their sources as
  20929. // object keys for better performance.
  20930. function findExistingAssetFileNameWithSource(bundle, source) {
  20931. for (const [fileName, outputFile] of Object.entries(bundle)) {
  20932. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  20933. return fileName;
  20934. }
  20935. return null;
  20936. }
  20937. function areSourcesEqual(sourceA, sourceB) {
  20938. if (typeof sourceA === 'string') {
  20939. return sourceA === sourceB;
  20940. }
  20941. if (typeof sourceB === 'string') {
  20942. return false;
  20943. }
  20944. if ('equals' in sourceA) {
  20945. return sourceA.equals(sourceB);
  20946. }
  20947. if (sourceA.length !== sourceB.length) {
  20948. return false;
  20949. }
  20950. for (let index = 0; index < sourceA.length; index++) {
  20951. if (sourceA[index] !== sourceB[index]) {
  20952. return false;
  20953. }
  20954. }
  20955. return true;
  20956. }
  20957. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  20958. let deprecationWarningShown = false;
  20959. return ((...args) => {
  20960. if (!deprecationWarningShown) {
  20961. deprecationWarningShown = true;
  20962. warnDeprecation({
  20963. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  20964. plugin: pluginName
  20965. }, activeDeprecation, options);
  20966. }
  20967. return handler(...args);
  20968. });
  20969. }
  20970. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  20971. let cacheable = true;
  20972. if (typeof plugin.cacheKey !== 'string') {
  20973. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20974. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  20975. existingPluginNames.has(plugin.name)) {
  20976. cacheable = false;
  20977. }
  20978. else {
  20979. existingPluginNames.add(plugin.name);
  20980. }
  20981. }
  20982. let cacheInstance;
  20983. if (!pluginCache) {
  20984. cacheInstance = NO_CACHE;
  20985. }
  20986. else if (cacheable) {
  20987. const cacheKey = plugin.cacheKey || plugin.name;
  20988. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  20989. }
  20990. else {
  20991. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  20992. }
  20993. return {
  20994. addWatchFile(id) {
  20995. if (graph.phase >= BuildPhase.GENERATE) {
  20996. return this.error(errInvalidRollupPhaseForAddWatchFile());
  20997. }
  20998. graph.watchFiles[id] = true;
  20999. },
  21000. cache: cacheInstance,
  21001. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  21002. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  21003. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  21004. error(err) {
  21005. return throwPluginError(err, plugin.name);
  21006. },
  21007. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  21008. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  21009. getFileName: fileEmitter.getFileName,
  21010. getModuleIds: () => graph.modulesById.keys(),
  21011. getModuleInfo: graph.getModuleInfo,
  21012. getWatchFiles: () => Object.keys(graph.watchFiles),
  21013. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  21014. load(resolvedId) {
  21015. return graph.moduleLoader.preloadModule(resolvedId);
  21016. },
  21017. meta: {
  21018. rollupVersion: version$1,
  21019. watchMode: graph.watchMode
  21020. },
  21021. get moduleIds() {
  21022. function* wrappedModuleIds() {
  21023. // We are wrapping this in a generator to only show the message once we are actually iterating
  21024. warnDeprecation({
  21025. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  21026. plugin: plugin.name
  21027. }, false, options);
  21028. yield* moduleIds;
  21029. }
  21030. const moduleIds = graph.modulesById.keys();
  21031. return wrappedModuleIds();
  21032. },
  21033. parse: graph.contextParse.bind(graph),
  21034. resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
  21035. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
  21036. },
  21037. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  21038. .resolveId(source, importer, BLANK, undefined)
  21039. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  21040. setAssetSource: fileEmitter.setAssetSource,
  21041. warn(warning) {
  21042. if (typeof warning === 'string')
  21043. warning = { message: warning };
  21044. if (warning.code)
  21045. warning.pluginCode = warning.code;
  21046. warning.code = 'PLUGIN_WARNING';
  21047. warning.plugin = plugin.name;
  21048. options.onwarn(warning);
  21049. }
  21050. };
  21051. }
  21052. // This will make sure no input hook is omitted
  21053. const inputHookNames = {
  21054. buildEnd: 1,
  21055. buildStart: 1,
  21056. closeBundle: 1,
  21057. closeWatcher: 1,
  21058. load: 1,
  21059. moduleParsed: 1,
  21060. options: 1,
  21061. resolveDynamicImport: 1,
  21062. resolveId: 1,
  21063. shouldTransformCachedModule: 1,
  21064. transform: 1,
  21065. watchChange: 1
  21066. };
  21067. const inputHooks = Object.keys(inputHookNames);
  21068. class PluginDriver {
  21069. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21070. this.graph = graph;
  21071. this.options = options;
  21072. this.pluginCache = pluginCache;
  21073. this.sortedPlugins = new Map();
  21074. this.unfulfilledActions = new Set();
  21075. warnDeprecatedHooks(userPlugins, options);
  21076. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21077. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21078. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21079. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  21080. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21081. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  21082. const existingPluginNames = new Set();
  21083. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21084. plugin,
  21085. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21086. ]));
  21087. if (basePluginDriver) {
  21088. for (const plugin of userPlugins) {
  21089. for (const hook of inputHooks) {
  21090. if (hook in plugin) {
  21091. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  21092. }
  21093. }
  21094. }
  21095. }
  21096. }
  21097. createOutputPluginDriver(plugins) {
  21098. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21099. }
  21100. getUnfulfilledHookActions() {
  21101. return this.unfulfilledActions;
  21102. }
  21103. // chains, first non-null result stops and returns
  21104. hookFirst(hookName, args, replaceContext, skipped) {
  21105. let promise = Promise.resolve(null);
  21106. for (const plugin of this.getSortedPlugins(hookName)) {
  21107. if (skipped && skipped.has(plugin))
  21108. continue;
  21109. promise = promise.then(result => {
  21110. if (result != null)
  21111. return result;
  21112. return this.runHook(hookName, args, plugin, replaceContext);
  21113. });
  21114. }
  21115. return promise;
  21116. }
  21117. // chains synchronously, first non-null result stops and returns
  21118. hookFirstSync(hookName, args, replaceContext) {
  21119. for (const plugin of this.getSortedPlugins(hookName)) {
  21120. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21121. if (result != null)
  21122. return result;
  21123. }
  21124. return null;
  21125. }
  21126. // parallel, ignores returns
  21127. async hookParallel(hookName, args, replaceContext) {
  21128. const parallelPromises = [];
  21129. for (const plugin of this.getSortedPlugins(hookName)) {
  21130. if (plugin[hookName].sequential) {
  21131. await Promise.all(parallelPromises);
  21132. parallelPromises.length = 0;
  21133. await this.runHook(hookName, args, plugin, replaceContext);
  21134. }
  21135. else {
  21136. parallelPromises.push(this.runHook(hookName, args, plugin, replaceContext));
  21137. }
  21138. }
  21139. await Promise.all(parallelPromises);
  21140. }
  21141. // chains, reduces returned value, handling the reduced value as the first hook argument
  21142. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  21143. let promise = Promise.resolve(arg0);
  21144. for (const plugin of this.getSortedPlugins(hookName)) {
  21145. promise = promise.then(arg0 => this.runHook(hookName, [arg0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)));
  21146. }
  21147. return promise;
  21148. }
  21149. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21150. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  21151. for (const plugin of this.getSortedPlugins(hookName)) {
  21152. const args = [arg0, ...rest];
  21153. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21154. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  21155. }
  21156. return arg0;
  21157. }
  21158. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21159. async hookReduceValue(hookName, initialValue, args, reducer) {
  21160. const results = [];
  21161. const parallelResults = [];
  21162. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21163. if (plugin[hookName].sequential) {
  21164. results.push(...(await Promise.all(parallelResults)));
  21165. parallelResults.length = 0;
  21166. results.push(await this.runHook(hookName, args, plugin));
  21167. }
  21168. else {
  21169. parallelResults.push(this.runHook(hookName, args, plugin));
  21170. }
  21171. }
  21172. results.push(...(await Promise.all(parallelResults)));
  21173. return results.reduce(reducer, await initialValue);
  21174. }
  21175. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21176. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  21177. let acc = initialValue;
  21178. for (const plugin of this.getSortedPlugins(hookName)) {
  21179. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21180. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  21181. }
  21182. return acc;
  21183. }
  21184. // chains, ignores returns
  21185. hookSeq(hookName, args, replaceContext) {
  21186. let promise = Promise.resolve();
  21187. for (const plugin of this.getSortedPlugins(hookName)) {
  21188. promise = promise.then(() => this.runHook(hookName, args, plugin, replaceContext));
  21189. }
  21190. return promise.then(noReturn);
  21191. }
  21192. getSortedPlugins(hookName, validateHandler) {
  21193. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21194. }
  21195. // Implementation signature
  21196. runHook(hookName, args, plugin, replaceContext) {
  21197. // We always filter for plugins that support the hook before running it
  21198. const hook = plugin[hookName];
  21199. const handler = typeof hook === 'object' ? hook.handler : hook;
  21200. let context = this.pluginContexts.get(plugin);
  21201. if (replaceContext) {
  21202. context = replaceContext(context, plugin);
  21203. }
  21204. let action = null;
  21205. return Promise.resolve()
  21206. .then(() => {
  21207. if (typeof handler !== 'function') {
  21208. return handler;
  21209. }
  21210. // eslint-disable-next-line @typescript-eslint/ban-types
  21211. const hookResult = handler.apply(context, args);
  21212. if (!(hookResult === null || hookResult === void 0 ? void 0 : hookResult.then)) {
  21213. // short circuit for non-thenables and non-Promises
  21214. return hookResult;
  21215. }
  21216. // Track pending hook actions to properly error out when
  21217. // unfulfilled promises cause rollup to abruptly and confusingly
  21218. // exit with a successful 0 return code but without producing any
  21219. // output, errors or warnings.
  21220. action = [plugin.name, hookName, args];
  21221. this.unfulfilledActions.add(action);
  21222. // Although it would be more elegant to just return hookResult here
  21223. // and put the .then() handler just above the .catch() handler below,
  21224. // doing so would subtly change the defacto async event dispatch order
  21225. // which at least one test and some plugins in the wild may depend on.
  21226. return Promise.resolve(hookResult).then(result => {
  21227. // action was fulfilled
  21228. this.unfulfilledActions.delete(action);
  21229. return result;
  21230. });
  21231. })
  21232. .catch(err => {
  21233. if (action !== null) {
  21234. // action considered to be fulfilled since error being handled
  21235. this.unfulfilledActions.delete(action);
  21236. }
  21237. return throwPluginError(err, plugin.name, { hook: hookName });
  21238. });
  21239. }
  21240. /**
  21241. * Run a sync plugin hook and return the result.
  21242. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21243. * @param args Arguments passed to the plugin hook.
  21244. * @param plugin The acutal plugin
  21245. * @param replaceContext When passed, the plugin context can be overridden.
  21246. */
  21247. runHookSync(hookName, args, plugin, replaceContext) {
  21248. const hook = plugin[hookName];
  21249. const handler = typeof hook === 'object' ? hook.handler : hook;
  21250. let context = this.pluginContexts.get(plugin);
  21251. if (replaceContext) {
  21252. context = replaceContext(context, plugin);
  21253. }
  21254. try {
  21255. // eslint-disable-next-line @typescript-eslint/ban-types
  21256. return handler.apply(context, args);
  21257. }
  21258. catch (err) {
  21259. return throwPluginError(err, plugin.name, { hook: hookName });
  21260. }
  21261. }
  21262. }
  21263. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  21264. const pre = [];
  21265. const normal = [];
  21266. const post = [];
  21267. for (const plugin of plugins) {
  21268. const hook = plugin[hookName];
  21269. if (hook) {
  21270. if (typeof hook === 'object') {
  21271. validateHandler(hook.handler, hookName, plugin);
  21272. if (hook.order === 'pre') {
  21273. pre.push(plugin);
  21274. continue;
  21275. }
  21276. if (hook.order === 'post') {
  21277. post.push(plugin);
  21278. continue;
  21279. }
  21280. }
  21281. else {
  21282. validateHandler(hook, hookName, plugin);
  21283. }
  21284. normal.push(plugin);
  21285. }
  21286. }
  21287. return [...pre, ...normal, ...post];
  21288. }
  21289. function validateFunctionPluginHandler(handler, hookName, plugin) {
  21290. if (typeof handler !== 'function') {
  21291. error(errInvalidFunctionPluginHook(hookName, plugin.name));
  21292. }
  21293. }
  21294. function validateAddonPluginHandler(handler, hookName, plugin) {
  21295. if (typeof handler !== 'string' && typeof handler !== 'function') {
  21296. return error(errInvalidAddonPluginHook(hookName, plugin.name));
  21297. }
  21298. }
  21299. function noReturn() { }
  21300. class Queue {
  21301. constructor(maxParallel) {
  21302. this.maxParallel = maxParallel;
  21303. this.queue = [];
  21304. this.workerCount = 0;
  21305. }
  21306. run(task) {
  21307. return new Promise((resolve, reject) => {
  21308. this.queue.push({ reject, resolve, task });
  21309. this.work();
  21310. });
  21311. }
  21312. async work() {
  21313. if (this.workerCount >= this.maxParallel)
  21314. return;
  21315. this.workerCount++;
  21316. let entry;
  21317. while ((entry = this.queue.shift())) {
  21318. const { reject, resolve, task } = entry;
  21319. try {
  21320. const result = await task();
  21321. resolve(result);
  21322. }
  21323. catch (err) {
  21324. reject(err);
  21325. }
  21326. }
  21327. this.workerCount--;
  21328. }
  21329. }
  21330. function normalizeEntryModules(entryModules) {
  21331. if (Array.isArray(entryModules)) {
  21332. return entryModules.map(id => ({
  21333. fileName: null,
  21334. id,
  21335. implicitlyLoadedAfter: [],
  21336. importer: undefined,
  21337. name: null
  21338. }));
  21339. }
  21340. return Object.entries(entryModules).map(([name, id]) => ({
  21341. fileName: null,
  21342. id,
  21343. implicitlyLoadedAfter: [],
  21344. importer: undefined,
  21345. name
  21346. }));
  21347. }
  21348. class Graph {
  21349. constructor(options, watcher) {
  21350. var _a, _b;
  21351. this.options = options;
  21352. this.cachedModules = new Map();
  21353. this.deoptimizationTracker = new PathTracker();
  21354. this.entryModules = [];
  21355. this.modulesById = new Map();
  21356. this.needsTreeshakingPass = false;
  21357. this.phase = BuildPhase.LOAD_AND_PARSE;
  21358. this.scope = new GlobalScope();
  21359. this.watchFiles = Object.create(null);
  21360. this.watchMode = false;
  21361. this.externalModules = [];
  21362. this.implicitEntryModules = [];
  21363. this.modules = [];
  21364. this.getModuleInfo = (moduleId) => {
  21365. const foundModule = this.modulesById.get(moduleId);
  21366. if (!foundModule)
  21367. return null;
  21368. return foundModule.info;
  21369. };
  21370. if (options.cache !== false) {
  21371. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  21372. for (const module of options.cache.modules)
  21373. this.cachedModules.set(module.id, module);
  21374. }
  21375. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  21376. // increment access counter
  21377. for (const name in this.pluginCache) {
  21378. const cache = this.pluginCache[name];
  21379. for (const value of Object.values(cache))
  21380. value[0]++;
  21381. }
  21382. }
  21383. if (watcher) {
  21384. this.watchMode = true;
  21385. const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
  21386. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21387. watcher.onCurrentAwaited('change', handleChange);
  21388. watcher.onCurrentAwaited('close', handleClose);
  21389. }
  21390. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21391. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  21392. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21393. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21394. }
  21395. async build() {
  21396. timeStart('generate module graph', 2);
  21397. await this.generateModuleGraph();
  21398. timeEnd('generate module graph', 2);
  21399. timeStart('sort modules', 2);
  21400. this.phase = BuildPhase.ANALYSE;
  21401. this.sortModules();
  21402. timeEnd('sort modules', 2);
  21403. timeStart('mark included statements', 2);
  21404. this.includeStatements();
  21405. timeEnd('mark included statements', 2);
  21406. this.phase = BuildPhase.GENERATE;
  21407. }
  21408. contextParse(code, options = {}) {
  21409. const onCommentOrig = options.onComment;
  21410. const comments = [];
  21411. if (onCommentOrig && typeof onCommentOrig == 'function') {
  21412. options.onComment = (block, text, start, end, ...args) => {
  21413. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  21414. return onCommentOrig.call(options, block, text, start, end, ...args);
  21415. };
  21416. }
  21417. else {
  21418. options.onComment = comments;
  21419. }
  21420. const ast = this.acornParser.parse(code, {
  21421. ...this.options.acorn,
  21422. ...options
  21423. });
  21424. if (typeof onCommentOrig == 'object') {
  21425. onCommentOrig.push(...comments);
  21426. }
  21427. options.onComment = onCommentOrig;
  21428. addAnnotations(comments, ast, code);
  21429. return ast;
  21430. }
  21431. getCache() {
  21432. // handle plugin cache eviction
  21433. for (const name in this.pluginCache) {
  21434. const cache = this.pluginCache[name];
  21435. let allDeleted = true;
  21436. for (const [key, value] of Object.entries(cache)) {
  21437. if (value[0] >= this.options.experimentalCacheExpiry)
  21438. delete cache[key];
  21439. else
  21440. allDeleted = false;
  21441. }
  21442. if (allDeleted)
  21443. delete this.pluginCache[name];
  21444. }
  21445. return {
  21446. modules: this.modules.map(module => module.toJSON()),
  21447. plugins: this.pluginCache
  21448. };
  21449. }
  21450. async generateModuleGraph() {
  21451. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21452. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21453. if (this.entryModules.length === 0) {
  21454. throw new Error('You must supply options.input to rollup');
  21455. }
  21456. for (const module of this.modulesById.values()) {
  21457. if (module instanceof Module) {
  21458. this.modules.push(module);
  21459. }
  21460. else {
  21461. this.externalModules.push(module);
  21462. }
  21463. }
  21464. }
  21465. includeStatements() {
  21466. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21467. markModuleAndImpureDependenciesAsExecuted(module);
  21468. }
  21469. if (this.options.treeshake) {
  21470. let treeshakingPass = 1;
  21471. do {
  21472. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21473. this.needsTreeshakingPass = false;
  21474. for (const module of this.modules) {
  21475. if (module.isExecuted) {
  21476. if (module.info.moduleSideEffects === 'no-treeshake') {
  21477. module.includeAllInBundle();
  21478. }
  21479. else {
  21480. module.include();
  21481. }
  21482. }
  21483. }
  21484. if (treeshakingPass === 1) {
  21485. // We only include exports after the first pass to avoid issues with
  21486. // the TDZ detection logic
  21487. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21488. if (module.preserveSignature !== false) {
  21489. module.includeAllExports(false);
  21490. this.needsTreeshakingPass = true;
  21491. }
  21492. }
  21493. }
  21494. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21495. } while (this.needsTreeshakingPass);
  21496. }
  21497. else {
  21498. for (const module of this.modules)
  21499. module.includeAllInBundle();
  21500. }
  21501. for (const externalModule of this.externalModules)
  21502. externalModule.warnUnusedImports();
  21503. for (const module of this.implicitEntryModules) {
  21504. for (const dependant of module.implicitlyLoadedAfter) {
  21505. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21506. error(errImplicitDependantIsNotIncluded(dependant));
  21507. }
  21508. }
  21509. }
  21510. }
  21511. sortModules() {
  21512. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21513. for (const cyclePath of cyclePaths) {
  21514. this.options.onwarn({
  21515. code: 'CIRCULAR_DEPENDENCY',
  21516. cycle: cyclePath,
  21517. importer: cyclePath[0],
  21518. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  21519. });
  21520. }
  21521. this.modules = orderedModules;
  21522. for (const module of this.modules) {
  21523. module.bindReferences();
  21524. }
  21525. this.warnForMissingExports();
  21526. }
  21527. warnForMissingExports() {
  21528. for (const module of this.modules) {
  21529. for (const importDescription of module.importDescriptions.values()) {
  21530. if (importDescription.name !== '*' &&
  21531. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21532. module.warn({
  21533. code: 'NON_EXISTENT_EXPORT',
  21534. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  21535. name: importDescription.name,
  21536. source: importDescription.module.id
  21537. }, importDescription.start);
  21538. }
  21539. }
  21540. }
  21541. }
  21542. }
  21543. function ensureArray(items) {
  21544. if (Array.isArray(items)) {
  21545. return items.filter(Boolean);
  21546. }
  21547. if (items) {
  21548. return [items];
  21549. }
  21550. return [];
  21551. }
  21552. function formatAction([pluginName, hookName, args]) {
  21553. const action = `(${pluginName}) ${hookName}`;
  21554. const s = JSON.stringify;
  21555. switch (hookName) {
  21556. case 'resolveId':
  21557. return `${action} ${s(args[0])} ${s(args[1])}`;
  21558. case 'load':
  21559. return `${action} ${s(args[0])}`;
  21560. case 'transform':
  21561. return `${action} ${s(args[1])}`;
  21562. case 'shouldTransformCachedModule':
  21563. return `${action} ${s(args[0].id)}`;
  21564. case 'moduleParsed':
  21565. return `${action} ${s(args[0].id)}`;
  21566. }
  21567. return action;
  21568. }
  21569. // We do not directly listen on process to avoid max listeners warnings for
  21570. // complicated build processes
  21571. const beforeExitEvent = 'beforeExit';
  21572. const beforeExitEmitter = new EventEmitter();
  21573. beforeExitEmitter.setMaxListeners(0);
  21574. process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
  21575. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21576. let handleEmptyEventLoop;
  21577. const emptyEventLoopPromise = new Promise((_, reject) => {
  21578. handleEmptyEventLoop = () => {
  21579. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21580. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21581. [...unfulfilledActions].map(formatAction).join('\n')));
  21582. };
  21583. beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
  21584. });
  21585. const result = await Promise.race([callback(), emptyEventLoopPromise]);
  21586. beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
  21587. return result;
  21588. }
  21589. const defaultOnWarn = warning => console.warn(warning.message || warning);
  21590. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  21591. const validOptionSet = new Set(validOptions);
  21592. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  21593. if (unknownOptions.length > 0) {
  21594. warn({
  21595. code: 'UNKNOWN_OPTION',
  21596. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  21597. ...validOptionSet
  21598. ]
  21599. .sort()
  21600. .join(', ')}`
  21601. });
  21602. }
  21603. }
  21604. const treeshakePresets = {
  21605. recommended: {
  21606. annotations: true,
  21607. correctVarValueBeforeDeclaration: false,
  21608. moduleSideEffects: () => true,
  21609. propertyReadSideEffects: true,
  21610. tryCatchDeoptimization: true,
  21611. unknownGlobalSideEffects: false
  21612. },
  21613. safest: {
  21614. annotations: true,
  21615. correctVarValueBeforeDeclaration: true,
  21616. moduleSideEffects: () => true,
  21617. propertyReadSideEffects: true,
  21618. tryCatchDeoptimization: true,
  21619. unknownGlobalSideEffects: true
  21620. },
  21621. smallest: {
  21622. annotations: true,
  21623. correctVarValueBeforeDeclaration: false,
  21624. moduleSideEffects: () => false,
  21625. propertyReadSideEffects: false,
  21626. tryCatchDeoptimization: false,
  21627. unknownGlobalSideEffects: false
  21628. }
  21629. };
  21630. const generatedCodePresets = {
  21631. es2015: {
  21632. arrowFunctions: true,
  21633. constBindings: true,
  21634. objectShorthand: true,
  21635. reservedNamesAsProps: true,
  21636. symbols: true
  21637. },
  21638. es5: {
  21639. arrowFunctions: false,
  21640. constBindings: false,
  21641. objectShorthand: false,
  21642. reservedNamesAsProps: true,
  21643. symbols: false
  21644. }
  21645. };
  21646. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  21647. const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
  21648. if (typeof value === 'string') {
  21649. const preset = presets[value];
  21650. if (preset) {
  21651. return preset;
  21652. }
  21653. error(errInvalidOption(optionName, getHashFromObjectOption(optionName), `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  21654. }
  21655. return objectifyOption(value);
  21656. };
  21657. const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
  21658. const presetName = value === null || value === void 0 ? void 0 : value.preset;
  21659. if (presetName) {
  21660. const preset = presets[presetName];
  21661. if (preset) {
  21662. return { ...preset, ...value };
  21663. }
  21664. else {
  21665. error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  21666. }
  21667. }
  21668. return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
  21669. };
  21670. const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
  21671. function normalizeInputOptions(config) {
  21672. var _a, _b, _c;
  21673. // These are options that may trigger special warnings or behaviour later
  21674. // if the user did not select an explicit value
  21675. const unsetOptions = new Set();
  21676. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  21677. const onwarn = getOnwarn(config);
  21678. const strictDeprecations = config.strictDeprecations || false;
  21679. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  21680. const options = {
  21681. acorn: getAcorn(config),
  21682. acornInjectPlugins: getAcornInjectPlugins(config),
  21683. cache: getCache(config),
  21684. context,
  21685. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  21686. external: getIdMatcher(config.external),
  21687. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  21688. input: getInput(config),
  21689. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  21690. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  21691. maxParallelFileOps,
  21692. maxParallelFileReads: maxParallelFileOps,
  21693. moduleContext: getModuleContext(config, context),
  21694. onwarn,
  21695. perf: config.perf || false,
  21696. plugins: ensureArray(config.plugins),
  21697. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  21698. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  21699. preserveSymlinks: config.preserveSymlinks || false,
  21700. shimMissingExports: config.shimMissingExports || false,
  21701. strictDeprecations,
  21702. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  21703. };
  21704. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  21705. return { options, unsetOptions };
  21706. }
  21707. const getOnwarn = (config) => {
  21708. const { onwarn } = config;
  21709. return onwarn
  21710. ? warning => {
  21711. warning.toString = () => {
  21712. let str = '';
  21713. if (warning.plugin)
  21714. str += `(${warning.plugin} plugin) `;
  21715. if (warning.loc)
  21716. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  21717. str += warning.message;
  21718. return str;
  21719. };
  21720. onwarn(warning, defaultOnWarn);
  21721. }
  21722. : defaultOnWarn;
  21723. };
  21724. const getAcorn = (config) => ({
  21725. allowAwaitOutsideFunction: true,
  21726. ecmaVersion: 'latest',
  21727. preserveParens: false,
  21728. sourceType: 'module',
  21729. ...config.acorn
  21730. });
  21731. const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
  21732. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  21733. const getIdMatcher = (option) => {
  21734. if (option === true) {
  21735. return () => true;
  21736. }
  21737. if (typeof option === 'function') {
  21738. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  21739. }
  21740. if (option) {
  21741. const ids = new Set();
  21742. const matchers = [];
  21743. for (const value of ensureArray(option)) {
  21744. if (value instanceof RegExp) {
  21745. matchers.push(value);
  21746. }
  21747. else {
  21748. ids.add(value);
  21749. }
  21750. }
  21751. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21752. }
  21753. return () => false;
  21754. };
  21755. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  21756. const configInlineDynamicImports = config.inlineDynamicImports;
  21757. if (configInlineDynamicImports) {
  21758. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  21759. }
  21760. return configInlineDynamicImports;
  21761. };
  21762. const getInput = (config) => {
  21763. const configInput = config.input;
  21764. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21765. };
  21766. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  21767. const configManualChunks = config.manualChunks;
  21768. if (configManualChunks) {
  21769. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  21770. }
  21771. return configManualChunks;
  21772. };
  21773. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  21774. var _a;
  21775. const maxParallelFileReads = config.maxParallelFileReads;
  21776. if (typeof maxParallelFileReads === 'number') {
  21777. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
  21778. }
  21779. const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
  21780. if (typeof maxParallelFileOps === 'number') {
  21781. if (maxParallelFileOps <= 0)
  21782. return Infinity;
  21783. return maxParallelFileOps;
  21784. }
  21785. return 20;
  21786. };
  21787. const getModuleContext = (config, context) => {
  21788. const configModuleContext = config.moduleContext;
  21789. if (typeof configModuleContext === 'function') {
  21790. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  21791. }
  21792. if (configModuleContext) {
  21793. const contextByModuleId = Object.create(null);
  21794. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21795. contextByModuleId[resolve(key)] = moduleContext;
  21796. }
  21797. return id => contextByModuleId[id] || context;
  21798. }
  21799. return () => context;
  21800. };
  21801. const getPreserveEntrySignatures = (config, unsetOptions) => {
  21802. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  21803. if (configPreserveEntrySignatures == null) {
  21804. unsetOptions.add('preserveEntrySignatures');
  21805. }
  21806. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  21807. };
  21808. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  21809. const configPreserveModules = config.preserveModules;
  21810. if (configPreserveModules) {
  21811. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  21812. }
  21813. return configPreserveModules;
  21814. };
  21815. const getTreeshake = (config, warn, strictDeprecations) => {
  21816. const configTreeshake = config.treeshake;
  21817. if (configTreeshake === false) {
  21818. return false;
  21819. }
  21820. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
  21821. if (typeof configWithPreset.pureExternalModules !== 'undefined') {
  21822. warnDeprecationWithOptions(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, true, warn, strictDeprecations);
  21823. }
  21824. return {
  21825. annotations: configWithPreset.annotations !== false,
  21826. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21827. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  21828. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  21829. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  21830. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21831. ? 'always'
  21832. : configWithPreset.propertyReadSideEffects !== false,
  21833. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21834. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21835. };
  21836. };
  21837. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  21838. if (typeof moduleSideEffectsOption === 'boolean') {
  21839. return () => moduleSideEffectsOption;
  21840. }
  21841. if (moduleSideEffectsOption === 'no-external') {
  21842. return (_id, external) => !external;
  21843. }
  21844. if (typeof moduleSideEffectsOption === 'function') {
  21845. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  21846. }
  21847. if (Array.isArray(moduleSideEffectsOption)) {
  21848. const ids = new Set(moduleSideEffectsOption);
  21849. return id => ids.has(id);
  21850. }
  21851. if (moduleSideEffectsOption) {
  21852. error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
  21853. }
  21854. const isPureExternalModule = getIdMatcher(pureExternalModules);
  21855. return (id, external) => !(external && isPureExternalModule(id));
  21856. };
  21857. // https://datatracker.ietf.org/doc/html/rfc2396
  21858. // eslint-disable-next-line no-control-regex
  21859. const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
  21860. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21861. function sanitizeFileName(name) {
  21862. const match = DRIVE_LETTER_REGEX.exec(name);
  21863. const driveLetter = match ? match[0] : '';
  21864. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21865. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21866. return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21867. }
  21868. function isValidUrl(url) {
  21869. try {
  21870. new URL(url);
  21871. }
  21872. catch (_) {
  21873. return false;
  21874. }
  21875. return true;
  21876. }
  21877. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21878. var _a, _b, _c, _d, _e, _f, _g;
  21879. // These are options that may trigger special warnings or behaviour later
  21880. // if the user did not select an explicit value
  21881. const unsetOptions = new Set(unsetInputOptions);
  21882. const compact = config.compact || false;
  21883. const format = getFormat(config);
  21884. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21885. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21886. const file = getFile(config, preserveModules, inputOptions);
  21887. const preferConst = getPreferConst(config, inputOptions);
  21888. const generatedCode = getGeneratedCode(config, preferConst);
  21889. const outputOptions = {
  21890. amd: getAmd(config),
  21891. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  21892. banner: getAddon(config, 'banner'),
  21893. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  21894. compact,
  21895. dir: getDir(config, file),
  21896. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  21897. entryFileNames: getEntryFileNames(config, unsetOptions),
  21898. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  21899. exports: getExports(config, unsetOptions),
  21900. extend: config.extend || false,
  21901. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  21902. file,
  21903. footer: getAddon(config, 'footer'),
  21904. format,
  21905. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  21906. generatedCode,
  21907. globals: config.globals || {},
  21908. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  21909. indent: getIndent(config, compact),
  21910. inlineDynamicImports,
  21911. interop: getInterop(config, inputOptions),
  21912. intro: getAddon(config, 'intro'),
  21913. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  21914. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21915. name: config.name,
  21916. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  21917. noConflict: config.noConflict || false,
  21918. outro: getAddon(config, 'outro'),
  21919. paths: config.paths || {},
  21920. plugins: ensureArray(config.plugins),
  21921. preferConst,
  21922. preserveModules,
  21923. preserveModulesRoot: getPreserveModulesRoot(config),
  21924. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21925. ? config.sanitizeFileName
  21926. : config.sanitizeFileName === false
  21927. ? id => id
  21928. : sanitizeFileName,
  21929. sourcemap: config.sourcemap || false,
  21930. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21931. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21932. sourcemapFile: config.sourcemapFile,
  21933. sourcemapPathTransform: config.sourcemapPathTransform,
  21934. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  21935. systemNullSetters: config.systemNullSetters || false,
  21936. validate: config.validate || false
  21937. };
  21938. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  21939. return { options: outputOptions, unsetOptions };
  21940. }
  21941. const getFile = (config, preserveModules, inputOptions) => {
  21942. const { file } = config;
  21943. if (typeof file === 'string') {
  21944. if (preserveModules) {
  21945. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21946. }
  21947. if (!Array.isArray(inputOptions.input))
  21948. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21949. }
  21950. return file;
  21951. };
  21952. const getFormat = (config) => {
  21953. const configFormat = config.format;
  21954. switch (configFormat) {
  21955. case undefined:
  21956. case 'es':
  21957. case 'esm':
  21958. case 'module':
  21959. return 'es';
  21960. case 'cjs':
  21961. case 'commonjs':
  21962. return 'cjs';
  21963. case 'system':
  21964. case 'systemjs':
  21965. return 'system';
  21966. case 'amd':
  21967. case 'iife':
  21968. case 'umd':
  21969. return configFormat;
  21970. default:
  21971. return error({
  21972. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  21973. url: `https://rollupjs.org/guide/en/#outputformat`
  21974. });
  21975. }
  21976. };
  21977. const getInlineDynamicImports = (config, inputOptions) => {
  21978. var _a;
  21979. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  21980. const { input } = inputOptions;
  21981. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21982. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21983. }
  21984. return inlineDynamicImports;
  21985. };
  21986. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21987. var _a;
  21988. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  21989. if (preserveModules) {
  21990. if (inlineDynamicImports) {
  21991. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
  21992. }
  21993. if (inputOptions.preserveEntrySignatures === false) {
  21994. return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
  21995. }
  21996. }
  21997. return preserveModules;
  21998. };
  21999. const getPreferConst = (config, inputOptions) => {
  22000. const configPreferConst = config.preferConst;
  22001. if (configPreferConst != null) {
  22002. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
  22003. }
  22004. return !!configPreferConst;
  22005. };
  22006. const getPreserveModulesRoot = (config) => {
  22007. const { preserveModulesRoot } = config;
  22008. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22009. return undefined;
  22010. }
  22011. return resolve(preserveModulesRoot);
  22012. };
  22013. const getAmd = (config) => {
  22014. const mergedOption = {
  22015. autoId: false,
  22016. basePath: '',
  22017. define: 'define',
  22018. forceJsExtensionForImports: false,
  22019. ...config.amd
  22020. };
  22021. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22022. return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  22023. }
  22024. if (mergedOption.basePath && !mergedOption.autoId) {
  22025. return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
  22026. }
  22027. let normalized;
  22028. if (mergedOption.autoId) {
  22029. normalized = {
  22030. autoId: true,
  22031. basePath: mergedOption.basePath,
  22032. define: mergedOption.define,
  22033. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22034. };
  22035. }
  22036. else {
  22037. normalized = {
  22038. autoId: false,
  22039. define: mergedOption.define,
  22040. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22041. id: mergedOption.id
  22042. };
  22043. }
  22044. return normalized;
  22045. };
  22046. const getAddon = (config, name) => {
  22047. const configAddon = config[name];
  22048. if (typeof configAddon === 'function') {
  22049. return configAddon;
  22050. }
  22051. return () => configAddon || '';
  22052. };
  22053. const getDir = (config, file) => {
  22054. const { dir } = config;
  22055. if (typeof dir === 'string' && typeof file === 'string') {
  22056. return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  22057. }
  22058. return dir;
  22059. };
  22060. const getDynamicImportFunction = (config, inputOptions) => {
  22061. const configDynamicImportFunction = config.dynamicImportFunction;
  22062. if (configDynamicImportFunction) {
  22063. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  22064. }
  22065. return configDynamicImportFunction;
  22066. };
  22067. const getEntryFileNames = (config, unsetOptions) => {
  22068. const configEntryFileNames = config.entryFileNames;
  22069. if (configEntryFileNames == null) {
  22070. unsetOptions.add('entryFileNames');
  22071. }
  22072. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  22073. };
  22074. function getExports(config, unsetOptions) {
  22075. const configExports = config.exports;
  22076. if (configExports == null) {
  22077. unsetOptions.add('exports');
  22078. }
  22079. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22080. return error(errInvalidExportOptionValue(configExports));
  22081. }
  22082. return configExports || 'auto';
  22083. }
  22084. const getGeneratedCode = (config, preferConst) => {
  22085. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
  22086. return {
  22087. arrowFunctions: configWithPreset.arrowFunctions === true,
  22088. constBindings: configWithPreset.constBindings === true || preferConst,
  22089. objectShorthand: configWithPreset.objectShorthand === true,
  22090. reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
  22091. symbols: configWithPreset.symbols === true
  22092. };
  22093. };
  22094. const getIndent = (config, compact) => {
  22095. if (compact) {
  22096. return '';
  22097. }
  22098. const configIndent = config.indent;
  22099. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  22100. };
  22101. const ALLOWED_INTEROP_TYPES = new Set([
  22102. 'auto',
  22103. 'esModule',
  22104. 'default',
  22105. 'defaultOnly',
  22106. true,
  22107. false
  22108. ]);
  22109. const getInterop = (config, inputOptions) => {
  22110. const configInterop = config.interop;
  22111. const validatedInteropTypes = new Set();
  22112. const validateInterop = (interop) => {
  22113. if (!validatedInteropTypes.has(interop)) {
  22114. validatedInteropTypes.add(interop);
  22115. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22116. return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22117. }
  22118. if (typeof interop === 'boolean') {
  22119. warnDeprecation({
  22120. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  22121. url: 'https://rollupjs.org/guide/en/#outputinterop'
  22122. }, false, inputOptions);
  22123. }
  22124. }
  22125. return interop;
  22126. };
  22127. if (typeof configInterop === 'function') {
  22128. const interopPerId = Object.create(null);
  22129. let defaultInterop = null;
  22130. return id => id === null
  22131. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22132. : id in interopPerId
  22133. ? interopPerId[id]
  22134. : validateInterop((interopPerId[id] = configInterop(id)));
  22135. }
  22136. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  22137. };
  22138. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  22139. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  22140. if (configManualChunks) {
  22141. if (inlineDynamicImports) {
  22142. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
  22143. }
  22144. if (preserveModules) {
  22145. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
  22146. }
  22147. }
  22148. return configManualChunks || {};
  22149. };
  22150. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  22151. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  22152. const configNamespaceToStringTag = config.namespaceToStringTag;
  22153. if (configNamespaceToStringTag != null) {
  22154. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
  22155. return configNamespaceToStringTag;
  22156. }
  22157. return generatedCode.symbols || false;
  22158. };
  22159. const getSourcemapBaseUrl = (config) => {
  22160. const { sourcemapBaseUrl } = config;
  22161. if (sourcemapBaseUrl) {
  22162. if (isValidUrl(sourcemapBaseUrl)) {
  22163. return sourcemapBaseUrl;
  22164. }
  22165. return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22166. }
  22167. };
  22168. function rollup(rawInputOptions) {
  22169. return rollupInternal(rawInputOptions, null);
  22170. }
  22171. async function rollupInternal(rawInputOptions, watcher) {
  22172. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22173. initialiseTimers(inputOptions);
  22174. const graph = new Graph(inputOptions, watcher);
  22175. // remove the cache option from the memory after graph creation (cache is not used anymore)
  22176. const useCache = rawInputOptions.cache !== false;
  22177. delete inputOptions.cache;
  22178. delete rawInputOptions.cache;
  22179. timeStart('BUILD', 1);
  22180. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22181. try {
  22182. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22183. await graph.build();
  22184. }
  22185. catch (err) {
  22186. const watchFiles = Object.keys(graph.watchFiles);
  22187. if (watchFiles.length > 0) {
  22188. err.watchFiles = watchFiles;
  22189. }
  22190. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  22191. await graph.pluginDriver.hookParallel('closeBundle', []);
  22192. throw err;
  22193. }
  22194. await graph.pluginDriver.hookParallel('buildEnd', []);
  22195. });
  22196. timeEnd('BUILD', 1);
  22197. const result = {
  22198. cache: useCache ? graph.getCache() : undefined,
  22199. async close() {
  22200. if (result.closed)
  22201. return;
  22202. result.closed = true;
  22203. await graph.pluginDriver.hookParallel('closeBundle', []);
  22204. },
  22205. closed: false,
  22206. async generate(rawOutputOptions) {
  22207. if (result.closed)
  22208. return error(errAlreadyClosed());
  22209. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22210. },
  22211. watchFiles: Object.keys(graph.watchFiles),
  22212. async write(rawOutputOptions) {
  22213. if (result.closed)
  22214. return error(errAlreadyClosed());
  22215. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22216. }
  22217. };
  22218. if (inputOptions.perf)
  22219. result.getTimings = getTimings;
  22220. return result;
  22221. }
  22222. async function getInputOptions(rawInputOptions, watchMode) {
  22223. if (!rawInputOptions) {
  22224. throw new Error('You must supply an options object to rollup');
  22225. }
  22226. const rawPlugins = getSortedValidatedPlugins('options', ensureArray(rawInputOptions.plugins));
  22227. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  22228. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22229. return { options, unsetOptions };
  22230. }
  22231. function applyOptionHook(watchMode) {
  22232. return async (inputOptions, plugin) => {
  22233. const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
  22234. return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  22235. };
  22236. }
  22237. function normalizePlugins(plugins, anonymousPrefix) {
  22238. plugins.forEach((plugin, index) => {
  22239. if (!plugin.name) {
  22240. plugin.name = `${anonymousPrefix}${index + 1}`;
  22241. }
  22242. });
  22243. }
  22244. function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22245. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22246. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22247. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22248. const generated = await bundle.generate(isWrite);
  22249. if (isWrite) {
  22250. if (!outputOptions.dir && !outputOptions.file) {
  22251. return error({
  22252. code: 'MISSING_OPTION',
  22253. message: 'You must specify "output.file" or "output.dir" for the build.'
  22254. });
  22255. }
  22256. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22257. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22258. }
  22259. return createOutput(generated);
  22260. });
  22261. }
  22262. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22263. if (!rawOutputOptions) {
  22264. throw new Error('You must supply an options object');
  22265. }
  22266. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  22267. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22268. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22269. return {
  22270. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  22271. outputPluginDriver
  22272. };
  22273. }
  22274. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22275. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22276. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  22277. return {
  22278. ...pluginContext,
  22279. emitFile: emitError,
  22280. setAssetSource: emitError
  22281. };
  22282. }), inputOptions, unsetInputOptions);
  22283. }
  22284. function createOutput(outputBundle) {
  22285. return {
  22286. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22287. };
  22288. }
  22289. var SortingFileType;
  22290. (function (SortingFileType) {
  22291. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22292. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22293. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22294. })(SortingFileType || (SortingFileType = {}));
  22295. function getSortingFileType(file) {
  22296. if (file.type === 'asset') {
  22297. return SortingFileType.ASSET;
  22298. }
  22299. if (file.isEntry) {
  22300. return SortingFileType.ENTRY_CHUNK;
  22301. }
  22302. return SortingFileType.SECONDARY_CHUNK;
  22303. }
  22304. async function writeOutputFile(outputFile, outputOptions) {
  22305. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22306. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22307. await promises.mkdir(dirname(fileName), { recursive: true });
  22308. let writeSourceMapPromise;
  22309. let source;
  22310. if (outputFile.type === 'asset') {
  22311. source = outputFile.source;
  22312. }
  22313. else {
  22314. source = outputFile.code;
  22315. if (outputOptions.sourcemap && outputFile.map) {
  22316. let url;
  22317. if (outputOptions.sourcemap === 'inline') {
  22318. url = outputFile.map.toUrl();
  22319. }
  22320. else {
  22321. const { sourcemapBaseUrl } = outputOptions;
  22322. const sourcemapFileName = `${basename(outputFile.fileName)}.map`;
  22323. url = sourcemapBaseUrl
  22324. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  22325. : sourcemapFileName;
  22326. writeSourceMapPromise = promises.writeFile(`${fileName}.map`, outputFile.map.toString());
  22327. }
  22328. if (outputOptions.sourcemap !== 'hidden') {
  22329. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  22330. }
  22331. }
  22332. }
  22333. return Promise.all([promises.writeFile(fileName, source), writeSourceMapPromise]);
  22334. }
  22335. /**
  22336. * Auxiliary function for defining rollup configuration
  22337. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  22338. * @param options
  22339. */
  22340. function defineConfig(options) {
  22341. return options;
  22342. }
  22343. class WatchEmitter extends EventEmitter {
  22344. constructor() {
  22345. super();
  22346. this.awaitedHandlers = Object.create(null);
  22347. // Allows more than 10 bundles to be watched without
  22348. // showing the `MaxListenersExceededWarning` to the user.
  22349. this.setMaxListeners(Infinity);
  22350. }
  22351. // Will be overwritten by Rollup
  22352. async close() { }
  22353. emitAndAwait(event, ...args) {
  22354. this.emit(event, ...args);
  22355. return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
  22356. }
  22357. onCurrentAwaited(event, listener) {
  22358. this.getHandlers(event).push(listener);
  22359. return this;
  22360. }
  22361. removeAwaited() {
  22362. this.awaitedHandlers = {};
  22363. return this;
  22364. }
  22365. getHandlers(event) {
  22366. return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
  22367. }
  22368. }
  22369. let fsEvents;
  22370. let fsEventsImportError;
  22371. async function loadFsEvents() {
  22372. try {
  22373. ({ default: fsEvents } = await import('fsevents'));
  22374. }
  22375. catch (err) {
  22376. fsEventsImportError = err;
  22377. }
  22378. }
  22379. // A call to this function will be injected into the chokidar code
  22380. function getFsEvents() {
  22381. if (fsEventsImportError)
  22382. throw fsEventsImportError;
  22383. return fsEvents;
  22384. }
  22385. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  22386. __proto__: null,
  22387. loadFsEvents,
  22388. getFsEvents
  22389. }, Symbol.toStringTag, { value: 'Module' });
  22390. function watch(configs) {
  22391. const emitter = new WatchEmitter();
  22392. const configArray = ensureArray(configs);
  22393. const watchConfigs = configArray.filter(config => config.watch !== false);
  22394. if (watchConfigs.length === 0) {
  22395. return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
  22396. }
  22397. loadFsEvents()
  22398. .then(() => import('./watch.js'))
  22399. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  22400. return emitter;
  22401. }
  22402. export { createFilter, defaultOnWarn, defineConfig, ensureArray, fseventsImporter, generatedCodePresets, getAugmentedNamespace, objectifyOption, objectifyOptionWithPresets, picomatch$1 as picomatch, rollup, rollupInternal, treeshakePresets, version$1 as version, warnUnknownOptions, watch };