rollup.js 875 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992
  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. 'use strict';
  9. const require$$0 = require('path');
  10. const process$1 = require('process');
  11. const perf_hooks = require('perf_hooks');
  12. const crypto = require('crypto');
  13. const require$$0$1 = require('fs');
  14. const require$$0$2 = require('events');
  15. function _interopNamespaceDefault(e) {
  16. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  17. if (e) {
  18. for (const k in e) {
  19. n[k] = e[k];
  20. }
  21. }
  22. n.default = e;
  23. return n;
  24. }
  25. var version$1 = "2.79.1";
  26. function ensureArray$1(items) {
  27. if (Array.isArray(items)) {
  28. return items.filter(Boolean);
  29. }
  30. if (items) {
  31. return [items];
  32. }
  33. return [];
  34. }
  35. function getLocator$1(source, options) {
  36. if (options === void 0) { options = {}; }
  37. var offsetLine = options.offsetLine || 0;
  38. var offsetColumn = options.offsetColumn || 0;
  39. var originalLines = source.split('\n');
  40. var start = 0;
  41. var lineRanges = originalLines.map(function (line, i) {
  42. var end = start + line.length + 1;
  43. var range = { start: start, end: end, line: i };
  44. start = end;
  45. return range;
  46. });
  47. var i = 0;
  48. function rangeContains(range, index) {
  49. return range.start <= index && index < range.end;
  50. }
  51. function getLocation(range, index) {
  52. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  53. }
  54. function locate(search, startIndex) {
  55. if (typeof search === 'string') {
  56. search = source.indexOf(search, startIndex || 0);
  57. }
  58. var range = lineRanges[i];
  59. var d = search >= range.end ? 1 : -1;
  60. while (range) {
  61. if (rangeContains(range, search))
  62. return getLocation(range, search);
  63. i += d;
  64. range = lineRanges[i];
  65. }
  66. }
  67. return locate;
  68. }
  69. function locate(source, search, options) {
  70. if (typeof options === 'number') {
  71. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  72. }
  73. return getLocator$1(source, options)(search, options && options.startIndex);
  74. }
  75. function spaces(i) {
  76. let result = '';
  77. while (i--)
  78. result += ' ';
  79. return result;
  80. }
  81. function tabsToSpaces(str) {
  82. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  83. }
  84. function getCodeFrame(source, line, column) {
  85. let lines = source.split('\n');
  86. const frameStart = Math.max(0, line - 3);
  87. let frameEnd = Math.min(line + 2, lines.length);
  88. lines = lines.slice(frameStart, frameEnd);
  89. while (!/\S/.test(lines[lines.length - 1])) {
  90. lines.pop();
  91. frameEnd -= 1;
  92. }
  93. const digits = String(frameEnd).length;
  94. return lines
  95. .map((str, i) => {
  96. const isErrorLine = frameStart + i + 1 === line;
  97. let lineNum = String(i + frameStart + 1);
  98. while (lineNum.length < digits)
  99. lineNum = ` ${lineNum}`;
  100. if (isErrorLine) {
  101. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  102. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  103. }
  104. return `${lineNum}: ${tabsToSpaces(str)}`;
  105. })
  106. .join('\n');
  107. }
  108. function printQuotedStringList(list, verbs) {
  109. const isSingleItem = list.length <= 1;
  110. const quotedList = list.map(item => `"${item}"`);
  111. let output = isSingleItem
  112. ? quotedList[0]
  113. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  114. if (verbs) {
  115. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  116. }
  117. return output;
  118. }
  119. const ANY_SLASH_REGEX = /[/\\]/;
  120. function relative(from, to) {
  121. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  122. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  123. if (fromParts[0] === '.')
  124. fromParts.shift();
  125. if (toParts[0] === '.')
  126. toParts.shift();
  127. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  128. fromParts.shift();
  129. toParts.shift();
  130. }
  131. while (toParts[0] === '..' && fromParts.length > 0) {
  132. toParts.shift();
  133. fromParts.pop();
  134. }
  135. while (fromParts.pop()) {
  136. toParts.unshift('..');
  137. }
  138. return toParts.join('/');
  139. }
  140. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  141. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  142. function isAbsolute(path) {
  143. return ABSOLUTE_PATH_REGEX.test(path);
  144. }
  145. function isRelative(path) {
  146. return RELATIVE_PATH_REGEX.test(path);
  147. }
  148. const BACKSLASH_REGEX = /\\/g;
  149. function normalize(path) {
  150. return path.replace(BACKSLASH_REGEX, '/');
  151. }
  152. function getAliasName(id) {
  153. const base = require$$0.basename(id);
  154. return base.substring(0, base.length - require$$0.extname(id).length);
  155. }
  156. function relativeId(id) {
  157. if (!isAbsolute(id))
  158. return id;
  159. return relative(require$$0.resolve(), id);
  160. }
  161. function isPathFragment(name) {
  162. // starting with "/", "./", "../", "C:/"
  163. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  164. }
  165. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  166. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  167. let relativePath = normalize(relative(require$$0.dirname(importerId), targetPath));
  168. if (stripJsExtension && relativePath.endsWith('.js')) {
  169. relativePath = relativePath.slice(0, -3);
  170. }
  171. if (ensureFileName) {
  172. if (relativePath === '')
  173. return '../' + require$$0.basename(targetPath);
  174. if (UPPER_DIR_REGEX.test(relativePath)) {
  175. return relativePath
  176. .split('/')
  177. .concat(['..', require$$0.basename(targetPath)])
  178. .join('/');
  179. }
  180. }
  181. return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
  182. }
  183. function error(base) {
  184. if (!(base instanceof Error))
  185. base = Object.assign(new Error(base.message), base);
  186. throw base;
  187. }
  188. function augmentCodeLocation(props, pos, source, id) {
  189. if (typeof pos === 'object') {
  190. const { line, column } = pos;
  191. props.loc = { column, file: id, line };
  192. }
  193. else {
  194. props.pos = pos;
  195. const { line, column } = locate(source, pos, { offsetLine: 1 });
  196. props.loc = { column, file: id, line };
  197. }
  198. if (props.frame === undefined) {
  199. const { line, column } = props.loc;
  200. props.frame = getCodeFrame(source, line, column);
  201. }
  202. }
  203. var Errors;
  204. (function (Errors) {
  205. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  206. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  207. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  208. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  209. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  210. Errors["BAD_LOADER"] = "BAD_LOADER";
  211. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  212. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  213. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  214. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  215. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  216. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  217. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  218. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  219. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  220. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  221. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  222. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  223. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  224. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  225. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  226. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  227. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  228. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  229. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  230. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  231. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  232. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  233. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  234. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  235. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  236. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  237. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  238. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  239. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  240. })(Errors || (Errors = {}));
  241. function errAssetNotFinalisedForFileName(name) {
  242. return {
  243. code: Errors.ASSET_NOT_FINALISED,
  244. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  245. };
  246. }
  247. function errCannotEmitFromOptionsHook() {
  248. return {
  249. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  250. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  251. };
  252. }
  253. function errChunkNotGeneratedForFileName(name) {
  254. return {
  255. code: Errors.CHUNK_NOT_GENERATED,
  256. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  257. };
  258. }
  259. function errChunkInvalid({ fileName, code }, exception) {
  260. const errorProps = {
  261. code: Errors.CHUNK_INVALID,
  262. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  263. };
  264. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  265. return errorProps;
  266. }
  267. function errCircularReexport(exportName, importedModule) {
  268. return {
  269. code: Errors.CIRCULAR_REEXPORT,
  270. id: importedModule,
  271. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  272. };
  273. }
  274. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  275. return {
  276. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  277. exporter,
  278. importer,
  279. 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.`,
  280. reexporter
  281. };
  282. }
  283. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  284. return {
  285. code: Errors.ASSET_NOT_FOUND,
  286. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  287. };
  288. }
  289. function errAssetSourceAlreadySet(name) {
  290. return {
  291. code: Errors.ASSET_SOURCE_ALREADY_SET,
  292. message: `Unable to set the source for asset "${name}", source already set.`
  293. };
  294. }
  295. function errNoAssetSourceSet(assetName) {
  296. return {
  297. code: Errors.ASSET_SOURCE_MISSING,
  298. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  299. };
  300. }
  301. function errBadLoader(id) {
  302. return {
  303. code: Errors.BAD_LOADER,
  304. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  305. };
  306. }
  307. function errDeprecation(deprecation) {
  308. return {
  309. code: Errors.DEPRECATED_FEATURE,
  310. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  311. };
  312. }
  313. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  314. return {
  315. code: Errors.FILE_NOT_FOUND,
  316. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  317. };
  318. }
  319. function errFileNameConflict(fileName) {
  320. return {
  321. code: Errors.FILE_NAME_CONFLICT,
  322. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  323. };
  324. }
  325. function errInputHookInOutputPlugin(pluginName, hookName) {
  326. return {
  327. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  328. 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.`
  329. };
  330. }
  331. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  332. return {
  333. code: Errors.INVALID_CHUNK,
  334. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  335. };
  336. }
  337. function errInvalidExportOptionValue(optionValue) {
  338. return {
  339. code: Errors.INVALID_EXPORT_OPTION,
  340. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  341. url: `https://rollupjs.org/guide/en/#outputexports`
  342. };
  343. }
  344. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  345. return {
  346. code: 'INVALID_EXPORT_OPTION',
  347. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  348. };
  349. }
  350. function errInternalIdCannotBeExternal(source, importer) {
  351. return {
  352. code: Errors.INVALID_EXTERNAL_ID,
  353. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  354. };
  355. }
  356. function errInvalidOption(option, urlHash, explanation, value) {
  357. return {
  358. code: Errors.INVALID_OPTION,
  359. message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
  360. url: `https://rollupjs.org/guide/en/#${urlHash}`
  361. };
  362. }
  363. function errInvalidAddonPluginHook(hook, plugin) {
  364. return {
  365. code: Errors.INVALID_PLUGIN_HOOK,
  366. hook,
  367. message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a string, a function hook or an object with a "handler" string or function.`,
  368. plugin
  369. };
  370. }
  371. function errInvalidFunctionPluginHook(hook, plugin) {
  372. return {
  373. code: Errors.INVALID_PLUGIN_HOOK,
  374. hook,
  375. message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a function hook or an object with a "handler" function.`,
  376. plugin
  377. };
  378. }
  379. function errInvalidRollupPhaseForAddWatchFile() {
  380. return {
  381. code: Errors.INVALID_ROLLUP_PHASE,
  382. message: `Cannot call addWatchFile after the build has finished.`
  383. };
  384. }
  385. function errInvalidRollupPhaseForChunkEmission() {
  386. return {
  387. code: Errors.INVALID_ROLLUP_PHASE,
  388. message: `Cannot emit chunks after module loading has finished.`
  389. };
  390. }
  391. function errMissingExport(exportName, importingModule, importedModule) {
  392. return {
  393. code: Errors.MISSING_EXPORT,
  394. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  395. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  396. };
  397. }
  398. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  399. return {
  400. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  401. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  402. };
  403. }
  404. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  405. return {
  406. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  407. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  408. };
  409. }
  410. function errImplicitDependantIsNotIncluded(module) {
  411. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  412. return {
  413. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  414. 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.`
  415. };
  416. }
  417. function errMixedExport(facadeModuleId, name) {
  418. return {
  419. code: Errors.MIXED_EXPORTS,
  420. id: facadeModuleId,
  421. 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`,
  422. url: `https://rollupjs.org/guide/en/#outputexports`
  423. };
  424. }
  425. function errNamespaceConflict(name, reexportingModuleId, sources) {
  426. return {
  427. code: Errors.NAMESPACE_CONFLICT,
  428. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
  429. name,
  430. reexporter: reexportingModuleId,
  431. sources
  432. };
  433. }
  434. function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
  435. return {
  436. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  437. 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)}".`,
  438. name,
  439. reexporter: reexportingModule,
  440. sources
  441. };
  442. }
  443. function errNoTransformMapOrAstWithoutCode(pluginName) {
  444. return {
  445. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  446. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  447. 'a "code". This will be ignored.'
  448. };
  449. }
  450. function errPreferNamedExports(facadeModuleId) {
  451. const file = relativeId(facadeModuleId);
  452. return {
  453. code: Errors.PREFER_NAMED_EXPORTS,
  454. id: facadeModuleId,
  455. 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.`,
  456. url: `https://rollupjs.org/guide/en/#outputexports`
  457. };
  458. }
  459. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  460. return {
  461. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  462. id,
  463. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  464. ? `an explicit export named "${syntheticNamedExportsOption}"`
  465. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  466. };
  467. }
  468. function errUnexpectedNamedImport(id, imported, isReexport) {
  469. const importType = isReexport ? 'reexport' : 'import';
  470. return {
  471. code: Errors.UNEXPECTED_NAMED_IMPORT,
  472. id,
  473. 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.`,
  474. url: 'https://rollupjs.org/guide/en/#outputinterop'
  475. };
  476. }
  477. function errUnexpectedNamespaceReexport(id) {
  478. return {
  479. code: Errors.UNEXPECTED_NAMED_IMPORT,
  480. id,
  481. 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.`,
  482. url: 'https://rollupjs.org/guide/en/#outputinterop'
  483. };
  484. }
  485. function errEntryCannotBeExternal(unresolvedId) {
  486. return {
  487. code: Errors.UNRESOLVED_ENTRY,
  488. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  489. };
  490. }
  491. function errUnresolvedEntry(unresolvedId) {
  492. return {
  493. code: Errors.UNRESOLVED_ENTRY,
  494. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  495. };
  496. }
  497. function errUnresolvedImport(source, importer) {
  498. return {
  499. code: Errors.UNRESOLVED_IMPORT,
  500. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  501. };
  502. }
  503. function errUnresolvedImportTreatedAsExternal(source, importer) {
  504. return {
  505. code: Errors.UNRESOLVED_IMPORT,
  506. importer: relativeId(importer),
  507. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  508. source,
  509. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  510. };
  511. }
  512. function errExternalSyntheticExports(source, importer) {
  513. return {
  514. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  515. importer: relativeId(importer),
  516. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  517. source
  518. };
  519. }
  520. function errFailedValidation(message) {
  521. return {
  522. code: Errors.VALIDATION_ERROR,
  523. message
  524. };
  525. }
  526. function errAlreadyClosed() {
  527. return {
  528. code: Errors.ALREADY_CLOSED,
  529. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  530. };
  531. }
  532. function warnDeprecation(deprecation, activeDeprecation, options) {
  533. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  534. }
  535. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  536. if (activeDeprecation || strictDeprecations) {
  537. const warning = errDeprecation(deprecation);
  538. if (strictDeprecations) {
  539. return error(warning);
  540. }
  541. warn(warning);
  542. }
  543. }
  544. const defaultOnWarn = warning => console.warn(warning.message || warning);
  545. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  546. const validOptionSet = new Set(validOptions);
  547. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  548. if (unknownOptions.length > 0) {
  549. warn({
  550. code: 'UNKNOWN_OPTION',
  551. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  552. ...validOptionSet
  553. ]
  554. .sort()
  555. .join(', ')}`
  556. });
  557. }
  558. }
  559. const treeshakePresets = {
  560. recommended: {
  561. annotations: true,
  562. correctVarValueBeforeDeclaration: false,
  563. moduleSideEffects: () => true,
  564. propertyReadSideEffects: true,
  565. tryCatchDeoptimization: true,
  566. unknownGlobalSideEffects: false
  567. },
  568. safest: {
  569. annotations: true,
  570. correctVarValueBeforeDeclaration: true,
  571. moduleSideEffects: () => true,
  572. propertyReadSideEffects: true,
  573. tryCatchDeoptimization: true,
  574. unknownGlobalSideEffects: true
  575. },
  576. smallest: {
  577. annotations: true,
  578. correctVarValueBeforeDeclaration: false,
  579. moduleSideEffects: () => false,
  580. propertyReadSideEffects: false,
  581. tryCatchDeoptimization: false,
  582. unknownGlobalSideEffects: false
  583. }
  584. };
  585. const generatedCodePresets = {
  586. es2015: {
  587. arrowFunctions: true,
  588. constBindings: true,
  589. objectShorthand: true,
  590. reservedNamesAsProps: true,
  591. symbols: true
  592. },
  593. es5: {
  594. arrowFunctions: false,
  595. constBindings: false,
  596. objectShorthand: false,
  597. reservedNamesAsProps: true,
  598. symbols: false
  599. }
  600. };
  601. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  602. const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
  603. if (typeof value === 'string') {
  604. const preset = presets[value];
  605. if (preset) {
  606. return preset;
  607. }
  608. 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));
  609. }
  610. return objectifyOption(value);
  611. };
  612. const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
  613. const presetName = value === null || value === void 0 ? void 0 : value.preset;
  614. if (presetName) {
  615. const preset = presets[presetName];
  616. if (preset) {
  617. return { ...preset, ...value };
  618. }
  619. else {
  620. error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  621. }
  622. }
  623. return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
  624. };
  625. const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
  626. let fsEvents;
  627. let fsEventsImportError;
  628. async function loadFsEvents() {
  629. try {
  630. ({ default: fsEvents } = await Promise.resolve().then(() => /*#__PURE__*/_interopNamespaceDefault(require('fsevents'))));
  631. }
  632. catch (err) {
  633. fsEventsImportError = err;
  634. }
  635. }
  636. // A call to this function will be injected into the chokidar code
  637. function getFsEvents() {
  638. if (fsEventsImportError)
  639. throw fsEventsImportError;
  640. return fsEvents;
  641. }
  642. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  643. __proto__: null,
  644. loadFsEvents,
  645. getFsEvents
  646. }, Symbol.toStringTag, { value: 'Module' });
  647. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  648. function getDefaultExportFromCjs (x) {
  649. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  650. }
  651. function getAugmentedNamespace(n) {
  652. var f = n.default;
  653. if (typeof f == "function") {
  654. var a = function () {
  655. return f.apply(this, arguments);
  656. };
  657. a.prototype = f.prototype;
  658. } else a = {};
  659. Object.defineProperty(a, '__esModule', {value: true});
  660. Object.keys(n).forEach(function (k) {
  661. var d = Object.getOwnPropertyDescriptor(n, k);
  662. Object.defineProperty(a, k, d.get ? d : {
  663. enumerable: true,
  664. get: function () {
  665. return n[k];
  666. }
  667. });
  668. });
  669. return a;
  670. }
  671. var charToInteger = {};
  672. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  673. for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
  674. charToInteger[chars$1.charCodeAt(i$1)] = i$1;
  675. }
  676. function decode(mappings) {
  677. var decoded = [];
  678. var line = [];
  679. var segment = [
  680. 0,
  681. 0,
  682. 0,
  683. 0,
  684. 0,
  685. ];
  686. var j = 0;
  687. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  688. var c = mappings.charCodeAt(i);
  689. if (c === 44) { // ","
  690. segmentify(line, segment, j);
  691. j = 0;
  692. }
  693. else if (c === 59) { // ";"
  694. segmentify(line, segment, j);
  695. j = 0;
  696. decoded.push(line);
  697. line = [];
  698. segment[0] = 0;
  699. }
  700. else {
  701. var integer = charToInteger[c];
  702. if (integer === undefined) {
  703. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  704. }
  705. var hasContinuationBit = integer & 32;
  706. integer &= 31;
  707. value += integer << shift;
  708. if (hasContinuationBit) {
  709. shift += 5;
  710. }
  711. else {
  712. var shouldNegate = value & 1;
  713. value >>>= 1;
  714. if (shouldNegate) {
  715. value = value === 0 ? -0x80000000 : -value;
  716. }
  717. segment[j] += value;
  718. j++;
  719. value = shift = 0; // reset
  720. }
  721. }
  722. }
  723. segmentify(line, segment, j);
  724. decoded.push(line);
  725. return decoded;
  726. }
  727. function segmentify(line, segment, j) {
  728. // This looks ugly, but we're creating specialized arrays with a specific
  729. // length. This is much faster than creating a new array (which v8 expands to
  730. // a capacity of 17 after pushing the first item), or slicing out a subarray
  731. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  732. // length 5 (since not everything will have an associated name), followed by
  733. // length 1 (it's probably rare for a source substring to not have an
  734. // associated segment data).
  735. if (j === 4)
  736. line.push([segment[0], segment[1], segment[2], segment[3]]);
  737. else if (j === 5)
  738. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  739. else if (j === 1)
  740. line.push([segment[0]]);
  741. }
  742. function encode(decoded) {
  743. var sourceFileIndex = 0; // second field
  744. var sourceCodeLine = 0; // third field
  745. var sourceCodeColumn = 0; // fourth field
  746. var nameIndex = 0; // fifth field
  747. var mappings = '';
  748. for (var i = 0; i < decoded.length; i++) {
  749. var line = decoded[i];
  750. if (i > 0)
  751. mappings += ';';
  752. if (line.length === 0)
  753. continue;
  754. var generatedCodeColumn = 0; // first field
  755. var lineMappings = [];
  756. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  757. var segment = line_1[_i];
  758. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  759. generatedCodeColumn = segment[0];
  760. if (segment.length > 1) {
  761. segmentMappings +=
  762. encodeInteger(segment[1] - sourceFileIndex) +
  763. encodeInteger(segment[2] - sourceCodeLine) +
  764. encodeInteger(segment[3] - sourceCodeColumn);
  765. sourceFileIndex = segment[1];
  766. sourceCodeLine = segment[2];
  767. sourceCodeColumn = segment[3];
  768. }
  769. if (segment.length === 5) {
  770. segmentMappings += encodeInteger(segment[4] - nameIndex);
  771. nameIndex = segment[4];
  772. }
  773. lineMappings.push(segmentMappings);
  774. }
  775. mappings += lineMappings.join(',');
  776. }
  777. return mappings;
  778. }
  779. function encodeInteger(num) {
  780. var result = '';
  781. num = num < 0 ? (-num << 1) | 1 : num << 1;
  782. do {
  783. var clamped = num & 31;
  784. num >>>= 5;
  785. if (num > 0) {
  786. clamped |= 32;
  787. }
  788. result += chars$1[clamped];
  789. } while (num > 0);
  790. return result;
  791. }
  792. class BitSet {
  793. constructor(arg) {
  794. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  795. }
  796. add(n) {
  797. this.bits[n >> 5] |= 1 << (n & 31);
  798. }
  799. has(n) {
  800. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  801. }
  802. }
  803. class Chunk$1 {
  804. constructor(start, end, content) {
  805. this.start = start;
  806. this.end = end;
  807. this.original = content;
  808. this.intro = '';
  809. this.outro = '';
  810. this.content = content;
  811. this.storeName = false;
  812. this.edited = false;
  813. // we make these non-enumerable, for sanity while debugging
  814. Object.defineProperties(this, {
  815. previous: { writable: true, value: null },
  816. next: { writable: true, value: null },
  817. });
  818. }
  819. appendLeft(content) {
  820. this.outro += content;
  821. }
  822. appendRight(content) {
  823. this.intro = this.intro + content;
  824. }
  825. clone() {
  826. const chunk = new Chunk$1(this.start, this.end, this.original);
  827. chunk.intro = this.intro;
  828. chunk.outro = this.outro;
  829. chunk.content = this.content;
  830. chunk.storeName = this.storeName;
  831. chunk.edited = this.edited;
  832. return chunk;
  833. }
  834. contains(index) {
  835. return this.start < index && index < this.end;
  836. }
  837. eachNext(fn) {
  838. let chunk = this;
  839. while (chunk) {
  840. fn(chunk);
  841. chunk = chunk.next;
  842. }
  843. }
  844. eachPrevious(fn) {
  845. let chunk = this;
  846. while (chunk) {
  847. fn(chunk);
  848. chunk = chunk.previous;
  849. }
  850. }
  851. edit(content, storeName, contentOnly) {
  852. this.content = content;
  853. if (!contentOnly) {
  854. this.intro = '';
  855. this.outro = '';
  856. }
  857. this.storeName = storeName;
  858. this.edited = true;
  859. return this;
  860. }
  861. prependLeft(content) {
  862. this.outro = content + this.outro;
  863. }
  864. prependRight(content) {
  865. this.intro = content + this.intro;
  866. }
  867. split(index) {
  868. const sliceIndex = index - this.start;
  869. const originalBefore = this.original.slice(0, sliceIndex);
  870. const originalAfter = this.original.slice(sliceIndex);
  871. this.original = originalBefore;
  872. const newChunk = new Chunk$1(index, this.end, originalAfter);
  873. newChunk.outro = this.outro;
  874. this.outro = '';
  875. this.end = index;
  876. if (this.edited) {
  877. // TODO is this block necessary?...
  878. newChunk.edit('', false);
  879. this.content = '';
  880. } else {
  881. this.content = originalBefore;
  882. }
  883. newChunk.next = this.next;
  884. if (newChunk.next) newChunk.next.previous = newChunk;
  885. newChunk.previous = this;
  886. this.next = newChunk;
  887. return newChunk;
  888. }
  889. toString() {
  890. return this.intro + this.content + this.outro;
  891. }
  892. trimEnd(rx) {
  893. this.outro = this.outro.replace(rx, '');
  894. if (this.outro.length) return true;
  895. const trimmed = this.content.replace(rx, '');
  896. if (trimmed.length) {
  897. if (trimmed !== this.content) {
  898. this.split(this.start + trimmed.length).edit('', undefined, true);
  899. }
  900. return true;
  901. } else {
  902. this.edit('', undefined, true);
  903. this.intro = this.intro.replace(rx, '');
  904. if (this.intro.length) return true;
  905. }
  906. }
  907. trimStart(rx) {
  908. this.intro = this.intro.replace(rx, '');
  909. if (this.intro.length) return true;
  910. const trimmed = this.content.replace(rx, '');
  911. if (trimmed.length) {
  912. if (trimmed !== this.content) {
  913. this.split(this.end - trimmed.length);
  914. this.edit('', undefined, true);
  915. }
  916. return true;
  917. } else {
  918. this.edit('', undefined, true);
  919. this.outro = this.outro.replace(rx, '');
  920. if (this.outro.length) return true;
  921. }
  922. }
  923. }
  924. let btoa = () => {
  925. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  926. };
  927. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  928. btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
  929. } else if (typeof Buffer === 'function') {
  930. btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
  931. }
  932. class SourceMap {
  933. constructor(properties) {
  934. this.version = 3;
  935. this.file = properties.file;
  936. this.sources = properties.sources;
  937. this.sourcesContent = properties.sourcesContent;
  938. this.names = properties.names;
  939. this.mappings = encode(properties.mappings);
  940. }
  941. toString() {
  942. return JSON.stringify(this);
  943. }
  944. toUrl() {
  945. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  946. }
  947. }
  948. function guessIndent(code) {
  949. const lines = code.split('\n');
  950. const tabbed = lines.filter((line) => /^\t+/.test(line));
  951. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  952. if (tabbed.length === 0 && spaced.length === 0) {
  953. return null;
  954. }
  955. // More lines tabbed than spaced? Assume tabs, and
  956. // default to tabs in the case of a tie (or nothing
  957. // to go on)
  958. if (tabbed.length >= spaced.length) {
  959. return '\t';
  960. }
  961. // Otherwise, we need to guess the multiple
  962. const min = spaced.reduce((previous, current) => {
  963. const numSpaces = /^ +/.exec(current)[0].length;
  964. return Math.min(numSpaces, previous);
  965. }, Infinity);
  966. return new Array(min + 1).join(' ');
  967. }
  968. function getRelativePath(from, to) {
  969. const fromParts = from.split(/[/\\]/);
  970. const toParts = to.split(/[/\\]/);
  971. fromParts.pop(); // get dirname
  972. while (fromParts[0] === toParts[0]) {
  973. fromParts.shift();
  974. toParts.shift();
  975. }
  976. if (fromParts.length) {
  977. let i = fromParts.length;
  978. while (i--) fromParts[i] = '..';
  979. }
  980. return fromParts.concat(toParts).join('/');
  981. }
  982. const toString$1 = Object.prototype.toString;
  983. function isObject$1(thing) {
  984. return toString$1.call(thing) === '[object Object]';
  985. }
  986. function getLocator(source) {
  987. const originalLines = source.split('\n');
  988. const lineOffsets = [];
  989. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  990. lineOffsets.push(pos);
  991. pos += originalLines[i].length + 1;
  992. }
  993. return function locate(index) {
  994. let i = 0;
  995. let j = lineOffsets.length;
  996. while (i < j) {
  997. const m = (i + j) >> 1;
  998. if (index < lineOffsets[m]) {
  999. j = m;
  1000. } else {
  1001. i = m + 1;
  1002. }
  1003. }
  1004. const line = i - 1;
  1005. const column = index - lineOffsets[line];
  1006. return { line, column };
  1007. };
  1008. }
  1009. class Mappings {
  1010. constructor(hires) {
  1011. this.hires = hires;
  1012. this.generatedCodeLine = 0;
  1013. this.generatedCodeColumn = 0;
  1014. this.raw = [];
  1015. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1016. this.pending = null;
  1017. }
  1018. addEdit(sourceIndex, content, loc, nameIndex) {
  1019. if (content.length) {
  1020. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1021. if (nameIndex >= 0) {
  1022. segment.push(nameIndex);
  1023. }
  1024. this.rawSegments.push(segment);
  1025. } else if (this.pending) {
  1026. this.rawSegments.push(this.pending);
  1027. }
  1028. this.advance(content);
  1029. this.pending = null;
  1030. }
  1031. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  1032. let originalCharIndex = chunk.start;
  1033. let first = true;
  1034. while (originalCharIndex < chunk.end) {
  1035. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  1036. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  1037. }
  1038. if (original[originalCharIndex] === '\n') {
  1039. loc.line += 1;
  1040. loc.column = 0;
  1041. this.generatedCodeLine += 1;
  1042. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1043. this.generatedCodeColumn = 0;
  1044. first = true;
  1045. } else {
  1046. loc.column += 1;
  1047. this.generatedCodeColumn += 1;
  1048. first = false;
  1049. }
  1050. originalCharIndex += 1;
  1051. }
  1052. this.pending = null;
  1053. }
  1054. advance(str) {
  1055. if (!str) return;
  1056. const lines = str.split('\n');
  1057. if (lines.length > 1) {
  1058. for (let i = 0; i < lines.length - 1; i++) {
  1059. this.generatedCodeLine++;
  1060. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1061. }
  1062. this.generatedCodeColumn = 0;
  1063. }
  1064. this.generatedCodeColumn += lines[lines.length - 1].length;
  1065. }
  1066. }
  1067. const n = '\n';
  1068. const warned = {
  1069. insertLeft: false,
  1070. insertRight: false,
  1071. storeName: false,
  1072. };
  1073. class MagicString {
  1074. constructor(string, options = {}) {
  1075. const chunk = new Chunk$1(0, string.length, string);
  1076. Object.defineProperties(this, {
  1077. original: { writable: true, value: string },
  1078. outro: { writable: true, value: '' },
  1079. intro: { writable: true, value: '' },
  1080. firstChunk: { writable: true, value: chunk },
  1081. lastChunk: { writable: true, value: chunk },
  1082. lastSearchedChunk: { writable: true, value: chunk },
  1083. byStart: { writable: true, value: {} },
  1084. byEnd: { writable: true, value: {} },
  1085. filename: { writable: true, value: options.filename },
  1086. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  1087. sourcemapLocations: { writable: true, value: new BitSet() },
  1088. storedNames: { writable: true, value: {} },
  1089. indentStr: { writable: true, value: guessIndent(string) },
  1090. });
  1091. this.byStart[0] = chunk;
  1092. this.byEnd[string.length] = chunk;
  1093. }
  1094. addSourcemapLocation(char) {
  1095. this.sourcemapLocations.add(char);
  1096. }
  1097. append(content) {
  1098. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1099. this.outro += content;
  1100. return this;
  1101. }
  1102. appendLeft(index, content) {
  1103. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1104. this._split(index);
  1105. const chunk = this.byEnd[index];
  1106. if (chunk) {
  1107. chunk.appendLeft(content);
  1108. } else {
  1109. this.intro += content;
  1110. }
  1111. return this;
  1112. }
  1113. appendRight(index, content) {
  1114. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1115. this._split(index);
  1116. const chunk = this.byStart[index];
  1117. if (chunk) {
  1118. chunk.appendRight(content);
  1119. } else {
  1120. this.outro += content;
  1121. }
  1122. return this;
  1123. }
  1124. clone() {
  1125. const cloned = new MagicString(this.original, { filename: this.filename });
  1126. let originalChunk = this.firstChunk;
  1127. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  1128. while (originalChunk) {
  1129. cloned.byStart[clonedChunk.start] = clonedChunk;
  1130. cloned.byEnd[clonedChunk.end] = clonedChunk;
  1131. const nextOriginalChunk = originalChunk.next;
  1132. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  1133. if (nextClonedChunk) {
  1134. clonedChunk.next = nextClonedChunk;
  1135. nextClonedChunk.previous = clonedChunk;
  1136. clonedChunk = nextClonedChunk;
  1137. }
  1138. originalChunk = nextOriginalChunk;
  1139. }
  1140. cloned.lastChunk = clonedChunk;
  1141. if (this.indentExclusionRanges) {
  1142. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  1143. }
  1144. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  1145. cloned.intro = this.intro;
  1146. cloned.outro = this.outro;
  1147. return cloned;
  1148. }
  1149. generateDecodedMap(options) {
  1150. options = options || {};
  1151. const sourceIndex = 0;
  1152. const names = Object.keys(this.storedNames);
  1153. const mappings = new Mappings(options.hires);
  1154. const locate = getLocator(this.original);
  1155. if (this.intro) {
  1156. mappings.advance(this.intro);
  1157. }
  1158. this.firstChunk.eachNext((chunk) => {
  1159. const loc = locate(chunk.start);
  1160. if (chunk.intro.length) mappings.advance(chunk.intro);
  1161. if (chunk.edited) {
  1162. mappings.addEdit(
  1163. sourceIndex,
  1164. chunk.content,
  1165. loc,
  1166. chunk.storeName ? names.indexOf(chunk.original) : -1
  1167. );
  1168. } else {
  1169. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  1170. }
  1171. if (chunk.outro.length) mappings.advance(chunk.outro);
  1172. });
  1173. return {
  1174. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1175. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  1176. sourcesContent: options.includeContent ? [this.original] : [null],
  1177. names,
  1178. mappings: mappings.raw,
  1179. };
  1180. }
  1181. generateMap(options) {
  1182. return new SourceMap(this.generateDecodedMap(options));
  1183. }
  1184. getIndentString() {
  1185. return this.indentStr === null ? '\t' : this.indentStr;
  1186. }
  1187. indent(indentStr, options) {
  1188. const pattern = /^[^\r\n]/gm;
  1189. if (isObject$1(indentStr)) {
  1190. options = indentStr;
  1191. indentStr = undefined;
  1192. }
  1193. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  1194. if (indentStr === '') return this; // noop
  1195. options = options || {};
  1196. // Process exclusion ranges
  1197. const isExcluded = {};
  1198. if (options.exclude) {
  1199. const exclusions =
  1200. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  1201. exclusions.forEach((exclusion) => {
  1202. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  1203. isExcluded[i] = true;
  1204. }
  1205. });
  1206. }
  1207. let shouldIndentNextCharacter = options.indentStart !== false;
  1208. const replacer = (match) => {
  1209. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  1210. shouldIndentNextCharacter = true;
  1211. return match;
  1212. };
  1213. this.intro = this.intro.replace(pattern, replacer);
  1214. let charIndex = 0;
  1215. let chunk = this.firstChunk;
  1216. while (chunk) {
  1217. const end = chunk.end;
  1218. if (chunk.edited) {
  1219. if (!isExcluded[charIndex]) {
  1220. chunk.content = chunk.content.replace(pattern, replacer);
  1221. if (chunk.content.length) {
  1222. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  1223. }
  1224. }
  1225. } else {
  1226. charIndex = chunk.start;
  1227. while (charIndex < end) {
  1228. if (!isExcluded[charIndex]) {
  1229. const char = this.original[charIndex];
  1230. if (char === '\n') {
  1231. shouldIndentNextCharacter = true;
  1232. } else if (char !== '\r' && shouldIndentNextCharacter) {
  1233. shouldIndentNextCharacter = false;
  1234. if (charIndex === chunk.start) {
  1235. chunk.prependRight(indentStr);
  1236. } else {
  1237. this._splitChunk(chunk, charIndex);
  1238. chunk = chunk.next;
  1239. chunk.prependRight(indentStr);
  1240. }
  1241. }
  1242. }
  1243. charIndex += 1;
  1244. }
  1245. }
  1246. charIndex = chunk.end;
  1247. chunk = chunk.next;
  1248. }
  1249. this.outro = this.outro.replace(pattern, replacer);
  1250. return this;
  1251. }
  1252. insert() {
  1253. throw new Error(
  1254. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  1255. );
  1256. }
  1257. insertLeft(index, content) {
  1258. if (!warned.insertLeft) {
  1259. console.warn(
  1260. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  1261. ); // eslint-disable-line no-console
  1262. warned.insertLeft = true;
  1263. }
  1264. return this.appendLeft(index, content);
  1265. }
  1266. insertRight(index, content) {
  1267. if (!warned.insertRight) {
  1268. console.warn(
  1269. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  1270. ); // eslint-disable-line no-console
  1271. warned.insertRight = true;
  1272. }
  1273. return this.prependRight(index, content);
  1274. }
  1275. move(start, end, index) {
  1276. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  1277. this._split(start);
  1278. this._split(end);
  1279. this._split(index);
  1280. const first = this.byStart[start];
  1281. const last = this.byEnd[end];
  1282. const oldLeft = first.previous;
  1283. const oldRight = last.next;
  1284. const newRight = this.byStart[index];
  1285. if (!newRight && last === this.lastChunk) return this;
  1286. const newLeft = newRight ? newRight.previous : this.lastChunk;
  1287. if (oldLeft) oldLeft.next = oldRight;
  1288. if (oldRight) oldRight.previous = oldLeft;
  1289. if (newLeft) newLeft.next = first;
  1290. if (newRight) newRight.previous = last;
  1291. if (!first.previous) this.firstChunk = last.next;
  1292. if (!last.next) {
  1293. this.lastChunk = first.previous;
  1294. this.lastChunk.next = null;
  1295. }
  1296. first.previous = newLeft;
  1297. last.next = newRight || null;
  1298. if (!newLeft) this.firstChunk = first;
  1299. if (!newRight) this.lastChunk = last;
  1300. return this;
  1301. }
  1302. overwrite(start, end, content, options) {
  1303. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  1304. while (start < 0) start += this.original.length;
  1305. while (end < 0) end += this.original.length;
  1306. if (end > this.original.length) throw new Error('end is out of bounds');
  1307. if (start === end)
  1308. throw new Error(
  1309. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  1310. );
  1311. this._split(start);
  1312. this._split(end);
  1313. if (options === true) {
  1314. if (!warned.storeName) {
  1315. console.warn(
  1316. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  1317. ); // eslint-disable-line no-console
  1318. warned.storeName = true;
  1319. }
  1320. options = { storeName: true };
  1321. }
  1322. const storeName = options !== undefined ? options.storeName : false;
  1323. const contentOnly = options !== undefined ? options.contentOnly : false;
  1324. if (storeName) {
  1325. const original = this.original.slice(start, end);
  1326. Object.defineProperty(this.storedNames, original, {
  1327. writable: true,
  1328. value: true,
  1329. enumerable: true,
  1330. });
  1331. }
  1332. const first = this.byStart[start];
  1333. const last = this.byEnd[end];
  1334. if (first) {
  1335. let chunk = first;
  1336. while (chunk !== last) {
  1337. if (chunk.next !== this.byStart[chunk.end]) {
  1338. throw new Error('Cannot overwrite across a split point');
  1339. }
  1340. chunk = chunk.next;
  1341. chunk.edit('', false);
  1342. }
  1343. first.edit(content, storeName, contentOnly);
  1344. } else {
  1345. // must be inserting at the end
  1346. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  1347. // TODO last chunk in the array may not be the last chunk, if it's moved...
  1348. last.next = newChunk;
  1349. newChunk.previous = last;
  1350. }
  1351. return this;
  1352. }
  1353. prepend(content) {
  1354. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1355. this.intro = content + this.intro;
  1356. return this;
  1357. }
  1358. prependLeft(index, content) {
  1359. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1360. this._split(index);
  1361. const chunk = this.byEnd[index];
  1362. if (chunk) {
  1363. chunk.prependLeft(content);
  1364. } else {
  1365. this.intro = content + this.intro;
  1366. }
  1367. return this;
  1368. }
  1369. prependRight(index, content) {
  1370. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1371. this._split(index);
  1372. const chunk = this.byStart[index];
  1373. if (chunk) {
  1374. chunk.prependRight(content);
  1375. } else {
  1376. this.outro = content + this.outro;
  1377. }
  1378. return this;
  1379. }
  1380. remove(start, end) {
  1381. while (start < 0) start += this.original.length;
  1382. while (end < 0) end += this.original.length;
  1383. if (start === end) return this;
  1384. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  1385. if (start > end) throw new Error('end must be greater than start');
  1386. this._split(start);
  1387. this._split(end);
  1388. let chunk = this.byStart[start];
  1389. while (chunk) {
  1390. chunk.intro = '';
  1391. chunk.outro = '';
  1392. chunk.edit('');
  1393. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  1394. }
  1395. return this;
  1396. }
  1397. lastChar() {
  1398. if (this.outro.length) return this.outro[this.outro.length - 1];
  1399. let chunk = this.lastChunk;
  1400. do {
  1401. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  1402. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  1403. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  1404. } while ((chunk = chunk.previous));
  1405. if (this.intro.length) return this.intro[this.intro.length - 1];
  1406. return '';
  1407. }
  1408. lastLine() {
  1409. let lineIndex = this.outro.lastIndexOf(n);
  1410. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  1411. let lineStr = this.outro;
  1412. let chunk = this.lastChunk;
  1413. do {
  1414. if (chunk.outro.length > 0) {
  1415. lineIndex = chunk.outro.lastIndexOf(n);
  1416. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  1417. lineStr = chunk.outro + lineStr;
  1418. }
  1419. if (chunk.content.length > 0) {
  1420. lineIndex = chunk.content.lastIndexOf(n);
  1421. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  1422. lineStr = chunk.content + lineStr;
  1423. }
  1424. if (chunk.intro.length > 0) {
  1425. lineIndex = chunk.intro.lastIndexOf(n);
  1426. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  1427. lineStr = chunk.intro + lineStr;
  1428. }
  1429. } while ((chunk = chunk.previous));
  1430. lineIndex = this.intro.lastIndexOf(n);
  1431. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  1432. return this.intro + lineStr;
  1433. }
  1434. slice(start = 0, end = this.original.length) {
  1435. while (start < 0) start += this.original.length;
  1436. while (end < 0) end += this.original.length;
  1437. let result = '';
  1438. // find start chunk
  1439. let chunk = this.firstChunk;
  1440. while (chunk && (chunk.start > start || chunk.end <= start)) {
  1441. // found end chunk before start
  1442. if (chunk.start < end && chunk.end >= end) {
  1443. return result;
  1444. }
  1445. chunk = chunk.next;
  1446. }
  1447. if (chunk && chunk.edited && chunk.start !== start)
  1448. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  1449. const startChunk = chunk;
  1450. while (chunk) {
  1451. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  1452. result += chunk.intro;
  1453. }
  1454. const containsEnd = chunk.start < end && chunk.end >= end;
  1455. if (containsEnd && chunk.edited && chunk.end !== end)
  1456. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  1457. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  1458. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  1459. result += chunk.content.slice(sliceStart, sliceEnd);
  1460. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  1461. result += chunk.outro;
  1462. }
  1463. if (containsEnd) {
  1464. break;
  1465. }
  1466. chunk = chunk.next;
  1467. }
  1468. return result;
  1469. }
  1470. // TODO deprecate this? not really very useful
  1471. snip(start, end) {
  1472. const clone = this.clone();
  1473. clone.remove(0, start);
  1474. clone.remove(end, clone.original.length);
  1475. return clone;
  1476. }
  1477. _split(index) {
  1478. if (this.byStart[index] || this.byEnd[index]) return;
  1479. let chunk = this.lastSearchedChunk;
  1480. const searchForward = index > chunk.end;
  1481. while (chunk) {
  1482. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1483. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1484. }
  1485. }
  1486. _splitChunk(chunk, index) {
  1487. if (chunk.edited && chunk.content.length) {
  1488. // zero-length edited chunks are a special case (overlapping replacements)
  1489. const loc = getLocator(this.original)(index);
  1490. throw new Error(
  1491. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  1492. );
  1493. }
  1494. const newChunk = chunk.split(index);
  1495. this.byEnd[index] = chunk;
  1496. this.byStart[index] = newChunk;
  1497. this.byEnd[newChunk.end] = newChunk;
  1498. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1499. this.lastSearchedChunk = chunk;
  1500. return true;
  1501. }
  1502. toString() {
  1503. let str = this.intro;
  1504. let chunk = this.firstChunk;
  1505. while (chunk) {
  1506. str += chunk.toString();
  1507. chunk = chunk.next;
  1508. }
  1509. return str + this.outro;
  1510. }
  1511. isEmpty() {
  1512. let chunk = this.firstChunk;
  1513. do {
  1514. if (
  1515. (chunk.intro.length && chunk.intro.trim()) ||
  1516. (chunk.content.length && chunk.content.trim()) ||
  1517. (chunk.outro.length && chunk.outro.trim())
  1518. )
  1519. return false;
  1520. } while ((chunk = chunk.next));
  1521. return true;
  1522. }
  1523. length() {
  1524. let chunk = this.firstChunk;
  1525. let length = 0;
  1526. do {
  1527. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1528. } while ((chunk = chunk.next));
  1529. return length;
  1530. }
  1531. trimLines() {
  1532. return this.trim('[\\r\\n]');
  1533. }
  1534. trim(charType) {
  1535. return this.trimStart(charType).trimEnd(charType);
  1536. }
  1537. trimEndAborted(charType) {
  1538. const rx = new RegExp((charType || '\\s') + '+$');
  1539. this.outro = this.outro.replace(rx, '');
  1540. if (this.outro.length) return true;
  1541. let chunk = this.lastChunk;
  1542. do {
  1543. const end = chunk.end;
  1544. const aborted = chunk.trimEnd(rx);
  1545. // if chunk was trimmed, we have a new lastChunk
  1546. if (chunk.end !== end) {
  1547. if (this.lastChunk === chunk) {
  1548. this.lastChunk = chunk.next;
  1549. }
  1550. this.byEnd[chunk.end] = chunk;
  1551. this.byStart[chunk.next.start] = chunk.next;
  1552. this.byEnd[chunk.next.end] = chunk.next;
  1553. }
  1554. if (aborted) return true;
  1555. chunk = chunk.previous;
  1556. } while (chunk);
  1557. return false;
  1558. }
  1559. trimEnd(charType) {
  1560. this.trimEndAborted(charType);
  1561. return this;
  1562. }
  1563. trimStartAborted(charType) {
  1564. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1565. this.intro = this.intro.replace(rx, '');
  1566. if (this.intro.length) return true;
  1567. let chunk = this.firstChunk;
  1568. do {
  1569. const end = chunk.end;
  1570. const aborted = chunk.trimStart(rx);
  1571. if (chunk.end !== end) {
  1572. // special case...
  1573. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1574. this.byEnd[chunk.end] = chunk;
  1575. this.byStart[chunk.next.start] = chunk.next;
  1576. this.byEnd[chunk.next.end] = chunk.next;
  1577. }
  1578. if (aborted) return true;
  1579. chunk = chunk.next;
  1580. } while (chunk);
  1581. return false;
  1582. }
  1583. trimStart(charType) {
  1584. this.trimStartAborted(charType);
  1585. return this;
  1586. }
  1587. hasChanged() {
  1588. return this.original !== this.toString();
  1589. }
  1590. replace(searchValue, replacement) {
  1591. function getReplacement(match, str) {
  1592. if (typeof replacement === 'string') {
  1593. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1594. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1595. if (i === '$') return '$';
  1596. if (i === '&') return match[0];
  1597. const num = +i;
  1598. if (num < match.length) return match[+i];
  1599. return `$${i}`;
  1600. });
  1601. } else {
  1602. return replacement(...match, match.index, str, match.groups);
  1603. }
  1604. }
  1605. function matchAll(re, str) {
  1606. let match;
  1607. const matches = [];
  1608. while ((match = re.exec(str))) {
  1609. matches.push(match);
  1610. }
  1611. return matches;
  1612. }
  1613. if (typeof searchValue !== 'string' && searchValue.global) {
  1614. const matches = matchAll(searchValue, this.original);
  1615. matches.forEach((match) => {
  1616. if (match.index != null)
  1617. this.overwrite(
  1618. match.index,
  1619. match.index + match[0].length,
  1620. getReplacement(match, this.original)
  1621. );
  1622. });
  1623. } else {
  1624. const match = this.original.match(searchValue);
  1625. if (match && match.index != null)
  1626. this.overwrite(
  1627. match.index,
  1628. match.index + match[0].length,
  1629. getReplacement(match, this.original)
  1630. );
  1631. }
  1632. return this;
  1633. }
  1634. }
  1635. const hasOwnProp = Object.prototype.hasOwnProperty;
  1636. class Bundle$1 {
  1637. constructor(options = {}) {
  1638. this.intro = options.intro || '';
  1639. this.separator = options.separator !== undefined ? options.separator : '\n';
  1640. this.sources = [];
  1641. this.uniqueSources = [];
  1642. this.uniqueSourceIndexByFilename = {};
  1643. }
  1644. addSource(source) {
  1645. if (source instanceof MagicString) {
  1646. return this.addSource({
  1647. content: source,
  1648. filename: source.filename,
  1649. separator: this.separator,
  1650. });
  1651. }
  1652. if (!isObject$1(source) || !source.content) {
  1653. throw new Error(
  1654. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  1655. );
  1656. }
  1657. ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1658. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1659. });
  1660. if (source.separator === undefined) {
  1661. // TODO there's a bunch of this sort of thing, needs cleaning up
  1662. source.separator = this.separator;
  1663. }
  1664. if (source.filename) {
  1665. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1666. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1667. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1668. } else {
  1669. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1670. if (source.content.original !== uniqueSource.content) {
  1671. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1672. }
  1673. }
  1674. }
  1675. this.sources.push(source);
  1676. return this;
  1677. }
  1678. append(str, options) {
  1679. this.addSource({
  1680. content: new MagicString(str),
  1681. separator: (options && options.separator) || '',
  1682. });
  1683. return this;
  1684. }
  1685. clone() {
  1686. const bundle = new Bundle$1({
  1687. intro: this.intro,
  1688. separator: this.separator,
  1689. });
  1690. this.sources.forEach((source) => {
  1691. bundle.addSource({
  1692. filename: source.filename,
  1693. content: source.content.clone(),
  1694. separator: source.separator,
  1695. });
  1696. });
  1697. return bundle;
  1698. }
  1699. generateDecodedMap(options = {}) {
  1700. const names = [];
  1701. this.sources.forEach((source) => {
  1702. Object.keys(source.content.storedNames).forEach((name) => {
  1703. if (!~names.indexOf(name)) names.push(name);
  1704. });
  1705. });
  1706. const mappings = new Mappings(options.hires);
  1707. if (this.intro) {
  1708. mappings.advance(this.intro);
  1709. }
  1710. this.sources.forEach((source, i) => {
  1711. if (i > 0) {
  1712. mappings.advance(this.separator);
  1713. }
  1714. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1715. const magicString = source.content;
  1716. const locate = getLocator(magicString.original);
  1717. if (magicString.intro) {
  1718. mappings.advance(magicString.intro);
  1719. }
  1720. magicString.firstChunk.eachNext((chunk) => {
  1721. const loc = locate(chunk.start);
  1722. if (chunk.intro.length) mappings.advance(chunk.intro);
  1723. if (source.filename) {
  1724. if (chunk.edited) {
  1725. mappings.addEdit(
  1726. sourceIndex,
  1727. chunk.content,
  1728. loc,
  1729. chunk.storeName ? names.indexOf(chunk.original) : -1
  1730. );
  1731. } else {
  1732. mappings.addUneditedChunk(
  1733. sourceIndex,
  1734. chunk,
  1735. magicString.original,
  1736. loc,
  1737. magicString.sourcemapLocations
  1738. );
  1739. }
  1740. } else {
  1741. mappings.advance(chunk.content);
  1742. }
  1743. if (chunk.outro.length) mappings.advance(chunk.outro);
  1744. });
  1745. if (magicString.outro) {
  1746. mappings.advance(magicString.outro);
  1747. }
  1748. });
  1749. return {
  1750. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1751. sources: this.uniqueSources.map((source) => {
  1752. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1753. }),
  1754. sourcesContent: this.uniqueSources.map((source) => {
  1755. return options.includeContent ? source.content : null;
  1756. }),
  1757. names,
  1758. mappings: mappings.raw,
  1759. };
  1760. }
  1761. generateMap(options) {
  1762. return new SourceMap(this.generateDecodedMap(options));
  1763. }
  1764. getIndentString() {
  1765. const indentStringCounts = {};
  1766. this.sources.forEach((source) => {
  1767. const indentStr = source.content.indentStr;
  1768. if (indentStr === null) return;
  1769. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1770. indentStringCounts[indentStr] += 1;
  1771. });
  1772. return (
  1773. Object.keys(indentStringCounts).sort((a, b) => {
  1774. return indentStringCounts[a] - indentStringCounts[b];
  1775. })[0] || '\t'
  1776. );
  1777. }
  1778. indent(indentStr) {
  1779. if (!arguments.length) {
  1780. indentStr = this.getIndentString();
  1781. }
  1782. if (indentStr === '') return this; // noop
  1783. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1784. this.sources.forEach((source, i) => {
  1785. const separator = source.separator !== undefined ? source.separator : this.separator;
  1786. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1787. source.content.indent(indentStr, {
  1788. exclude: source.indentExclusionRanges,
  1789. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1790. });
  1791. trailingNewline = source.content.lastChar() === '\n';
  1792. });
  1793. if (this.intro) {
  1794. this.intro =
  1795. indentStr +
  1796. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1797. return index > 0 ? indentStr + match : match;
  1798. });
  1799. }
  1800. return this;
  1801. }
  1802. prepend(str) {
  1803. this.intro = str + this.intro;
  1804. return this;
  1805. }
  1806. toString() {
  1807. const body = this.sources
  1808. .map((source, i) => {
  1809. const separator = source.separator !== undefined ? source.separator : this.separator;
  1810. const str = (i > 0 ? separator : '') + source.content.toString();
  1811. return str;
  1812. })
  1813. .join('');
  1814. return this.intro + body;
  1815. }
  1816. isEmpty() {
  1817. if (this.intro.length && this.intro.trim()) return false;
  1818. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1819. return true;
  1820. }
  1821. length() {
  1822. return this.sources.reduce(
  1823. (length, source) => length + source.content.length(),
  1824. this.intro.length
  1825. );
  1826. }
  1827. trimLines() {
  1828. return this.trim('[\\r\\n]');
  1829. }
  1830. trim(charType) {
  1831. return this.trimStart(charType).trimEnd(charType);
  1832. }
  1833. trimStart(charType) {
  1834. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1835. this.intro = this.intro.replace(rx, '');
  1836. if (!this.intro) {
  1837. let source;
  1838. let i = 0;
  1839. do {
  1840. source = this.sources[i++];
  1841. if (!source) {
  1842. break;
  1843. }
  1844. } while (!source.content.trimStartAborted(charType));
  1845. }
  1846. return this;
  1847. }
  1848. trimEnd(charType) {
  1849. const rx = new RegExp((charType || '\\s') + '+$');
  1850. let source;
  1851. let i = this.sources.length - 1;
  1852. do {
  1853. source = this.sources[i--];
  1854. if (!source) {
  1855. this.intro = this.intro.replace(rx, '');
  1856. break;
  1857. }
  1858. } while (!source.content.trimEndAborted(charType));
  1859. return this;
  1860. }
  1861. }
  1862. function getOrCreate(map, key, init) {
  1863. const existing = map.get(key);
  1864. if (existing) {
  1865. return existing;
  1866. }
  1867. const value = init();
  1868. map.set(key, value);
  1869. return value;
  1870. }
  1871. const UnknownKey = Symbol('Unknown Key');
  1872. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1873. const UnknownInteger = Symbol('Unknown Integer');
  1874. const EMPTY_PATH = [];
  1875. const UNKNOWN_PATH = [UnknownKey];
  1876. // For deoptimizations, this means we are modifying an unknown property but did
  1877. // not lose track of the object or are creating a setter/getter;
  1878. // For assignment effects it means we do not check for setter/getter effects
  1879. // but only if something is mutated that is included, which is relevant for
  1880. // Object.defineProperty
  1881. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1882. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1883. const EntitiesKey = Symbol('Entities');
  1884. class PathTracker {
  1885. constructor() {
  1886. this.entityPaths = Object.create(null, {
  1887. [EntitiesKey]: { value: new Set() }
  1888. });
  1889. }
  1890. trackEntityAtPathAndGetIfTracked(path, entity) {
  1891. const trackedEntities = this.getEntities(path);
  1892. if (trackedEntities.has(entity))
  1893. return true;
  1894. trackedEntities.add(entity);
  1895. return false;
  1896. }
  1897. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1898. const trackedEntities = this.getEntities(path);
  1899. if (trackedEntities.has(entity))
  1900. return returnIfTracked;
  1901. trackedEntities.add(entity);
  1902. const result = onUntracked();
  1903. trackedEntities.delete(entity);
  1904. return result;
  1905. }
  1906. getEntities(path) {
  1907. let currentPaths = this.entityPaths;
  1908. for (const pathSegment of path) {
  1909. currentPaths = currentPaths[pathSegment] =
  1910. currentPaths[pathSegment] ||
  1911. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1912. }
  1913. return currentPaths[EntitiesKey];
  1914. }
  1915. }
  1916. const SHARED_RECURSION_TRACKER = new PathTracker();
  1917. class DiscriminatedPathTracker {
  1918. constructor() {
  1919. this.entityPaths = Object.create(null, {
  1920. [EntitiesKey]: { value: new Map() }
  1921. });
  1922. }
  1923. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1924. let currentPaths = this.entityPaths;
  1925. for (const pathSegment of path) {
  1926. currentPaths = currentPaths[pathSegment] =
  1927. currentPaths[pathSegment] ||
  1928. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1929. }
  1930. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1931. if (trackedEntities.has(entity))
  1932. return true;
  1933. trackedEntities.add(entity);
  1934. return false;
  1935. }
  1936. }
  1937. const UnknownValue = Symbol('Unknown Value');
  1938. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1939. class ExpressionEntity {
  1940. constructor() {
  1941. this.included = false;
  1942. }
  1943. deoptimizePath(_path) { }
  1944. deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
  1945. thisArg.deoptimizePath(UNKNOWN_PATH);
  1946. }
  1947. /**
  1948. * If possible it returns a stringifyable literal value for this node that can be used
  1949. * for inlining or comparing values.
  1950. * Otherwise it should return UnknownValue.
  1951. */
  1952. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1953. return UnknownValue;
  1954. }
  1955. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1956. return UNKNOWN_EXPRESSION;
  1957. }
  1958. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1959. return true;
  1960. }
  1961. include(_context, _includeChildrenRecursively, _options) {
  1962. this.included = true;
  1963. }
  1964. includeCallArguments(context, args) {
  1965. for (const arg of args) {
  1966. arg.include(context, false);
  1967. }
  1968. }
  1969. shouldBeIncluded(_context) {
  1970. return true;
  1971. }
  1972. }
  1973. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1974. })();
  1975. const INTERACTION_ACCESSED = 0;
  1976. const INTERACTION_ASSIGNED = 1;
  1977. const INTERACTION_CALLED = 2;
  1978. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1979. thisArg: null,
  1980. type: INTERACTION_ACCESSED
  1981. };
  1982. const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
  1983. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1984. args: UNKNOWN_ARG,
  1985. thisArg: null,
  1986. type: INTERACTION_ASSIGNED
  1987. };
  1988. const NO_ARGS = [];
  1989. // While this is technically a call without arguments, we can compare against
  1990. // this reference in places where precise values or thisArg would make a
  1991. // difference
  1992. const NODE_INTERACTION_UNKNOWN_CALL = {
  1993. args: NO_ARGS,
  1994. thisArg: null,
  1995. type: INTERACTION_CALLED,
  1996. withNew: false
  1997. };
  1998. class Variable extends ExpressionEntity {
  1999. constructor(name) {
  2000. super();
  2001. this.name = name;
  2002. this.alwaysRendered = false;
  2003. this.initReached = false;
  2004. this.isId = false;
  2005. this.isReassigned = false;
  2006. this.kind = null;
  2007. this.renderBaseName = null;
  2008. this.renderName = null;
  2009. }
  2010. /**
  2011. * Binds identifiers that reference this variable to this variable.
  2012. * Necessary to be able to change variable names.
  2013. */
  2014. addReference(_identifier) { }
  2015. getBaseVariableName() {
  2016. return this.renderBaseName || this.renderName || this.name;
  2017. }
  2018. getName(getPropertyAccess) {
  2019. const name = this.renderName || this.name;
  2020. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2021. }
  2022. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2023. return type !== INTERACTION_ACCESSED || path.length > 0;
  2024. }
  2025. /**
  2026. * Marks this variable as being part of the bundle, which is usually the case when one of
  2027. * its identifiers becomes part of the bundle. Returns true if it has not been included
  2028. * previously.
  2029. * Once a variable is included, it should take care all its declarations are included.
  2030. */
  2031. include() {
  2032. this.included = true;
  2033. }
  2034. markCalledFromTryStatement() { }
  2035. setRenderNames(baseName, name) {
  2036. this.renderBaseName = baseName;
  2037. this.renderName = name;
  2038. }
  2039. }
  2040. class ExternalVariable extends Variable {
  2041. constructor(module, name) {
  2042. super(name);
  2043. this.referenced = false;
  2044. this.module = module;
  2045. this.isNamespace = name === '*';
  2046. }
  2047. addReference(identifier) {
  2048. this.referenced = true;
  2049. if (this.name === 'default' || this.name === '*') {
  2050. this.module.suggestName(identifier.name);
  2051. }
  2052. }
  2053. hasEffectsOnInteractionAtPath(path, { type }) {
  2054. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2055. }
  2056. include() {
  2057. if (!this.included) {
  2058. this.included = true;
  2059. this.module.used = true;
  2060. }
  2061. }
  2062. }
  2063. const BLANK = Object.freeze(Object.create(null));
  2064. const EMPTY_OBJECT = Object.freeze({});
  2065. const EMPTY_ARRAY = Object.freeze([]);
  2066. const RESERVED_NAMES = new Set([
  2067. 'await',
  2068. 'break',
  2069. 'case',
  2070. 'catch',
  2071. 'class',
  2072. 'const',
  2073. 'continue',
  2074. 'debugger',
  2075. 'default',
  2076. 'delete',
  2077. 'do',
  2078. 'else',
  2079. 'enum',
  2080. 'eval',
  2081. 'export',
  2082. 'extends',
  2083. 'false',
  2084. 'finally',
  2085. 'for',
  2086. 'function',
  2087. 'if',
  2088. 'implements',
  2089. 'import',
  2090. 'in',
  2091. 'instanceof',
  2092. 'interface',
  2093. 'let',
  2094. 'NaN',
  2095. 'new',
  2096. 'null',
  2097. 'package',
  2098. 'private',
  2099. 'protected',
  2100. 'public',
  2101. 'return',
  2102. 'static',
  2103. 'super',
  2104. 'switch',
  2105. 'this',
  2106. 'throw',
  2107. 'true',
  2108. 'try',
  2109. 'typeof',
  2110. 'undefined',
  2111. 'var',
  2112. 'void',
  2113. 'while',
  2114. 'with',
  2115. 'yield'
  2116. ]);
  2117. const RESERVED_NAMES$1 = RESERVED_NAMES;
  2118. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  2119. const startsWithDigit = (str) => /\d/.test(str[0]);
  2120. const needsEscape = (str) => startsWithDigit(str) || RESERVED_NAMES$1.has(str) || str === 'arguments';
  2121. function isLegal(str) {
  2122. if (needsEscape(str)) {
  2123. return false;
  2124. }
  2125. return !illegalCharacters.test(str);
  2126. }
  2127. function makeLegal(str) {
  2128. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  2129. if (needsEscape(str))
  2130. str = `_${str}`;
  2131. return str || '_';
  2132. }
  2133. class ExternalModule {
  2134. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
  2135. this.options = options;
  2136. this.id = id;
  2137. this.renormalizeRenderPath = renormalizeRenderPath;
  2138. this.declarations = new Map();
  2139. this.defaultVariableName = '';
  2140. this.dynamicImporters = [];
  2141. this.execIndex = Infinity;
  2142. this.exportedVariables = new Map();
  2143. this.importers = [];
  2144. this.mostCommonSuggestion = 0;
  2145. this.nameSuggestions = new Map();
  2146. this.namespaceVariableName = '';
  2147. this.reexported = false;
  2148. this.renderPath = undefined;
  2149. this.used = false;
  2150. this.variableName = '';
  2151. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  2152. const { importers, dynamicImporters } = this;
  2153. const info = (this.info = {
  2154. ast: null,
  2155. code: null,
  2156. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2157. dynamicallyImportedIds: EMPTY_ARRAY,
  2158. get dynamicImporters() {
  2159. return dynamicImporters.sort();
  2160. },
  2161. hasDefaultExport: null,
  2162. get hasModuleSideEffects() {
  2163. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  2164. return info.moduleSideEffects;
  2165. },
  2166. id,
  2167. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2168. implicitlyLoadedBefore: EMPTY_ARRAY,
  2169. importedIdResolutions: EMPTY_ARRAY,
  2170. importedIds: EMPTY_ARRAY,
  2171. get importers() {
  2172. return importers.sort();
  2173. },
  2174. isEntry: false,
  2175. isExternal: true,
  2176. isIncluded: null,
  2177. meta,
  2178. moduleSideEffects,
  2179. syntheticNamedExports: false
  2180. });
  2181. // Hide the deprecated key so that it only warns when accessed explicitly
  2182. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2183. enumerable: false
  2184. });
  2185. }
  2186. getVariableForExportName(name) {
  2187. const declaration = this.declarations.get(name);
  2188. if (declaration)
  2189. return [declaration];
  2190. const externalVariable = new ExternalVariable(this, name);
  2191. this.declarations.set(name, externalVariable);
  2192. this.exportedVariables.set(externalVariable, name);
  2193. return [externalVariable];
  2194. }
  2195. setRenderPath(options, inputBase) {
  2196. this.renderPath =
  2197. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2198. if (!this.renderPath) {
  2199. this.renderPath = this.renormalizeRenderPath
  2200. ? normalize(require$$0.relative(inputBase, this.id))
  2201. : this.id;
  2202. }
  2203. }
  2204. suggestName(name) {
  2205. var _a;
  2206. const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
  2207. this.nameSuggestions.set(name, value);
  2208. if (value > this.mostCommonSuggestion) {
  2209. this.mostCommonSuggestion = value;
  2210. this.suggestedVariableName = name;
  2211. }
  2212. }
  2213. warnUnusedImports() {
  2214. const unused = Array.from(this.declarations)
  2215. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2216. .map(([name]) => name);
  2217. if (unused.length === 0)
  2218. return;
  2219. const importersSet = new Set();
  2220. for (const name of unused) {
  2221. for (const importer of this.declarations.get(name).module.importers) {
  2222. importersSet.add(importer);
  2223. }
  2224. }
  2225. const importersArray = [...importersSet];
  2226. this.options.onwarn({
  2227. code: 'UNUSED_EXTERNAL_IMPORT',
  2228. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  2229. names: unused,
  2230. source: this.id,
  2231. sources: importersArray
  2232. });
  2233. }
  2234. }
  2235. var picomatch$1 = {exports: {}};
  2236. var utils$3 = {};
  2237. const path$1 = require$$0;
  2238. const WIN_SLASH = '\\\\/';
  2239. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2240. /**
  2241. * Posix glob regex
  2242. */
  2243. const DOT_LITERAL = '\\.';
  2244. const PLUS_LITERAL = '\\+';
  2245. const QMARK_LITERAL = '\\?';
  2246. const SLASH_LITERAL = '\\/';
  2247. const ONE_CHAR = '(?=.)';
  2248. const QMARK = '[^/]';
  2249. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2250. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2251. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2252. const NO_DOT = `(?!${DOT_LITERAL})`;
  2253. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2254. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2255. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2256. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2257. const STAR = `${QMARK}*?`;
  2258. const POSIX_CHARS = {
  2259. DOT_LITERAL,
  2260. PLUS_LITERAL,
  2261. QMARK_LITERAL,
  2262. SLASH_LITERAL,
  2263. ONE_CHAR,
  2264. QMARK,
  2265. END_ANCHOR,
  2266. DOTS_SLASH,
  2267. NO_DOT,
  2268. NO_DOTS,
  2269. NO_DOT_SLASH,
  2270. NO_DOTS_SLASH,
  2271. QMARK_NO_DOT,
  2272. STAR,
  2273. START_ANCHOR
  2274. };
  2275. /**
  2276. * Windows glob regex
  2277. */
  2278. const WINDOWS_CHARS = {
  2279. ...POSIX_CHARS,
  2280. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2281. QMARK: WIN_NO_SLASH,
  2282. STAR: `${WIN_NO_SLASH}*?`,
  2283. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2284. NO_DOT: `(?!${DOT_LITERAL})`,
  2285. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2286. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2287. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2288. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2289. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2290. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2291. };
  2292. /**
  2293. * POSIX Bracket Regex
  2294. */
  2295. const POSIX_REGEX_SOURCE$1 = {
  2296. alnum: 'a-zA-Z0-9',
  2297. alpha: 'a-zA-Z',
  2298. ascii: '\\x00-\\x7F',
  2299. blank: ' \\t',
  2300. cntrl: '\\x00-\\x1F\\x7F',
  2301. digit: '0-9',
  2302. graph: '\\x21-\\x7E',
  2303. lower: 'a-z',
  2304. print: '\\x20-\\x7E ',
  2305. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2306. space: ' \\t\\r\\n\\v\\f',
  2307. upper: 'A-Z',
  2308. word: 'A-Za-z0-9_',
  2309. xdigit: 'A-Fa-f0-9'
  2310. };
  2311. var constants$2 = {
  2312. MAX_LENGTH: 1024 * 64,
  2313. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2314. // regular expressions
  2315. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2316. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2317. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2318. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2319. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2320. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2321. // Replace globs with equivalent patterns to reduce parsing time.
  2322. REPLACEMENTS: {
  2323. '***': '*',
  2324. '**/**': '**',
  2325. '**/**/**': '**'
  2326. },
  2327. // Digits
  2328. CHAR_0: 48, /* 0 */
  2329. CHAR_9: 57, /* 9 */
  2330. // Alphabet chars.
  2331. CHAR_UPPERCASE_A: 65, /* A */
  2332. CHAR_LOWERCASE_A: 97, /* a */
  2333. CHAR_UPPERCASE_Z: 90, /* Z */
  2334. CHAR_LOWERCASE_Z: 122, /* z */
  2335. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2336. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2337. CHAR_ASTERISK: 42, /* * */
  2338. // Non-alphabetic chars.
  2339. CHAR_AMPERSAND: 38, /* & */
  2340. CHAR_AT: 64, /* @ */
  2341. CHAR_BACKWARD_SLASH: 92, /* \ */
  2342. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2343. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2344. CHAR_COLON: 58, /* : */
  2345. CHAR_COMMA: 44, /* , */
  2346. CHAR_DOT: 46, /* . */
  2347. CHAR_DOUBLE_QUOTE: 34, /* " */
  2348. CHAR_EQUAL: 61, /* = */
  2349. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2350. CHAR_FORM_FEED: 12, /* \f */
  2351. CHAR_FORWARD_SLASH: 47, /* / */
  2352. CHAR_GRAVE_ACCENT: 96, /* ` */
  2353. CHAR_HASH: 35, /* # */
  2354. CHAR_HYPHEN_MINUS: 45, /* - */
  2355. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2356. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2357. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2358. CHAR_LINE_FEED: 10, /* \n */
  2359. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2360. CHAR_PERCENT: 37, /* % */
  2361. CHAR_PLUS: 43, /* + */
  2362. CHAR_QUESTION_MARK: 63, /* ? */
  2363. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2364. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2365. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2366. CHAR_SEMICOLON: 59, /* ; */
  2367. CHAR_SINGLE_QUOTE: 39, /* ' */
  2368. CHAR_SPACE: 32, /* */
  2369. CHAR_TAB: 9, /* \t */
  2370. CHAR_UNDERSCORE: 95, /* _ */
  2371. CHAR_VERTICAL_LINE: 124, /* | */
  2372. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2373. SEP: path$1.sep,
  2374. /**
  2375. * Create EXTGLOB_CHARS
  2376. */
  2377. extglobChars(chars) {
  2378. return {
  2379. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2380. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2381. '+': { type: 'plus', open: '(?:', close: ')+' },
  2382. '*': { type: 'star', open: '(?:', close: ')*' },
  2383. '@': { type: 'at', open: '(?:', close: ')' }
  2384. };
  2385. },
  2386. /**
  2387. * Create GLOB_CHARS
  2388. */
  2389. globChars(win32) {
  2390. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2391. }
  2392. };
  2393. (function (exports) {
  2394. const path = require$$0;
  2395. const win32 = process.platform === 'win32';
  2396. const {
  2397. REGEX_BACKSLASH,
  2398. REGEX_REMOVE_BACKSLASH,
  2399. REGEX_SPECIAL_CHARS,
  2400. REGEX_SPECIAL_CHARS_GLOBAL
  2401. } = constants$2;
  2402. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2403. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2404. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2405. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2406. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2407. exports.removeBackslashes = str => {
  2408. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2409. return match === '\\' ? '' : match;
  2410. });
  2411. };
  2412. exports.supportsLookbehinds = () => {
  2413. const segs = process.version.slice(1).split('.').map(Number);
  2414. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2415. return true;
  2416. }
  2417. return false;
  2418. };
  2419. exports.isWindows = options => {
  2420. if (options && typeof options.windows === 'boolean') {
  2421. return options.windows;
  2422. }
  2423. return win32 === true || path.sep === '\\';
  2424. };
  2425. exports.escapeLast = (input, char, lastIdx) => {
  2426. const idx = input.lastIndexOf(char, lastIdx);
  2427. if (idx === -1) return input;
  2428. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2429. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2430. };
  2431. exports.removePrefix = (input, state = {}) => {
  2432. let output = input;
  2433. if (output.startsWith('./')) {
  2434. output = output.slice(2);
  2435. state.prefix = './';
  2436. }
  2437. return output;
  2438. };
  2439. exports.wrapOutput = (input, state = {}, options = {}) => {
  2440. const prepend = options.contains ? '' : '^';
  2441. const append = options.contains ? '' : '$';
  2442. let output = `${prepend}(?:${input})${append}`;
  2443. if (state.negated === true) {
  2444. output = `(?:^(?!${output}).*$)`;
  2445. }
  2446. return output;
  2447. };
  2448. } (utils$3));
  2449. const utils$2 = utils$3;
  2450. const {
  2451. CHAR_ASTERISK, /* * */
  2452. CHAR_AT, /* @ */
  2453. CHAR_BACKWARD_SLASH, /* \ */
  2454. CHAR_COMMA, /* , */
  2455. CHAR_DOT, /* . */
  2456. CHAR_EXCLAMATION_MARK, /* ! */
  2457. CHAR_FORWARD_SLASH, /* / */
  2458. CHAR_LEFT_CURLY_BRACE, /* { */
  2459. CHAR_LEFT_PARENTHESES, /* ( */
  2460. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2461. CHAR_PLUS, /* + */
  2462. CHAR_QUESTION_MARK, /* ? */
  2463. CHAR_RIGHT_CURLY_BRACE, /* } */
  2464. CHAR_RIGHT_PARENTHESES, /* ) */
  2465. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2466. } = constants$2;
  2467. const isPathSeparator = code => {
  2468. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2469. };
  2470. const depth = token => {
  2471. if (token.isPrefix !== true) {
  2472. token.depth = token.isGlobstar ? Infinity : 1;
  2473. }
  2474. };
  2475. /**
  2476. * Quickly scans a glob pattern and returns an object with a handful of
  2477. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2478. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2479. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2480. *
  2481. * ```js
  2482. * const pm = require('picomatch');
  2483. * console.log(pm.scan('foo/bar/*.js'));
  2484. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2485. * ```
  2486. * @param {String} `str`
  2487. * @param {Object} `options`
  2488. * @return {Object} Returns an object with tokens and regex source string.
  2489. * @api public
  2490. */
  2491. const scan$1 = (input, options) => {
  2492. const opts = options || {};
  2493. const length = input.length - 1;
  2494. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2495. const slashes = [];
  2496. const tokens = [];
  2497. const parts = [];
  2498. let str = input;
  2499. let index = -1;
  2500. let start = 0;
  2501. let lastIndex = 0;
  2502. let isBrace = false;
  2503. let isBracket = false;
  2504. let isGlob = false;
  2505. let isExtglob = false;
  2506. let isGlobstar = false;
  2507. let braceEscaped = false;
  2508. let backslashes = false;
  2509. let negated = false;
  2510. let negatedExtglob = false;
  2511. let finished = false;
  2512. let braces = 0;
  2513. let prev;
  2514. let code;
  2515. let token = { value: '', depth: 0, isGlob: false };
  2516. const eos = () => index >= length;
  2517. const peek = () => str.charCodeAt(index + 1);
  2518. const advance = () => {
  2519. prev = code;
  2520. return str.charCodeAt(++index);
  2521. };
  2522. while (index < length) {
  2523. code = advance();
  2524. let next;
  2525. if (code === CHAR_BACKWARD_SLASH) {
  2526. backslashes = token.backslashes = true;
  2527. code = advance();
  2528. if (code === CHAR_LEFT_CURLY_BRACE) {
  2529. braceEscaped = true;
  2530. }
  2531. continue;
  2532. }
  2533. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2534. braces++;
  2535. while (eos() !== true && (code = advance())) {
  2536. if (code === CHAR_BACKWARD_SLASH) {
  2537. backslashes = token.backslashes = true;
  2538. advance();
  2539. continue;
  2540. }
  2541. if (code === CHAR_LEFT_CURLY_BRACE) {
  2542. braces++;
  2543. continue;
  2544. }
  2545. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2546. isBrace = token.isBrace = true;
  2547. isGlob = token.isGlob = true;
  2548. finished = true;
  2549. if (scanToEnd === true) {
  2550. continue;
  2551. }
  2552. break;
  2553. }
  2554. if (braceEscaped !== true && code === CHAR_COMMA) {
  2555. isBrace = token.isBrace = true;
  2556. isGlob = token.isGlob = true;
  2557. finished = true;
  2558. if (scanToEnd === true) {
  2559. continue;
  2560. }
  2561. break;
  2562. }
  2563. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2564. braces--;
  2565. if (braces === 0) {
  2566. braceEscaped = false;
  2567. isBrace = token.isBrace = true;
  2568. finished = true;
  2569. break;
  2570. }
  2571. }
  2572. }
  2573. if (scanToEnd === true) {
  2574. continue;
  2575. }
  2576. break;
  2577. }
  2578. if (code === CHAR_FORWARD_SLASH) {
  2579. slashes.push(index);
  2580. tokens.push(token);
  2581. token = { value: '', depth: 0, isGlob: false };
  2582. if (finished === true) continue;
  2583. if (prev === CHAR_DOT && index === (start + 1)) {
  2584. start += 2;
  2585. continue;
  2586. }
  2587. lastIndex = index + 1;
  2588. continue;
  2589. }
  2590. if (opts.noext !== true) {
  2591. const isExtglobChar = code === CHAR_PLUS
  2592. || code === CHAR_AT
  2593. || code === CHAR_ASTERISK
  2594. || code === CHAR_QUESTION_MARK
  2595. || code === CHAR_EXCLAMATION_MARK;
  2596. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2597. isGlob = token.isGlob = true;
  2598. isExtglob = token.isExtglob = true;
  2599. finished = true;
  2600. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2601. negatedExtglob = true;
  2602. }
  2603. if (scanToEnd === true) {
  2604. while (eos() !== true && (code = advance())) {
  2605. if (code === CHAR_BACKWARD_SLASH) {
  2606. backslashes = token.backslashes = true;
  2607. code = advance();
  2608. continue;
  2609. }
  2610. if (code === CHAR_RIGHT_PARENTHESES) {
  2611. isGlob = token.isGlob = true;
  2612. finished = true;
  2613. break;
  2614. }
  2615. }
  2616. continue;
  2617. }
  2618. break;
  2619. }
  2620. }
  2621. if (code === CHAR_ASTERISK) {
  2622. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2623. isGlob = token.isGlob = true;
  2624. finished = true;
  2625. if (scanToEnd === true) {
  2626. continue;
  2627. }
  2628. break;
  2629. }
  2630. if (code === CHAR_QUESTION_MARK) {
  2631. isGlob = token.isGlob = true;
  2632. finished = true;
  2633. if (scanToEnd === true) {
  2634. continue;
  2635. }
  2636. break;
  2637. }
  2638. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2639. while (eos() !== true && (next = advance())) {
  2640. if (next === CHAR_BACKWARD_SLASH) {
  2641. backslashes = token.backslashes = true;
  2642. advance();
  2643. continue;
  2644. }
  2645. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2646. isBracket = token.isBracket = true;
  2647. isGlob = token.isGlob = true;
  2648. finished = true;
  2649. break;
  2650. }
  2651. }
  2652. if (scanToEnd === true) {
  2653. continue;
  2654. }
  2655. break;
  2656. }
  2657. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2658. negated = token.negated = true;
  2659. start++;
  2660. continue;
  2661. }
  2662. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2663. isGlob = token.isGlob = true;
  2664. if (scanToEnd === true) {
  2665. while (eos() !== true && (code = advance())) {
  2666. if (code === CHAR_LEFT_PARENTHESES) {
  2667. backslashes = token.backslashes = true;
  2668. code = advance();
  2669. continue;
  2670. }
  2671. if (code === CHAR_RIGHT_PARENTHESES) {
  2672. finished = true;
  2673. break;
  2674. }
  2675. }
  2676. continue;
  2677. }
  2678. break;
  2679. }
  2680. if (isGlob === true) {
  2681. finished = true;
  2682. if (scanToEnd === true) {
  2683. continue;
  2684. }
  2685. break;
  2686. }
  2687. }
  2688. if (opts.noext === true) {
  2689. isExtglob = false;
  2690. isGlob = false;
  2691. }
  2692. let base = str;
  2693. let prefix = '';
  2694. let glob = '';
  2695. if (start > 0) {
  2696. prefix = str.slice(0, start);
  2697. str = str.slice(start);
  2698. lastIndex -= start;
  2699. }
  2700. if (base && isGlob === true && lastIndex > 0) {
  2701. base = str.slice(0, lastIndex);
  2702. glob = str.slice(lastIndex);
  2703. } else if (isGlob === true) {
  2704. base = '';
  2705. glob = str;
  2706. } else {
  2707. base = str;
  2708. }
  2709. if (base && base !== '' && base !== '/' && base !== str) {
  2710. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2711. base = base.slice(0, -1);
  2712. }
  2713. }
  2714. if (opts.unescape === true) {
  2715. if (glob) glob = utils$2.removeBackslashes(glob);
  2716. if (base && backslashes === true) {
  2717. base = utils$2.removeBackslashes(base);
  2718. }
  2719. }
  2720. const state = {
  2721. prefix,
  2722. input,
  2723. start,
  2724. base,
  2725. glob,
  2726. isBrace,
  2727. isBracket,
  2728. isGlob,
  2729. isExtglob,
  2730. isGlobstar,
  2731. negated,
  2732. negatedExtglob
  2733. };
  2734. if (opts.tokens === true) {
  2735. state.maxDepth = 0;
  2736. if (!isPathSeparator(code)) {
  2737. tokens.push(token);
  2738. }
  2739. state.tokens = tokens;
  2740. }
  2741. if (opts.parts === true || opts.tokens === true) {
  2742. let prevIndex;
  2743. for (let idx = 0; idx < slashes.length; idx++) {
  2744. const n = prevIndex ? prevIndex + 1 : start;
  2745. const i = slashes[idx];
  2746. const value = input.slice(n, i);
  2747. if (opts.tokens) {
  2748. if (idx === 0 && start !== 0) {
  2749. tokens[idx].isPrefix = true;
  2750. tokens[idx].value = prefix;
  2751. } else {
  2752. tokens[idx].value = value;
  2753. }
  2754. depth(tokens[idx]);
  2755. state.maxDepth += tokens[idx].depth;
  2756. }
  2757. if (idx !== 0 || value !== '') {
  2758. parts.push(value);
  2759. }
  2760. prevIndex = i;
  2761. }
  2762. if (prevIndex && prevIndex + 1 < input.length) {
  2763. const value = input.slice(prevIndex + 1);
  2764. parts.push(value);
  2765. if (opts.tokens) {
  2766. tokens[tokens.length - 1].value = value;
  2767. depth(tokens[tokens.length - 1]);
  2768. state.maxDepth += tokens[tokens.length - 1].depth;
  2769. }
  2770. }
  2771. state.slashes = slashes;
  2772. state.parts = parts;
  2773. }
  2774. return state;
  2775. };
  2776. var scan_1 = scan$1;
  2777. const constants$1 = constants$2;
  2778. const utils$1 = utils$3;
  2779. /**
  2780. * Constants
  2781. */
  2782. const {
  2783. MAX_LENGTH,
  2784. POSIX_REGEX_SOURCE,
  2785. REGEX_NON_SPECIAL_CHARS,
  2786. REGEX_SPECIAL_CHARS_BACKREF,
  2787. REPLACEMENTS
  2788. } = constants$1;
  2789. /**
  2790. * Helpers
  2791. */
  2792. const expandRange = (args, options) => {
  2793. if (typeof options.expandRange === 'function') {
  2794. return options.expandRange(...args, options);
  2795. }
  2796. args.sort();
  2797. const value = `[${args.join('-')}]`;
  2798. return value;
  2799. };
  2800. /**
  2801. * Create the message for a syntax error
  2802. */
  2803. const syntaxError = (type, char) => {
  2804. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2805. };
  2806. /**
  2807. * Parse the given input string.
  2808. * @param {String} input
  2809. * @param {Object} options
  2810. * @return {Object}
  2811. */
  2812. const parse$1 = (input, options) => {
  2813. if (typeof input !== 'string') {
  2814. throw new TypeError('Expected a string');
  2815. }
  2816. input = REPLACEMENTS[input] || input;
  2817. const opts = { ...options };
  2818. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2819. let len = input.length;
  2820. if (len > max) {
  2821. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2822. }
  2823. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2824. const tokens = [bos];
  2825. const capture = opts.capture ? '' : '?:';
  2826. const win32 = utils$1.isWindows(options);
  2827. // create constants based on platform, for windows or posix
  2828. const PLATFORM_CHARS = constants$1.globChars(win32);
  2829. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  2830. const {
  2831. DOT_LITERAL,
  2832. PLUS_LITERAL,
  2833. SLASH_LITERAL,
  2834. ONE_CHAR,
  2835. DOTS_SLASH,
  2836. NO_DOT,
  2837. NO_DOT_SLASH,
  2838. NO_DOTS_SLASH,
  2839. QMARK,
  2840. QMARK_NO_DOT,
  2841. STAR,
  2842. START_ANCHOR
  2843. } = PLATFORM_CHARS;
  2844. const globstar = opts => {
  2845. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2846. };
  2847. const nodot = opts.dot ? '' : NO_DOT;
  2848. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2849. let star = opts.bash === true ? globstar(opts) : STAR;
  2850. if (opts.capture) {
  2851. star = `(${star})`;
  2852. }
  2853. // minimatch options support
  2854. if (typeof opts.noext === 'boolean') {
  2855. opts.noextglob = opts.noext;
  2856. }
  2857. const state = {
  2858. input,
  2859. index: -1,
  2860. start: 0,
  2861. dot: opts.dot === true,
  2862. consumed: '',
  2863. output: '',
  2864. prefix: '',
  2865. backtrack: false,
  2866. negated: false,
  2867. brackets: 0,
  2868. braces: 0,
  2869. parens: 0,
  2870. quotes: 0,
  2871. globstar: false,
  2872. tokens
  2873. };
  2874. input = utils$1.removePrefix(input, state);
  2875. len = input.length;
  2876. const extglobs = [];
  2877. const braces = [];
  2878. const stack = [];
  2879. let prev = bos;
  2880. let value;
  2881. /**
  2882. * Tokenizing helpers
  2883. */
  2884. const eos = () => state.index === len - 1;
  2885. const peek = state.peek = (n = 1) => input[state.index + n];
  2886. const advance = state.advance = () => input[++state.index] || '';
  2887. const remaining = () => input.slice(state.index + 1);
  2888. const consume = (value = '', num = 0) => {
  2889. state.consumed += value;
  2890. state.index += num;
  2891. };
  2892. const append = token => {
  2893. state.output += token.output != null ? token.output : token.value;
  2894. consume(token.value);
  2895. };
  2896. const negate = () => {
  2897. let count = 1;
  2898. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2899. advance();
  2900. state.start++;
  2901. count++;
  2902. }
  2903. if (count % 2 === 0) {
  2904. return false;
  2905. }
  2906. state.negated = true;
  2907. state.start++;
  2908. return true;
  2909. };
  2910. const increment = type => {
  2911. state[type]++;
  2912. stack.push(type);
  2913. };
  2914. const decrement = type => {
  2915. state[type]--;
  2916. stack.pop();
  2917. };
  2918. /**
  2919. * Push tokens onto the tokens array. This helper speeds up
  2920. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2921. * and 2) helping us avoid creating extra tokens when consecutive
  2922. * characters are plain text. This improves performance and simplifies
  2923. * lookbehinds.
  2924. */
  2925. const push = tok => {
  2926. if (prev.type === 'globstar') {
  2927. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2928. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2929. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2930. state.output = state.output.slice(0, -prev.output.length);
  2931. prev.type = 'star';
  2932. prev.value = '*';
  2933. prev.output = star;
  2934. state.output += prev.output;
  2935. }
  2936. }
  2937. if (extglobs.length && tok.type !== 'paren') {
  2938. extglobs[extglobs.length - 1].inner += tok.value;
  2939. }
  2940. if (tok.value || tok.output) append(tok);
  2941. if (prev && prev.type === 'text' && tok.type === 'text') {
  2942. prev.value += tok.value;
  2943. prev.output = (prev.output || '') + tok.value;
  2944. return;
  2945. }
  2946. tok.prev = prev;
  2947. tokens.push(tok);
  2948. prev = tok;
  2949. };
  2950. const extglobOpen = (type, value) => {
  2951. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2952. token.prev = prev;
  2953. token.parens = state.parens;
  2954. token.output = state.output;
  2955. const output = (opts.capture ? '(' : '') + token.open;
  2956. increment('parens');
  2957. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2958. push({ type: 'paren', extglob: true, value: advance(), output });
  2959. extglobs.push(token);
  2960. };
  2961. const extglobClose = token => {
  2962. let output = token.close + (opts.capture ? ')' : '');
  2963. let rest;
  2964. if (token.type === 'negate') {
  2965. let extglobStar = star;
  2966. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2967. extglobStar = globstar(opts);
  2968. }
  2969. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2970. output = token.close = `)$))${extglobStar}`;
  2971. }
  2972. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2973. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2974. // In this case, we need to parse the string and use it in the output of the original pattern.
  2975. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2976. //
  2977. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2978. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2979. output = token.close = `)${expression})${extglobStar})`;
  2980. }
  2981. if (token.prev.type === 'bos') {
  2982. state.negatedExtglob = true;
  2983. }
  2984. }
  2985. push({ type: 'paren', extglob: true, value, output });
  2986. decrement('parens');
  2987. };
  2988. /**
  2989. * Fast paths
  2990. */
  2991. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2992. let backslashes = false;
  2993. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2994. if (first === '\\') {
  2995. backslashes = true;
  2996. return m;
  2997. }
  2998. if (first === '?') {
  2999. if (esc) {
  3000. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  3001. }
  3002. if (index === 0) {
  3003. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  3004. }
  3005. return QMARK.repeat(chars.length);
  3006. }
  3007. if (first === '.') {
  3008. return DOT_LITERAL.repeat(chars.length);
  3009. }
  3010. if (first === '*') {
  3011. if (esc) {
  3012. return esc + first + (rest ? star : '');
  3013. }
  3014. return star;
  3015. }
  3016. return esc ? m : `\\${m}`;
  3017. });
  3018. if (backslashes === true) {
  3019. if (opts.unescape === true) {
  3020. output = output.replace(/\\/g, '');
  3021. } else {
  3022. output = output.replace(/\\+/g, m => {
  3023. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3024. });
  3025. }
  3026. }
  3027. if (output === input && opts.contains === true) {
  3028. state.output = input;
  3029. return state;
  3030. }
  3031. state.output = utils$1.wrapOutput(output, state, options);
  3032. return state;
  3033. }
  3034. /**
  3035. * Tokenize input until we reach end-of-string
  3036. */
  3037. while (!eos()) {
  3038. value = advance();
  3039. if (value === '\u0000') {
  3040. continue;
  3041. }
  3042. /**
  3043. * Escaped characters
  3044. */
  3045. if (value === '\\') {
  3046. const next = peek();
  3047. if (next === '/' && opts.bash !== true) {
  3048. continue;
  3049. }
  3050. if (next === '.' || next === ';') {
  3051. continue;
  3052. }
  3053. if (!next) {
  3054. value += '\\';
  3055. push({ type: 'text', value });
  3056. continue;
  3057. }
  3058. // collapse slashes to reduce potential for exploits
  3059. const match = /^\\+/.exec(remaining());
  3060. let slashes = 0;
  3061. if (match && match[0].length > 2) {
  3062. slashes = match[0].length;
  3063. state.index += slashes;
  3064. if (slashes % 2 !== 0) {
  3065. value += '\\';
  3066. }
  3067. }
  3068. if (opts.unescape === true) {
  3069. value = advance();
  3070. } else {
  3071. value += advance();
  3072. }
  3073. if (state.brackets === 0) {
  3074. push({ type: 'text', value });
  3075. continue;
  3076. }
  3077. }
  3078. /**
  3079. * If we're inside a regex character class, continue
  3080. * until we reach the closing bracket.
  3081. */
  3082. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3083. if (opts.posix !== false && value === ':') {
  3084. const inner = prev.value.slice(1);
  3085. if (inner.includes('[')) {
  3086. prev.posix = true;
  3087. if (inner.includes(':')) {
  3088. const idx = prev.value.lastIndexOf('[');
  3089. const pre = prev.value.slice(0, idx);
  3090. const rest = prev.value.slice(idx + 2);
  3091. const posix = POSIX_REGEX_SOURCE[rest];
  3092. if (posix) {
  3093. prev.value = pre + posix;
  3094. state.backtrack = true;
  3095. advance();
  3096. if (!bos.output && tokens.indexOf(prev) === 1) {
  3097. bos.output = ONE_CHAR;
  3098. }
  3099. continue;
  3100. }
  3101. }
  3102. }
  3103. }
  3104. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3105. value = `\\${value}`;
  3106. }
  3107. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3108. value = `\\${value}`;
  3109. }
  3110. if (opts.posix === true && value === '!' && prev.value === '[') {
  3111. value = '^';
  3112. }
  3113. prev.value += value;
  3114. append({ value });
  3115. continue;
  3116. }
  3117. /**
  3118. * If we're inside a quoted string, continue
  3119. * until we reach the closing double quote.
  3120. */
  3121. if (state.quotes === 1 && value !== '"') {
  3122. value = utils$1.escapeRegex(value);
  3123. prev.value += value;
  3124. append({ value });
  3125. continue;
  3126. }
  3127. /**
  3128. * Double quotes
  3129. */
  3130. if (value === '"') {
  3131. state.quotes = state.quotes === 1 ? 0 : 1;
  3132. if (opts.keepQuotes === true) {
  3133. push({ type: 'text', value });
  3134. }
  3135. continue;
  3136. }
  3137. /**
  3138. * Parentheses
  3139. */
  3140. if (value === '(') {
  3141. increment('parens');
  3142. push({ type: 'paren', value });
  3143. continue;
  3144. }
  3145. if (value === ')') {
  3146. if (state.parens === 0 && opts.strictBrackets === true) {
  3147. throw new SyntaxError(syntaxError('opening', '('));
  3148. }
  3149. const extglob = extglobs[extglobs.length - 1];
  3150. if (extglob && state.parens === extglob.parens + 1) {
  3151. extglobClose(extglobs.pop());
  3152. continue;
  3153. }
  3154. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3155. decrement('parens');
  3156. continue;
  3157. }
  3158. /**
  3159. * Square brackets
  3160. */
  3161. if (value === '[') {
  3162. if (opts.nobracket === true || !remaining().includes(']')) {
  3163. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3164. throw new SyntaxError(syntaxError('closing', ']'));
  3165. }
  3166. value = `\\${value}`;
  3167. } else {
  3168. increment('brackets');
  3169. }
  3170. push({ type: 'bracket', value });
  3171. continue;
  3172. }
  3173. if (value === ']') {
  3174. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3175. push({ type: 'text', value, output: `\\${value}` });
  3176. continue;
  3177. }
  3178. if (state.brackets === 0) {
  3179. if (opts.strictBrackets === true) {
  3180. throw new SyntaxError(syntaxError('opening', '['));
  3181. }
  3182. push({ type: 'text', value, output: `\\${value}` });
  3183. continue;
  3184. }
  3185. decrement('brackets');
  3186. const prevValue = prev.value.slice(1);
  3187. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3188. value = `/${value}`;
  3189. }
  3190. prev.value += value;
  3191. append({ value });
  3192. // when literal brackets are explicitly disabled
  3193. // assume we should match with a regex character class
  3194. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3195. continue;
  3196. }
  3197. const escaped = utils$1.escapeRegex(prev.value);
  3198. state.output = state.output.slice(0, -prev.value.length);
  3199. // when literal brackets are explicitly enabled
  3200. // assume we should escape the brackets to match literal characters
  3201. if (opts.literalBrackets === true) {
  3202. state.output += escaped;
  3203. prev.value = escaped;
  3204. continue;
  3205. }
  3206. // when the user specifies nothing, try to match both
  3207. prev.value = `(${capture}${escaped}|${prev.value})`;
  3208. state.output += prev.value;
  3209. continue;
  3210. }
  3211. /**
  3212. * Braces
  3213. */
  3214. if (value === '{' && opts.nobrace !== true) {
  3215. increment('braces');
  3216. const open = {
  3217. type: 'brace',
  3218. value,
  3219. output: '(',
  3220. outputIndex: state.output.length,
  3221. tokensIndex: state.tokens.length
  3222. };
  3223. braces.push(open);
  3224. push(open);
  3225. continue;
  3226. }
  3227. if (value === '}') {
  3228. const brace = braces[braces.length - 1];
  3229. if (opts.nobrace === true || !brace) {
  3230. push({ type: 'text', value, output: value });
  3231. continue;
  3232. }
  3233. let output = ')';
  3234. if (brace.dots === true) {
  3235. const arr = tokens.slice();
  3236. const range = [];
  3237. for (let i = arr.length - 1; i >= 0; i--) {
  3238. tokens.pop();
  3239. if (arr[i].type === 'brace') {
  3240. break;
  3241. }
  3242. if (arr[i].type !== 'dots') {
  3243. range.unshift(arr[i].value);
  3244. }
  3245. }
  3246. output = expandRange(range, opts);
  3247. state.backtrack = true;
  3248. }
  3249. if (brace.comma !== true && brace.dots !== true) {
  3250. const out = state.output.slice(0, brace.outputIndex);
  3251. const toks = state.tokens.slice(brace.tokensIndex);
  3252. brace.value = brace.output = '\\{';
  3253. value = output = '\\}';
  3254. state.output = out;
  3255. for (const t of toks) {
  3256. state.output += (t.output || t.value);
  3257. }
  3258. }
  3259. push({ type: 'brace', value, output });
  3260. decrement('braces');
  3261. braces.pop();
  3262. continue;
  3263. }
  3264. /**
  3265. * Pipes
  3266. */
  3267. if (value === '|') {
  3268. if (extglobs.length > 0) {
  3269. extglobs[extglobs.length - 1].conditions++;
  3270. }
  3271. push({ type: 'text', value });
  3272. continue;
  3273. }
  3274. /**
  3275. * Commas
  3276. */
  3277. if (value === ',') {
  3278. let output = value;
  3279. const brace = braces[braces.length - 1];
  3280. if (brace && stack[stack.length - 1] === 'braces') {
  3281. brace.comma = true;
  3282. output = '|';
  3283. }
  3284. push({ type: 'comma', value, output });
  3285. continue;
  3286. }
  3287. /**
  3288. * Slashes
  3289. */
  3290. if (value === '/') {
  3291. // if the beginning of the glob is "./", advance the start
  3292. // to the current index, and don't add the "./" characters
  3293. // to the state. This greatly simplifies lookbehinds when
  3294. // checking for BOS characters like "!" and "." (not "./")
  3295. if (prev.type === 'dot' && state.index === state.start + 1) {
  3296. state.start = state.index + 1;
  3297. state.consumed = '';
  3298. state.output = '';
  3299. tokens.pop();
  3300. prev = bos; // reset "prev" to the first token
  3301. continue;
  3302. }
  3303. push({ type: 'slash', value, output: SLASH_LITERAL });
  3304. continue;
  3305. }
  3306. /**
  3307. * Dots
  3308. */
  3309. if (value === '.') {
  3310. if (state.braces > 0 && prev.type === 'dot') {
  3311. if (prev.value === '.') prev.output = DOT_LITERAL;
  3312. const brace = braces[braces.length - 1];
  3313. prev.type = 'dots';
  3314. prev.output += value;
  3315. prev.value += value;
  3316. brace.dots = true;
  3317. continue;
  3318. }
  3319. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3320. push({ type: 'text', value, output: DOT_LITERAL });
  3321. continue;
  3322. }
  3323. push({ type: 'dot', value, output: DOT_LITERAL });
  3324. continue;
  3325. }
  3326. /**
  3327. * Question marks
  3328. */
  3329. if (value === '?') {
  3330. const isGroup = prev && prev.value === '(';
  3331. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3332. extglobOpen('qmark', value);
  3333. continue;
  3334. }
  3335. if (prev && prev.type === 'paren') {
  3336. const next = peek();
  3337. let output = value;
  3338. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3339. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3340. }
  3341. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3342. output = `\\${value}`;
  3343. }
  3344. push({ type: 'text', value, output });
  3345. continue;
  3346. }
  3347. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3348. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3349. continue;
  3350. }
  3351. push({ type: 'qmark', value, output: QMARK });
  3352. continue;
  3353. }
  3354. /**
  3355. * Exclamation
  3356. */
  3357. if (value === '!') {
  3358. if (opts.noextglob !== true && peek() === '(') {
  3359. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3360. extglobOpen('negate', value);
  3361. continue;
  3362. }
  3363. }
  3364. if (opts.nonegate !== true && state.index === 0) {
  3365. negate();
  3366. continue;
  3367. }
  3368. }
  3369. /**
  3370. * Plus
  3371. */
  3372. if (value === '+') {
  3373. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3374. extglobOpen('plus', value);
  3375. continue;
  3376. }
  3377. if ((prev && prev.value === '(') || opts.regex === false) {
  3378. push({ type: 'plus', value, output: PLUS_LITERAL });
  3379. continue;
  3380. }
  3381. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3382. push({ type: 'plus', value });
  3383. continue;
  3384. }
  3385. push({ type: 'plus', value: PLUS_LITERAL });
  3386. continue;
  3387. }
  3388. /**
  3389. * Plain text
  3390. */
  3391. if (value === '@') {
  3392. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3393. push({ type: 'at', extglob: true, value, output: '' });
  3394. continue;
  3395. }
  3396. push({ type: 'text', value });
  3397. continue;
  3398. }
  3399. /**
  3400. * Plain text
  3401. */
  3402. if (value !== '*') {
  3403. if (value === '$' || value === '^') {
  3404. value = `\\${value}`;
  3405. }
  3406. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3407. if (match) {
  3408. value += match[0];
  3409. state.index += match[0].length;
  3410. }
  3411. push({ type: 'text', value });
  3412. continue;
  3413. }
  3414. /**
  3415. * Stars
  3416. */
  3417. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3418. prev.type = 'star';
  3419. prev.star = true;
  3420. prev.value += value;
  3421. prev.output = star;
  3422. state.backtrack = true;
  3423. state.globstar = true;
  3424. consume(value);
  3425. continue;
  3426. }
  3427. let rest = remaining();
  3428. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3429. extglobOpen('star', value);
  3430. continue;
  3431. }
  3432. if (prev.type === 'star') {
  3433. if (opts.noglobstar === true) {
  3434. consume(value);
  3435. continue;
  3436. }
  3437. const prior = prev.prev;
  3438. const before = prior.prev;
  3439. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3440. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3441. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3442. push({ type: 'star', value, output: '' });
  3443. continue;
  3444. }
  3445. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3446. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3447. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3448. push({ type: 'star', value, output: '' });
  3449. continue;
  3450. }
  3451. // strip consecutive `/**/`
  3452. while (rest.slice(0, 3) === '/**') {
  3453. const after = input[state.index + 4];
  3454. if (after && after !== '/') {
  3455. break;
  3456. }
  3457. rest = rest.slice(3);
  3458. consume('/**', 3);
  3459. }
  3460. if (prior.type === 'bos' && eos()) {
  3461. prev.type = 'globstar';
  3462. prev.value += value;
  3463. prev.output = globstar(opts);
  3464. state.output = prev.output;
  3465. state.globstar = true;
  3466. consume(value);
  3467. continue;
  3468. }
  3469. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3470. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3471. prior.output = `(?:${prior.output}`;
  3472. prev.type = 'globstar';
  3473. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3474. prev.value += value;
  3475. state.globstar = true;
  3476. state.output += prior.output + prev.output;
  3477. consume(value);
  3478. continue;
  3479. }
  3480. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3481. const end = rest[1] !== void 0 ? '|$' : '';
  3482. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3483. prior.output = `(?:${prior.output}`;
  3484. prev.type = 'globstar';
  3485. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3486. prev.value += value;
  3487. state.output += prior.output + prev.output;
  3488. state.globstar = true;
  3489. consume(value + advance());
  3490. push({ type: 'slash', value: '/', output: '' });
  3491. continue;
  3492. }
  3493. if (prior.type === 'bos' && rest[0] === '/') {
  3494. prev.type = 'globstar';
  3495. prev.value += value;
  3496. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3497. state.output = prev.output;
  3498. state.globstar = true;
  3499. consume(value + advance());
  3500. push({ type: 'slash', value: '/', output: '' });
  3501. continue;
  3502. }
  3503. // remove single star from output
  3504. state.output = state.output.slice(0, -prev.output.length);
  3505. // reset previous token to globstar
  3506. prev.type = 'globstar';
  3507. prev.output = globstar(opts);
  3508. prev.value += value;
  3509. // reset output with globstar
  3510. state.output += prev.output;
  3511. state.globstar = true;
  3512. consume(value);
  3513. continue;
  3514. }
  3515. const token = { type: 'star', value, output: star };
  3516. if (opts.bash === true) {
  3517. token.output = '.*?';
  3518. if (prev.type === 'bos' || prev.type === 'slash') {
  3519. token.output = nodot + token.output;
  3520. }
  3521. push(token);
  3522. continue;
  3523. }
  3524. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3525. token.output = value;
  3526. push(token);
  3527. continue;
  3528. }
  3529. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3530. if (prev.type === 'dot') {
  3531. state.output += NO_DOT_SLASH;
  3532. prev.output += NO_DOT_SLASH;
  3533. } else if (opts.dot === true) {
  3534. state.output += NO_DOTS_SLASH;
  3535. prev.output += NO_DOTS_SLASH;
  3536. } else {
  3537. state.output += nodot;
  3538. prev.output += nodot;
  3539. }
  3540. if (peek() !== '*') {
  3541. state.output += ONE_CHAR;
  3542. prev.output += ONE_CHAR;
  3543. }
  3544. }
  3545. push(token);
  3546. }
  3547. while (state.brackets > 0) {
  3548. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3549. state.output = utils$1.escapeLast(state.output, '[');
  3550. decrement('brackets');
  3551. }
  3552. while (state.parens > 0) {
  3553. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3554. state.output = utils$1.escapeLast(state.output, '(');
  3555. decrement('parens');
  3556. }
  3557. while (state.braces > 0) {
  3558. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3559. state.output = utils$1.escapeLast(state.output, '{');
  3560. decrement('braces');
  3561. }
  3562. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3563. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3564. }
  3565. // rebuild the output if we had to backtrack at any point
  3566. if (state.backtrack === true) {
  3567. state.output = '';
  3568. for (const token of state.tokens) {
  3569. state.output += token.output != null ? token.output : token.value;
  3570. if (token.suffix) {
  3571. state.output += token.suffix;
  3572. }
  3573. }
  3574. }
  3575. return state;
  3576. };
  3577. /**
  3578. * Fast paths for creating regular expressions for common glob patterns.
  3579. * This can significantly speed up processing and has very little downside
  3580. * impact when none of the fast paths match.
  3581. */
  3582. parse$1.fastpaths = (input, options) => {
  3583. const opts = { ...options };
  3584. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3585. const len = input.length;
  3586. if (len > max) {
  3587. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3588. }
  3589. input = REPLACEMENTS[input] || input;
  3590. const win32 = utils$1.isWindows(options);
  3591. // create constants based on platform, for windows or posix
  3592. const {
  3593. DOT_LITERAL,
  3594. SLASH_LITERAL,
  3595. ONE_CHAR,
  3596. DOTS_SLASH,
  3597. NO_DOT,
  3598. NO_DOTS,
  3599. NO_DOTS_SLASH,
  3600. STAR,
  3601. START_ANCHOR
  3602. } = constants$1.globChars(win32);
  3603. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3604. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3605. const capture = opts.capture ? '' : '?:';
  3606. const state = { negated: false, prefix: '' };
  3607. let star = opts.bash === true ? '.*?' : STAR;
  3608. if (opts.capture) {
  3609. star = `(${star})`;
  3610. }
  3611. const globstar = opts => {
  3612. if (opts.noglobstar === true) return star;
  3613. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3614. };
  3615. const create = str => {
  3616. switch (str) {
  3617. case '*':
  3618. return `${nodot}${ONE_CHAR}${star}`;
  3619. case '.*':
  3620. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3621. case '*.*':
  3622. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3623. case '*/*':
  3624. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3625. case '**':
  3626. return nodot + globstar(opts);
  3627. case '**/*':
  3628. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3629. case '**/*.*':
  3630. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3631. case '**/.*':
  3632. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3633. default: {
  3634. const match = /^(.*?)\.(\w+)$/.exec(str);
  3635. if (!match) return;
  3636. const source = create(match[1]);
  3637. if (!source) return;
  3638. return source + DOT_LITERAL + match[2];
  3639. }
  3640. }
  3641. };
  3642. const output = utils$1.removePrefix(input, state);
  3643. let source = create(output);
  3644. if (source && opts.strictSlashes !== true) {
  3645. source += `${SLASH_LITERAL}?`;
  3646. }
  3647. return source;
  3648. };
  3649. var parse_1 = parse$1;
  3650. const path = require$$0;
  3651. const scan = scan_1;
  3652. const parse = parse_1;
  3653. const utils = utils$3;
  3654. const constants = constants$2;
  3655. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3656. /**
  3657. * Creates a matcher function from one or more glob patterns. The
  3658. * returned function takes a string to match as its first argument,
  3659. * and returns true if the string is a match. The returned matcher
  3660. * function also takes a boolean as the second argument that, when true,
  3661. * returns an object with additional information.
  3662. *
  3663. * ```js
  3664. * const picomatch = require('picomatch');
  3665. * // picomatch(glob[, options]);
  3666. *
  3667. * const isMatch = picomatch('*.!(*a)');
  3668. * console.log(isMatch('a.a')); //=> false
  3669. * console.log(isMatch('a.b')); //=> true
  3670. * ```
  3671. * @name picomatch
  3672. * @param {String|Array} `globs` One or more glob patterns.
  3673. * @param {Object=} `options`
  3674. * @return {Function=} Returns a matcher function.
  3675. * @api public
  3676. */
  3677. const picomatch = (glob, options, returnState = false) => {
  3678. if (Array.isArray(glob)) {
  3679. const fns = glob.map(input => picomatch(input, options, returnState));
  3680. const arrayMatcher = str => {
  3681. for (const isMatch of fns) {
  3682. const state = isMatch(str);
  3683. if (state) return state;
  3684. }
  3685. return false;
  3686. };
  3687. return arrayMatcher;
  3688. }
  3689. const isState = isObject(glob) && glob.tokens && glob.input;
  3690. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3691. throw new TypeError('Expected pattern to be a non-empty string');
  3692. }
  3693. const opts = options || {};
  3694. const posix = utils.isWindows(options);
  3695. const regex = isState
  3696. ? picomatch.compileRe(glob, options)
  3697. : picomatch.makeRe(glob, options, false, true);
  3698. const state = regex.state;
  3699. delete regex.state;
  3700. let isIgnored = () => false;
  3701. if (opts.ignore) {
  3702. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3703. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  3704. }
  3705. const matcher = (input, returnObject = false) => {
  3706. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  3707. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3708. if (typeof opts.onResult === 'function') {
  3709. opts.onResult(result);
  3710. }
  3711. if (isMatch === false) {
  3712. result.isMatch = false;
  3713. return returnObject ? result : false;
  3714. }
  3715. if (isIgnored(input)) {
  3716. if (typeof opts.onIgnore === 'function') {
  3717. opts.onIgnore(result);
  3718. }
  3719. result.isMatch = false;
  3720. return returnObject ? result : false;
  3721. }
  3722. if (typeof opts.onMatch === 'function') {
  3723. opts.onMatch(result);
  3724. }
  3725. return returnObject ? result : true;
  3726. };
  3727. if (returnState) {
  3728. matcher.state = state;
  3729. }
  3730. return matcher;
  3731. };
  3732. /**
  3733. * Test `input` with the given `regex`. This is used by the main
  3734. * `picomatch()` function to test the input string.
  3735. *
  3736. * ```js
  3737. * const picomatch = require('picomatch');
  3738. * // picomatch.test(input, regex[, options]);
  3739. *
  3740. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3741. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3742. * ```
  3743. * @param {String} `input` String to test.
  3744. * @param {RegExp} `regex`
  3745. * @return {Object} Returns an object with matching info.
  3746. * @api public
  3747. */
  3748. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  3749. if (typeof input !== 'string') {
  3750. throw new TypeError('Expected input to be a string');
  3751. }
  3752. if (input === '') {
  3753. return { isMatch: false, output: '' };
  3754. }
  3755. const opts = options || {};
  3756. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3757. let match = input === glob;
  3758. let output = (match && format) ? format(input) : input;
  3759. if (match === false) {
  3760. output = format ? format(input) : input;
  3761. match = output === glob;
  3762. }
  3763. if (match === false || opts.capture === true) {
  3764. if (opts.matchBase === true || opts.basename === true) {
  3765. match = picomatch.matchBase(input, regex, options, posix);
  3766. } else {
  3767. match = regex.exec(output);
  3768. }
  3769. }
  3770. return { isMatch: Boolean(match), match, output };
  3771. };
  3772. /**
  3773. * Match the basename of a filepath.
  3774. *
  3775. * ```js
  3776. * const picomatch = require('picomatch');
  3777. * // picomatch.matchBase(input, glob[, options]);
  3778. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3779. * ```
  3780. * @param {String} `input` String to test.
  3781. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3782. * @return {Boolean}
  3783. * @api public
  3784. */
  3785. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3786. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  3787. return regex.test(path.basename(input));
  3788. };
  3789. /**
  3790. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3791. *
  3792. * ```js
  3793. * const picomatch = require('picomatch');
  3794. * // picomatch.isMatch(string, patterns[, options]);
  3795. *
  3796. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3797. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3798. * ```
  3799. * @param {String|Array} str The string to test.
  3800. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3801. * @param {Object} [options] See available [options](#options).
  3802. * @return {Boolean} Returns true if any patterns match `str`
  3803. * @api public
  3804. */
  3805. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3806. /**
  3807. * Parse a glob pattern to create the source string for a regular
  3808. * expression.
  3809. *
  3810. * ```js
  3811. * const picomatch = require('picomatch');
  3812. * const result = picomatch.parse(pattern[, options]);
  3813. * ```
  3814. * @param {String} `pattern`
  3815. * @param {Object} `options`
  3816. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3817. * @api public
  3818. */
  3819. picomatch.parse = (pattern, options) => {
  3820. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  3821. return parse(pattern, { ...options, fastpaths: false });
  3822. };
  3823. /**
  3824. * Scan a glob pattern to separate the pattern into segments.
  3825. *
  3826. * ```js
  3827. * const picomatch = require('picomatch');
  3828. * // picomatch.scan(input[, options]);
  3829. *
  3830. * const result = picomatch.scan('!./foo/*.js');
  3831. * console.log(result);
  3832. * { prefix: '!./',
  3833. * input: '!./foo/*.js',
  3834. * start: 3,
  3835. * base: 'foo',
  3836. * glob: '*.js',
  3837. * isBrace: false,
  3838. * isBracket: false,
  3839. * isGlob: true,
  3840. * isExtglob: false,
  3841. * isGlobstar: false,
  3842. * negated: true }
  3843. * ```
  3844. * @param {String} `input` Glob pattern to scan.
  3845. * @param {Object} `options`
  3846. * @return {Object} Returns an object with
  3847. * @api public
  3848. */
  3849. picomatch.scan = (input, options) => scan(input, options);
  3850. /**
  3851. * Compile a regular expression from the `state` object returned by the
  3852. * [parse()](#parse) method.
  3853. *
  3854. * @param {Object} `state`
  3855. * @param {Object} `options`
  3856. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3857. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3858. * @return {RegExp}
  3859. * @api public
  3860. */
  3861. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3862. if (returnOutput === true) {
  3863. return state.output;
  3864. }
  3865. const opts = options || {};
  3866. const prepend = opts.contains ? '' : '^';
  3867. const append = opts.contains ? '' : '$';
  3868. let source = `${prepend}(?:${state.output})${append}`;
  3869. if (state && state.negated === true) {
  3870. source = `^(?!${source}).*$`;
  3871. }
  3872. const regex = picomatch.toRegex(source, options);
  3873. if (returnState === true) {
  3874. regex.state = state;
  3875. }
  3876. return regex;
  3877. };
  3878. /**
  3879. * Create a regular expression from a parsed glob pattern.
  3880. *
  3881. * ```js
  3882. * const picomatch = require('picomatch');
  3883. * const state = picomatch.parse('*.js');
  3884. * // picomatch.compileRe(state[, options]);
  3885. *
  3886. * console.log(picomatch.compileRe(state));
  3887. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3888. * ```
  3889. * @param {String} `state` The object returned from the `.parse` method.
  3890. * @param {Object} `options`
  3891. * @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.
  3892. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3893. * @return {RegExp} Returns a regex created from the given pattern.
  3894. * @api public
  3895. */
  3896. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3897. if (!input || typeof input !== 'string') {
  3898. throw new TypeError('Expected a non-empty string');
  3899. }
  3900. let parsed = { negated: false, fastpaths: true };
  3901. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3902. parsed.output = parse.fastpaths(input, options);
  3903. }
  3904. if (!parsed.output) {
  3905. parsed = parse(input, options);
  3906. }
  3907. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  3908. };
  3909. /**
  3910. * Create a regular expression from the given regex source string.
  3911. *
  3912. * ```js
  3913. * const picomatch = require('picomatch');
  3914. * // picomatch.toRegex(source[, options]);
  3915. *
  3916. * const { output } = picomatch.parse('*.js');
  3917. * console.log(picomatch.toRegex(output));
  3918. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3919. * ```
  3920. * @param {String} `source` Regular expression source string.
  3921. * @param {Object} `options`
  3922. * @return {RegExp}
  3923. * @api public
  3924. */
  3925. picomatch.toRegex = (source, options) => {
  3926. try {
  3927. const opts = options || {};
  3928. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3929. } catch (err) {
  3930. if (options && options.debug === true) throw err;
  3931. return /$^/;
  3932. }
  3933. };
  3934. /**
  3935. * Picomatch constants.
  3936. * @return {Object}
  3937. */
  3938. picomatch.constants = constants;
  3939. /**
  3940. * Expose "picomatch"
  3941. */
  3942. var picomatch_1 = picomatch;
  3943. (function (module) {
  3944. module.exports = picomatch_1;
  3945. } (picomatch$1));
  3946. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
  3947. const extractors = {
  3948. ArrayPattern(names, param) {
  3949. for (const element of param.elements) {
  3950. if (element)
  3951. extractors[element.type](names, element);
  3952. }
  3953. },
  3954. AssignmentPattern(names, param) {
  3955. extractors[param.left.type](names, param.left);
  3956. },
  3957. Identifier(names, param) {
  3958. names.push(param.name);
  3959. },
  3960. MemberExpression() { },
  3961. ObjectPattern(names, param) {
  3962. for (const prop of param.properties) {
  3963. // @ts-ignore Typescript reports that this is not a valid type
  3964. if (prop.type === 'RestElement') {
  3965. extractors.RestElement(names, prop);
  3966. }
  3967. else {
  3968. extractors[prop.value.type](names, prop.value);
  3969. }
  3970. }
  3971. },
  3972. RestElement(names, param) {
  3973. extractors[param.argument.type](names, param.argument);
  3974. }
  3975. };
  3976. const extractAssignedNames = function extractAssignedNames(param) {
  3977. const names = [];
  3978. extractors[param.type](names, param);
  3979. return names;
  3980. };
  3981. // Helper since Typescript can't detect readonly arrays with Array.isArray
  3982. function isArray$1(arg) {
  3983. return Array.isArray(arg);
  3984. }
  3985. function ensureArray(thing) {
  3986. if (isArray$1(thing))
  3987. return thing;
  3988. if (thing == null)
  3989. return [];
  3990. return [thing];
  3991. }
  3992. const normalizePath = function normalizePath(filename) {
  3993. return filename.split(require$$0.win32.sep).join(require$$0.posix.sep);
  3994. };
  3995. function getMatcherString(id, resolutionBase) {
  3996. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('*')) {
  3997. return normalizePath(id);
  3998. }
  3999. // resolve('') is valid and will default to process.cwd()
  4000. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  4001. // escape all possible (posix + win) path characters that might interfere with regex
  4002. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  4003. // Note that we use posix.join because:
  4004. // 1. the basePath has been normalized to use /
  4005. // 2. the incoming glob (id) matcher, also uses /
  4006. // otherwise Node will force backslash (\) on windows
  4007. return require$$0.posix.join(basePath, normalizePath(id));
  4008. }
  4009. const createFilter = function createFilter(include, exclude, options) {
  4010. const resolutionBase = options && options.resolve;
  4011. const getMatcher = (id) => id instanceof RegExp
  4012. ? id
  4013. : {
  4014. test: (what) => {
  4015. // this refactor is a tad overly verbose but makes for easy debugging
  4016. const pattern = getMatcherString(id, resolutionBase);
  4017. const fn = pm(pattern, { dot: true });
  4018. const result = fn(what);
  4019. return result;
  4020. }
  4021. };
  4022. const includeMatchers = ensureArray(include).map(getMatcher);
  4023. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  4024. return function result(id) {
  4025. if (typeof id !== 'string')
  4026. return false;
  4027. if (/\0/.test(id))
  4028. return false;
  4029. const pathId = normalizePath(id);
  4030. for (let i = 0; i < excludeMatchers.length; ++i) {
  4031. const matcher = excludeMatchers[i];
  4032. if (matcher.test(pathId))
  4033. return false;
  4034. }
  4035. for (let i = 0; i < includeMatchers.length; ++i) {
  4036. const matcher = includeMatchers[i];
  4037. if (matcher.test(pathId))
  4038. return true;
  4039. }
  4040. return !includeMatchers.length;
  4041. };
  4042. };
  4043. 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';
  4044. 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';
  4045. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  4046. forbiddenIdentifiers.add('');
  4047. const BROKEN_FLOW_NONE = 0;
  4048. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  4049. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  4050. function createInclusionContext() {
  4051. return {
  4052. brokenFlow: BROKEN_FLOW_NONE,
  4053. includedCallArguments: new Set(),
  4054. includedLabels: new Set()
  4055. };
  4056. }
  4057. function createHasEffectsContext() {
  4058. return {
  4059. accessed: new PathTracker(),
  4060. assigned: new PathTracker(),
  4061. brokenFlow: BROKEN_FLOW_NONE,
  4062. called: new DiscriminatedPathTracker(),
  4063. ignore: {
  4064. breaks: false,
  4065. continues: false,
  4066. labels: new Set(),
  4067. returnYield: false
  4068. },
  4069. includedLabels: new Set(),
  4070. instantiated: new DiscriminatedPathTracker(),
  4071. replacedVariableInits: new Map()
  4072. };
  4073. }
  4074. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  4075. return Object.create(inheritedDescriptions, memberDescriptions);
  4076. }
  4077. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  4078. getLiteralValueAtPath() {
  4079. return undefined;
  4080. }
  4081. })();
  4082. const returnsUnknown = {
  4083. value: {
  4084. hasEffectsWhenCalled: null,
  4085. returns: UNKNOWN_EXPRESSION
  4086. }
  4087. };
  4088. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  4089. getReturnExpressionWhenCalledAtPath(path) {
  4090. if (path.length === 1) {
  4091. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  4092. }
  4093. return UNKNOWN_EXPRESSION;
  4094. }
  4095. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4096. if (interaction.type === INTERACTION_ACCESSED) {
  4097. return path.length > 1;
  4098. }
  4099. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4100. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  4101. }
  4102. return true;
  4103. }
  4104. })();
  4105. const returnsBoolean = {
  4106. value: {
  4107. hasEffectsWhenCalled: null,
  4108. returns: UNKNOWN_LITERAL_BOOLEAN
  4109. }
  4110. };
  4111. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  4112. getReturnExpressionWhenCalledAtPath(path) {
  4113. if (path.length === 1) {
  4114. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  4115. }
  4116. return UNKNOWN_EXPRESSION;
  4117. }
  4118. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4119. if (interaction.type === INTERACTION_ACCESSED) {
  4120. return path.length > 1;
  4121. }
  4122. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4123. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4124. }
  4125. return true;
  4126. }
  4127. })();
  4128. const returnsNumber = {
  4129. value: {
  4130. hasEffectsWhenCalled: null,
  4131. returns: UNKNOWN_LITERAL_NUMBER
  4132. }
  4133. };
  4134. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4135. getReturnExpressionWhenCalledAtPath(path) {
  4136. if (path.length === 1) {
  4137. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4138. }
  4139. return UNKNOWN_EXPRESSION;
  4140. }
  4141. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4142. if (interaction.type === INTERACTION_ACCESSED) {
  4143. return path.length > 1;
  4144. }
  4145. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4146. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4147. }
  4148. return true;
  4149. }
  4150. })();
  4151. const returnsString = {
  4152. value: {
  4153. hasEffectsWhenCalled: null,
  4154. returns: UNKNOWN_LITERAL_STRING
  4155. }
  4156. };
  4157. const stringReplace = {
  4158. value: {
  4159. hasEffectsWhenCalled({ args }, context) {
  4160. const arg1 = args[1];
  4161. return (args.length < 2 ||
  4162. (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4163. deoptimizeCache() { }
  4164. }) === 'symbol' &&
  4165. arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4166. },
  4167. returns: UNKNOWN_LITERAL_STRING
  4168. }
  4169. };
  4170. const objectMembers = assembleMemberDescriptions({
  4171. hasOwnProperty: returnsBoolean,
  4172. isPrototypeOf: returnsBoolean,
  4173. propertyIsEnumerable: returnsBoolean,
  4174. toLocaleString: returnsString,
  4175. toString: returnsString,
  4176. valueOf: returnsUnknown
  4177. });
  4178. const literalBooleanMembers = assembleMemberDescriptions({
  4179. valueOf: returnsBoolean
  4180. }, objectMembers);
  4181. const literalNumberMembers = assembleMemberDescriptions({
  4182. toExponential: returnsString,
  4183. toFixed: returnsString,
  4184. toLocaleString: returnsString,
  4185. toPrecision: returnsString,
  4186. valueOf: returnsNumber
  4187. }, objectMembers);
  4188. const literalStringMembers = assembleMemberDescriptions({
  4189. anchor: returnsString,
  4190. at: returnsUnknown,
  4191. big: returnsString,
  4192. blink: returnsString,
  4193. bold: returnsString,
  4194. charAt: returnsString,
  4195. charCodeAt: returnsNumber,
  4196. codePointAt: returnsUnknown,
  4197. concat: returnsString,
  4198. endsWith: returnsBoolean,
  4199. fixed: returnsString,
  4200. fontcolor: returnsString,
  4201. fontsize: returnsString,
  4202. includes: returnsBoolean,
  4203. indexOf: returnsNumber,
  4204. italics: returnsString,
  4205. lastIndexOf: returnsNumber,
  4206. link: returnsString,
  4207. localeCompare: returnsNumber,
  4208. match: returnsUnknown,
  4209. matchAll: returnsUnknown,
  4210. normalize: returnsString,
  4211. padEnd: returnsString,
  4212. padStart: returnsString,
  4213. repeat: returnsString,
  4214. replace: stringReplace,
  4215. replaceAll: stringReplace,
  4216. search: returnsNumber,
  4217. slice: returnsString,
  4218. small: returnsString,
  4219. split: returnsUnknown,
  4220. startsWith: returnsBoolean,
  4221. strike: returnsString,
  4222. sub: returnsString,
  4223. substr: returnsString,
  4224. substring: returnsString,
  4225. sup: returnsString,
  4226. toLocaleLowerCase: returnsString,
  4227. toLocaleUpperCase: returnsString,
  4228. toLowerCase: returnsString,
  4229. toString: returnsString,
  4230. toUpperCase: returnsString,
  4231. trim: returnsString,
  4232. trimEnd: returnsString,
  4233. trimLeft: returnsString,
  4234. trimRight: returnsString,
  4235. trimStart: returnsString,
  4236. valueOf: returnsString
  4237. }, objectMembers);
  4238. function getLiteralMembersForValue(value) {
  4239. switch (typeof value) {
  4240. case 'boolean':
  4241. return literalBooleanMembers;
  4242. case 'number':
  4243. return literalNumberMembers;
  4244. case 'string':
  4245. return literalStringMembers;
  4246. }
  4247. return Object.create(null);
  4248. }
  4249. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4250. var _a, _b;
  4251. if (typeof memberName !== 'string' || !members[memberName]) {
  4252. return true;
  4253. }
  4254. return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
  4255. }
  4256. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4257. if (typeof memberName !== 'string' || !members[memberName])
  4258. return UNKNOWN_EXPRESSION;
  4259. return members[memberName].returns;
  4260. }
  4261. // AST walker module for Mozilla Parser API compatible trees
  4262. function skipThrough(node, st, c) { c(node, st); }
  4263. function ignore(_node, _st, _c) {}
  4264. // Node walkers.
  4265. var base$1 = {};
  4266. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  4267. for (var i = 0, list = node.body; i < list.length; i += 1)
  4268. {
  4269. var stmt = list[i];
  4270. c(stmt, st, "Statement");
  4271. }
  4272. };
  4273. base$1.Statement = skipThrough;
  4274. base$1.EmptyStatement = ignore;
  4275. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  4276. function (node, st, c) { return c(node.expression, st, "Expression"); };
  4277. base$1.IfStatement = function (node, st, c) {
  4278. c(node.test, st, "Expression");
  4279. c(node.consequent, st, "Statement");
  4280. if (node.alternate) { c(node.alternate, st, "Statement"); }
  4281. };
  4282. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  4283. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  4284. base$1.WithStatement = function (node, st, c) {
  4285. c(node.object, st, "Expression");
  4286. c(node.body, st, "Statement");
  4287. };
  4288. base$1.SwitchStatement = function (node, st, c) {
  4289. c(node.discriminant, st, "Expression");
  4290. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  4291. var cs = list$1[i$1];
  4292. if (cs.test) { c(cs.test, st, "Expression"); }
  4293. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  4294. {
  4295. var cons = list[i];
  4296. c(cons, st, "Statement");
  4297. }
  4298. }
  4299. };
  4300. base$1.SwitchCase = function (node, st, c) {
  4301. if (node.test) { c(node.test, st, "Expression"); }
  4302. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  4303. {
  4304. var cons = list[i];
  4305. c(cons, st, "Statement");
  4306. }
  4307. };
  4308. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  4309. if (node.argument) { c(node.argument, st, "Expression"); }
  4310. };
  4311. base$1.ThrowStatement = base$1.SpreadElement =
  4312. function (node, st, c) { return c(node.argument, st, "Expression"); };
  4313. base$1.TryStatement = function (node, st, c) {
  4314. c(node.block, st, "Statement");
  4315. if (node.handler) { c(node.handler, st); }
  4316. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  4317. };
  4318. base$1.CatchClause = function (node, st, c) {
  4319. if (node.param) { c(node.param, st, "Pattern"); }
  4320. c(node.body, st, "Statement");
  4321. };
  4322. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  4323. c(node.test, st, "Expression");
  4324. c(node.body, st, "Statement");
  4325. };
  4326. base$1.ForStatement = function (node, st, c) {
  4327. if (node.init) { c(node.init, st, "ForInit"); }
  4328. if (node.test) { c(node.test, st, "Expression"); }
  4329. if (node.update) { c(node.update, st, "Expression"); }
  4330. c(node.body, st, "Statement");
  4331. };
  4332. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  4333. c(node.left, st, "ForInit");
  4334. c(node.right, st, "Expression");
  4335. c(node.body, st, "Statement");
  4336. };
  4337. base$1.ForInit = function (node, st, c) {
  4338. if (node.type === "VariableDeclaration") { c(node, st); }
  4339. else { c(node, st, "Expression"); }
  4340. };
  4341. base$1.DebuggerStatement = ignore;
  4342. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  4343. base$1.VariableDeclaration = function (node, st, c) {
  4344. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  4345. {
  4346. var decl = list[i];
  4347. c(decl, st);
  4348. }
  4349. };
  4350. base$1.VariableDeclarator = function (node, st, c) {
  4351. c(node.id, st, "Pattern");
  4352. if (node.init) { c(node.init, st, "Expression"); }
  4353. };
  4354. base$1.Function = function (node, st, c) {
  4355. if (node.id) { c(node.id, st, "Pattern"); }
  4356. for (var i = 0, list = node.params; i < list.length; i += 1)
  4357. {
  4358. var param = list[i];
  4359. c(param, st, "Pattern");
  4360. }
  4361. c(node.body, st, node.expression ? "Expression" : "Statement");
  4362. };
  4363. base$1.Pattern = function (node, st, c) {
  4364. if (node.type === "Identifier")
  4365. { c(node, st, "VariablePattern"); }
  4366. else if (node.type === "MemberExpression")
  4367. { c(node, st, "MemberPattern"); }
  4368. else
  4369. { c(node, st); }
  4370. };
  4371. base$1.VariablePattern = ignore;
  4372. base$1.MemberPattern = skipThrough;
  4373. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  4374. base$1.ArrayPattern = function (node, st, c) {
  4375. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4376. var elt = list[i];
  4377. if (elt) { c(elt, st, "Pattern"); }
  4378. }
  4379. };
  4380. base$1.ObjectPattern = function (node, st, c) {
  4381. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  4382. var prop = list[i];
  4383. if (prop.type === "Property") {
  4384. if (prop.computed) { c(prop.key, st, "Expression"); }
  4385. c(prop.value, st, "Pattern");
  4386. } else if (prop.type === "RestElement") {
  4387. c(prop.argument, st, "Pattern");
  4388. }
  4389. }
  4390. };
  4391. base$1.Expression = skipThrough;
  4392. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  4393. base$1.ArrayExpression = function (node, st, c) {
  4394. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4395. var elt = list[i];
  4396. if (elt) { c(elt, st, "Expression"); }
  4397. }
  4398. };
  4399. base$1.ObjectExpression = function (node, st, c) {
  4400. for (var i = 0, list = node.properties; i < list.length; i += 1)
  4401. {
  4402. var prop = list[i];
  4403. c(prop, st);
  4404. }
  4405. };
  4406. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  4407. base$1.SequenceExpression = function (node, st, c) {
  4408. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  4409. {
  4410. var expr = list[i];
  4411. c(expr, st, "Expression");
  4412. }
  4413. };
  4414. base$1.TemplateLiteral = function (node, st, c) {
  4415. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  4416. {
  4417. var quasi = list[i];
  4418. c(quasi, st);
  4419. }
  4420. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  4421. {
  4422. var expr = list$1[i$1];
  4423. c(expr, st, "Expression");
  4424. }
  4425. };
  4426. base$1.TemplateElement = ignore;
  4427. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  4428. c(node.argument, st, "Expression");
  4429. };
  4430. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  4431. c(node.left, st, "Expression");
  4432. c(node.right, st, "Expression");
  4433. };
  4434. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  4435. c(node.left, st, "Pattern");
  4436. c(node.right, st, "Expression");
  4437. };
  4438. base$1.ConditionalExpression = function (node, st, c) {
  4439. c(node.test, st, "Expression");
  4440. c(node.consequent, st, "Expression");
  4441. c(node.alternate, st, "Expression");
  4442. };
  4443. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  4444. c(node.callee, st, "Expression");
  4445. if (node.arguments)
  4446. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  4447. {
  4448. var arg = list[i];
  4449. c(arg, st, "Expression");
  4450. } }
  4451. };
  4452. base$1.MemberExpression = function (node, st, c) {
  4453. c(node.object, st, "Expression");
  4454. if (node.computed) { c(node.property, st, "Expression"); }
  4455. };
  4456. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  4457. if (node.declaration)
  4458. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  4459. if (node.source) { c(node.source, st, "Expression"); }
  4460. };
  4461. base$1.ExportAllDeclaration = function (node, st, c) {
  4462. if (node.exported)
  4463. { c(node.exported, st); }
  4464. c(node.source, st, "Expression");
  4465. };
  4466. base$1.ImportDeclaration = function (node, st, c) {
  4467. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  4468. {
  4469. var spec = list[i];
  4470. c(spec, st);
  4471. }
  4472. c(node.source, st, "Expression");
  4473. };
  4474. base$1.ImportExpression = function (node, st, c) {
  4475. c(node.source, st, "Expression");
  4476. };
  4477. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  4478. base$1.TaggedTemplateExpression = function (node, st, c) {
  4479. c(node.tag, st, "Expression");
  4480. c(node.quasi, st, "Expression");
  4481. };
  4482. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  4483. base$1.Class = function (node, st, c) {
  4484. if (node.id) { c(node.id, st, "Pattern"); }
  4485. if (node.superClass) { c(node.superClass, st, "Expression"); }
  4486. c(node.body, st);
  4487. };
  4488. base$1.ClassBody = function (node, st, c) {
  4489. for (var i = 0, list = node.body; i < list.length; i += 1)
  4490. {
  4491. var elt = list[i];
  4492. c(elt, st);
  4493. }
  4494. };
  4495. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  4496. if (node.computed) { c(node.key, st, "Expression"); }
  4497. if (node.value) { c(node.value, st, "Expression"); }
  4498. };
  4499. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  4500. const BinaryExpression$1 = 'BinaryExpression';
  4501. const BlockStatement$1 = 'BlockStatement';
  4502. const CallExpression$1 = 'CallExpression';
  4503. const ChainExpression$1 = 'ChainExpression';
  4504. const ConditionalExpression$1 = 'ConditionalExpression';
  4505. const ExpressionStatement$1 = 'ExpressionStatement';
  4506. const Identifier$1 = 'Identifier';
  4507. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  4508. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  4509. const LogicalExpression$1 = 'LogicalExpression';
  4510. const NewExpression$1 = 'NewExpression';
  4511. const Program$1 = 'Program';
  4512. const Property$1 = 'Property';
  4513. const ReturnStatement$1 = 'ReturnStatement';
  4514. const SequenceExpression$1 = 'SequenceExpression';
  4515. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  4516. // this for an actual sourceMappingURL
  4517. exports.SOURCEMAPPING_URL = 'sourceMa';
  4518. exports.SOURCEMAPPING_URL += 'ppingURL';
  4519. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  4520. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${exports.SOURCEMAPPING_URL}=.+`);
  4521. const ANNOTATION_KEY = '_rollupAnnotations';
  4522. const INVALID_COMMENT_KEY = '_rollupRemoved';
  4523. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  4524. const { annotations } = state;
  4525. let comment = annotations[state.annotationIndex];
  4526. while (comment && node.start >= comment.end) {
  4527. markPureNode(node, comment, state.code);
  4528. comment = annotations[++state.annotationIndex];
  4529. }
  4530. if (comment && comment.end <= node.end) {
  4531. base$1[type](node, state, handlePureAnnotationsOfNode);
  4532. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  4533. ++state.annotationIndex;
  4534. annotateNode(node, comment, false);
  4535. }
  4536. }
  4537. }
  4538. const neitherWithespaceNorBrackets = /[^\s(]/g;
  4539. const noWhitespace = /\S/g;
  4540. function markPureNode(node, comment, code) {
  4541. const annotatedNodes = [];
  4542. let invalidAnnotation;
  4543. const codeInBetween = code.slice(comment.end, node.start);
  4544. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  4545. const parentStart = node.start;
  4546. while (true) {
  4547. annotatedNodes.push(node);
  4548. switch (node.type) {
  4549. case ExpressionStatement$1:
  4550. case ChainExpression$1:
  4551. node = node.expression;
  4552. continue;
  4553. case SequenceExpression$1:
  4554. // if there are parentheses, the annotation would apply to the entire expression
  4555. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4556. node = node.expressions[0];
  4557. continue;
  4558. }
  4559. invalidAnnotation = true;
  4560. break;
  4561. case ConditionalExpression$1:
  4562. // if there are parentheses, the annotation would apply to the entire expression
  4563. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4564. node = node.test;
  4565. continue;
  4566. }
  4567. invalidAnnotation = true;
  4568. break;
  4569. case LogicalExpression$1:
  4570. case BinaryExpression$1:
  4571. // if there are parentheses, the annotation would apply to the entire expression
  4572. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4573. node = node.left;
  4574. continue;
  4575. }
  4576. invalidAnnotation = true;
  4577. break;
  4578. case CallExpression$1:
  4579. case NewExpression$1:
  4580. break;
  4581. default:
  4582. invalidAnnotation = true;
  4583. }
  4584. break;
  4585. }
  4586. }
  4587. else {
  4588. invalidAnnotation = true;
  4589. }
  4590. if (invalidAnnotation) {
  4591. annotateNode(node, comment, false);
  4592. }
  4593. else {
  4594. for (const node of annotatedNodes) {
  4595. annotateNode(node, comment, true);
  4596. }
  4597. }
  4598. }
  4599. function doesNotMatchOutsideComment(code, forbiddenChars) {
  4600. let nextMatch;
  4601. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  4602. if (nextMatch[0] === '/') {
  4603. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  4604. if (charCodeAfterSlash === 42 /*"*"*/) {
  4605. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  4606. continue;
  4607. }
  4608. else if (charCodeAfterSlash === 47 /*"/"*/) {
  4609. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  4610. continue;
  4611. }
  4612. }
  4613. forbiddenChars.lastIndex = 0;
  4614. return false;
  4615. }
  4616. return true;
  4617. }
  4618. const pureCommentRegex = /[@#]__PURE__/;
  4619. function addAnnotations(comments, esTreeAst, code) {
  4620. const annotations = [];
  4621. const sourceMappingComments = [];
  4622. for (const comment of comments) {
  4623. if (pureCommentRegex.test(comment.value)) {
  4624. annotations.push(comment);
  4625. }
  4626. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  4627. sourceMappingComments.push(comment);
  4628. }
  4629. }
  4630. for (const comment of sourceMappingComments) {
  4631. annotateNode(esTreeAst, comment, false);
  4632. }
  4633. handlePureAnnotationsOfNode(esTreeAst, {
  4634. annotationIndex: 0,
  4635. annotations,
  4636. code
  4637. });
  4638. }
  4639. function annotateNode(node, comment, valid) {
  4640. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  4641. const property = node[key];
  4642. if (property) {
  4643. property.push(comment);
  4644. }
  4645. else {
  4646. node[key] = [comment];
  4647. }
  4648. }
  4649. const keys = {
  4650. Literal: [],
  4651. Program: ['body']
  4652. };
  4653. function getAndCreateKeys(esTreeNode) {
  4654. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4655. return keys[esTreeNode.type];
  4656. }
  4657. const INCLUDE_PARAMETERS = 'variables';
  4658. class NodeBase extends ExpressionEntity {
  4659. constructor(esTreeNode, parent, parentScope) {
  4660. super();
  4661. /**
  4662. * Nodes can apply custom deoptimizations once they become part of the
  4663. * executed code. To do this, they must initialize this as false, implement
  4664. * applyDeoptimizations and call this from include and hasEffects if they have
  4665. * custom handlers
  4666. */
  4667. this.deoptimized = false;
  4668. this.esTreeNode = esTreeNode;
  4669. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  4670. this.parent = parent;
  4671. this.context = parent.context;
  4672. this.createScope(parentScope);
  4673. this.parseNode(esTreeNode);
  4674. this.initialise();
  4675. this.context.magicString.addSourcemapLocation(this.start);
  4676. this.context.magicString.addSourcemapLocation(this.end);
  4677. }
  4678. addExportedVariables(_variables, _exportNamesByVariable) { }
  4679. /**
  4680. * Override this to bind assignments to variables and do any initialisations that
  4681. * require the scopes to be populated with variables.
  4682. */
  4683. bind() {
  4684. for (const key of this.keys) {
  4685. const value = this[key];
  4686. if (value === null)
  4687. continue;
  4688. if (Array.isArray(value)) {
  4689. for (const child of value) {
  4690. child === null || child === void 0 ? void 0 : child.bind();
  4691. }
  4692. }
  4693. else {
  4694. value.bind();
  4695. }
  4696. }
  4697. }
  4698. /**
  4699. * Override if this node should receive a different scope than the parent scope.
  4700. */
  4701. createScope(parentScope) {
  4702. this.scope = parentScope;
  4703. }
  4704. hasEffects(context) {
  4705. if (!this.deoptimized)
  4706. this.applyDeoptimizations();
  4707. for (const key of this.keys) {
  4708. const value = this[key];
  4709. if (value === null)
  4710. continue;
  4711. if (Array.isArray(value)) {
  4712. for (const child of value) {
  4713. if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
  4714. return true;
  4715. }
  4716. }
  4717. else if (value.hasEffects(context))
  4718. return true;
  4719. }
  4720. return false;
  4721. }
  4722. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4723. return (this.hasEffects(context) ||
  4724. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4725. }
  4726. include(context, includeChildrenRecursively, _options) {
  4727. if (!this.deoptimized)
  4728. this.applyDeoptimizations();
  4729. this.included = true;
  4730. for (const key of this.keys) {
  4731. const value = this[key];
  4732. if (value === null)
  4733. continue;
  4734. if (Array.isArray(value)) {
  4735. for (const child of value) {
  4736. child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
  4737. }
  4738. }
  4739. else {
  4740. value.include(context, includeChildrenRecursively);
  4741. }
  4742. }
  4743. }
  4744. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4745. this.include(context, includeChildrenRecursively);
  4746. }
  4747. /**
  4748. * Override to perform special initialisation steps after the scope is initialised
  4749. */
  4750. initialise() { }
  4751. insertSemicolon(code) {
  4752. if (code.original[this.end - 1] !== ';') {
  4753. code.appendLeft(this.end, ';');
  4754. }
  4755. }
  4756. parseNode(esTreeNode) {
  4757. for (const [key, value] of Object.entries(esTreeNode)) {
  4758. // That way, we can override this function to add custom initialisation and then call super.parseNode
  4759. if (this.hasOwnProperty(key))
  4760. continue;
  4761. if (key.charCodeAt(0) === 95 /* _ */) {
  4762. if (key === ANNOTATION_KEY) {
  4763. this.annotations = value;
  4764. }
  4765. else if (key === INVALID_COMMENT_KEY) {
  4766. for (const { start, end } of value)
  4767. this.context.magicString.remove(start, end);
  4768. }
  4769. }
  4770. else if (typeof value !== 'object' || value === null) {
  4771. this[key] = value;
  4772. }
  4773. else if (Array.isArray(value)) {
  4774. this[key] = [];
  4775. for (const child of value) {
  4776. this[key].push(child === null
  4777. ? null
  4778. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
  4779. }
  4780. }
  4781. else {
  4782. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
  4783. }
  4784. }
  4785. }
  4786. render(code, options) {
  4787. for (const key of this.keys) {
  4788. const value = this[key];
  4789. if (value === null)
  4790. continue;
  4791. if (Array.isArray(value)) {
  4792. for (const child of value) {
  4793. child === null || child === void 0 ? void 0 : child.render(code, options);
  4794. }
  4795. }
  4796. else {
  4797. value.render(code, options);
  4798. }
  4799. }
  4800. }
  4801. setAssignedValue(value) {
  4802. this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
  4803. }
  4804. shouldBeIncluded(context) {
  4805. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4806. }
  4807. /**
  4808. * Just deoptimize everything by default so that when e.g. we do not track
  4809. * something properly, it is deoptimized.
  4810. * @protected
  4811. */
  4812. applyDeoptimizations() {
  4813. this.deoptimized = true;
  4814. for (const key of this.keys) {
  4815. const value = this[key];
  4816. if (value === null)
  4817. continue;
  4818. if (Array.isArray(value)) {
  4819. for (const child of value) {
  4820. child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
  4821. }
  4822. }
  4823. else {
  4824. value.deoptimizePath(UNKNOWN_PATH);
  4825. }
  4826. }
  4827. this.context.requestTreeshakingPass();
  4828. }
  4829. }
  4830. class SpreadElement extends NodeBase {
  4831. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4832. if (path.length > 0) {
  4833. this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4834. }
  4835. }
  4836. hasEffects(context) {
  4837. if (!this.deoptimized)
  4838. this.applyDeoptimizations();
  4839. const { propertyReadSideEffects } = this.context.options
  4840. .treeshake;
  4841. return (this.argument.hasEffects(context) ||
  4842. (propertyReadSideEffects &&
  4843. (propertyReadSideEffects === 'always' ||
  4844. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4845. }
  4846. applyDeoptimizations() {
  4847. this.deoptimized = true;
  4848. // Only properties of properties of the argument could become subject to reassignment
  4849. // This will also reassign the return values of iterators
  4850. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4851. this.context.requestTreeshakingPass();
  4852. }
  4853. }
  4854. class Method extends ExpressionEntity {
  4855. constructor(description) {
  4856. super();
  4857. this.description = description;
  4858. }
  4859. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  4860. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4861. thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4862. }
  4863. }
  4864. getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
  4865. if (path.length > 0) {
  4866. return UNKNOWN_EXPRESSION;
  4867. }
  4868. return (this.description.returnsPrimitive ||
  4869. (this.description.returns === 'self'
  4870. ? thisArg || UNKNOWN_EXPRESSION
  4871. : this.description.returns()));
  4872. }
  4873. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4874. var _a, _b;
  4875. const { type } = interaction;
  4876. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4877. return true;
  4878. }
  4879. if (type === INTERACTION_CALLED) {
  4880. if (this.description.mutatesSelfAsArray === true &&
  4881. ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
  4882. return true;
  4883. }
  4884. if (this.description.callsArgs) {
  4885. for (const argIndex of this.description.callsArgs) {
  4886. if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4887. return true;
  4888. }
  4889. }
  4890. }
  4891. }
  4892. return false;
  4893. }
  4894. }
  4895. const METHOD_RETURNS_BOOLEAN = [
  4896. new Method({
  4897. callsArgs: null,
  4898. mutatesSelfAsArray: false,
  4899. returns: null,
  4900. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4901. })
  4902. ];
  4903. const METHOD_RETURNS_STRING = [
  4904. new Method({
  4905. callsArgs: null,
  4906. mutatesSelfAsArray: false,
  4907. returns: null,
  4908. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4909. })
  4910. ];
  4911. const METHOD_RETURNS_NUMBER = [
  4912. new Method({
  4913. callsArgs: null,
  4914. mutatesSelfAsArray: false,
  4915. returns: null,
  4916. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4917. })
  4918. ];
  4919. const METHOD_RETURNS_UNKNOWN = [
  4920. new Method({
  4921. callsArgs: null,
  4922. mutatesSelfAsArray: false,
  4923. returns: null,
  4924. returnsPrimitive: UNKNOWN_EXPRESSION
  4925. })
  4926. ];
  4927. const INTEGER_REG_EXP = /^\d+$/;
  4928. class ObjectEntity extends ExpressionEntity {
  4929. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4930. // and we assume there are no setters or getters
  4931. constructor(properties, prototypeExpression, immutable = false) {
  4932. super();
  4933. this.prototypeExpression = prototypeExpression;
  4934. this.immutable = immutable;
  4935. this.allProperties = [];
  4936. this.deoptimizedPaths = Object.create(null);
  4937. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4938. this.gettersByKey = Object.create(null);
  4939. this.hasLostTrack = false;
  4940. this.hasUnknownDeoptimizedInteger = false;
  4941. this.hasUnknownDeoptimizedProperty = false;
  4942. this.propertiesAndGettersByKey = Object.create(null);
  4943. this.propertiesAndSettersByKey = Object.create(null);
  4944. this.settersByKey = Object.create(null);
  4945. this.thisParametersToBeDeoptimized = new Set();
  4946. this.unknownIntegerProps = [];
  4947. this.unmatchableGetters = [];
  4948. this.unmatchablePropertiesAndGetters = [];
  4949. this.unmatchableSetters = [];
  4950. if (Array.isArray(properties)) {
  4951. this.buildPropertyMaps(properties);
  4952. }
  4953. else {
  4954. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4955. for (const propertiesForKey of Object.values(properties)) {
  4956. this.allProperties.push(...propertiesForKey);
  4957. }
  4958. }
  4959. }
  4960. deoptimizeAllProperties(noAccessors) {
  4961. var _a;
  4962. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4963. if (noAccessors) {
  4964. this.hasUnknownDeoptimizedProperty = true;
  4965. }
  4966. else {
  4967. this.hasLostTrack = true;
  4968. }
  4969. if (isDeoptimized) {
  4970. return;
  4971. }
  4972. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4973. for (const property of properties) {
  4974. property.deoptimizePath(UNKNOWN_PATH);
  4975. }
  4976. }
  4977. // While the prototype itself cannot be mutated, each property can
  4978. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4979. this.deoptimizeCachedEntities();
  4980. }
  4981. deoptimizeIntegerProperties() {
  4982. if (this.hasLostTrack ||
  4983. this.hasUnknownDeoptimizedProperty ||
  4984. this.hasUnknownDeoptimizedInteger) {
  4985. return;
  4986. }
  4987. this.hasUnknownDeoptimizedInteger = true;
  4988. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4989. if (INTEGER_REG_EXP.test(key)) {
  4990. for (const property of propertiesAndGetters) {
  4991. property.deoptimizePath(UNKNOWN_PATH);
  4992. }
  4993. }
  4994. }
  4995. this.deoptimizeCachedIntegerEntities();
  4996. }
  4997. // Assumption: If only a specific path is deoptimized, no accessors are created
  4998. deoptimizePath(path) {
  4999. var _a;
  5000. if (this.hasLostTrack || this.immutable) {
  5001. return;
  5002. }
  5003. const key = path[0];
  5004. if (path.length === 1) {
  5005. if (typeof key !== 'string') {
  5006. if (key === UnknownInteger) {
  5007. return this.deoptimizeIntegerProperties();
  5008. }
  5009. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  5010. }
  5011. if (!this.deoptimizedPaths[key]) {
  5012. this.deoptimizedPaths[key] = true;
  5013. // we only deoptimizeCache exact matches as in all other cases,
  5014. // we do not return a literal value or return expression
  5015. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  5016. if (expressionsToBeDeoptimized) {
  5017. for (const expression of expressionsToBeDeoptimized) {
  5018. expression.deoptimizeCache();
  5019. }
  5020. }
  5021. }
  5022. }
  5023. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  5024. for (const property of typeof key === 'string'
  5025. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  5026. : this.allProperties) {
  5027. property.deoptimizePath(subPath);
  5028. }
  5029. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  5030. }
  5031. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5032. var _a;
  5033. const [key, ...subPath] = path;
  5034. if (this.hasLostTrack ||
  5035. // single paths that are deoptimized will not become getters or setters
  5036. ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
  5037. (this.hasUnknownDeoptimizedProperty ||
  5038. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  5039. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5040. return;
  5041. }
  5042. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
  5043. ? [
  5044. this.propertiesAndGettersByKey,
  5045. this.propertiesAndGettersByKey,
  5046. this.unmatchablePropertiesAndGetters
  5047. ]
  5048. : interaction.type === INTERACTION_ACCESSED
  5049. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5050. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5051. if (typeof key === 'string') {
  5052. if (propertiesForExactMatchByKey[key]) {
  5053. const properties = relevantPropertiesByKey[key];
  5054. if (properties) {
  5055. for (const property of properties) {
  5056. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5057. }
  5058. }
  5059. if (!this.immutable) {
  5060. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  5061. }
  5062. return;
  5063. }
  5064. for (const property of relevantUnmatchableProperties) {
  5065. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5066. }
  5067. if (INTEGER_REG_EXP.test(key)) {
  5068. for (const property of this.unknownIntegerProps) {
  5069. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5070. }
  5071. }
  5072. }
  5073. else {
  5074. for (const properties of Object.values(relevantPropertiesByKey).concat([
  5075. relevantUnmatchableProperties
  5076. ])) {
  5077. for (const property of properties) {
  5078. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5079. }
  5080. }
  5081. for (const property of this.unknownIntegerProps) {
  5082. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5083. }
  5084. }
  5085. if (!this.immutable) {
  5086. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  5087. }
  5088. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5089. }
  5090. getLiteralValueAtPath(path, recursionTracker, origin) {
  5091. if (path.length === 0) {
  5092. return UnknownTruthyValue;
  5093. }
  5094. const key = path[0];
  5095. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5096. if (expressionAtPath) {
  5097. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  5098. }
  5099. if (this.prototypeExpression) {
  5100. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  5101. }
  5102. if (path.length === 1) {
  5103. return undefined;
  5104. }
  5105. return UnknownValue;
  5106. }
  5107. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5108. if (path.length === 0) {
  5109. return UNKNOWN_EXPRESSION;
  5110. }
  5111. const [key, ...subPath] = path;
  5112. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5113. if (expressionAtPath) {
  5114. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  5115. }
  5116. if (this.prototypeExpression) {
  5117. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5118. }
  5119. return UNKNOWN_EXPRESSION;
  5120. }
  5121. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5122. const [key, ...subPath] = path;
  5123. if (subPath.length || interaction.type === INTERACTION_CALLED) {
  5124. const expressionAtPath = this.getMemberExpression(key);
  5125. if (expressionAtPath) {
  5126. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5127. }
  5128. if (this.prototypeExpression) {
  5129. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5130. }
  5131. return true;
  5132. }
  5133. if (key === UnknownNonAccessorKey)
  5134. return false;
  5135. if (this.hasLostTrack)
  5136. return true;
  5137. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5138. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5139. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5140. if (typeof key === 'string') {
  5141. if (propertiesAndAccessorsByKey[key]) {
  5142. const accessors = accessorsByKey[key];
  5143. if (accessors) {
  5144. for (const accessor of accessors) {
  5145. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5146. return true;
  5147. }
  5148. }
  5149. return false;
  5150. }
  5151. for (const accessor of unmatchableAccessors) {
  5152. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5153. return true;
  5154. }
  5155. }
  5156. }
  5157. else {
  5158. for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
  5159. for (const accessor of accessors) {
  5160. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5161. return true;
  5162. }
  5163. }
  5164. }
  5165. if (this.prototypeExpression) {
  5166. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5167. }
  5168. return false;
  5169. }
  5170. buildPropertyMaps(properties) {
  5171. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5172. const unmatchablePropertiesAndSetters = [];
  5173. for (let index = properties.length - 1; index >= 0; index--) {
  5174. const { key, kind, property } = properties[index];
  5175. allProperties.push(property);
  5176. if (typeof key !== 'string') {
  5177. if (key === UnknownInteger) {
  5178. unknownIntegerProps.push(property);
  5179. continue;
  5180. }
  5181. if (kind === 'set')
  5182. unmatchableSetters.push(property);
  5183. if (kind === 'get')
  5184. unmatchableGetters.push(property);
  5185. if (kind !== 'get')
  5186. unmatchablePropertiesAndSetters.push(property);
  5187. if (kind !== 'set')
  5188. unmatchablePropertiesAndGetters.push(property);
  5189. }
  5190. else {
  5191. if (kind === 'set') {
  5192. if (!propertiesAndSettersByKey[key]) {
  5193. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5194. settersByKey[key] = [property, ...unmatchableSetters];
  5195. }
  5196. }
  5197. else if (kind === 'get') {
  5198. if (!propertiesAndGettersByKey[key]) {
  5199. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5200. gettersByKey[key] = [property, ...unmatchableGetters];
  5201. }
  5202. }
  5203. else {
  5204. if (!propertiesAndSettersByKey[key]) {
  5205. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5206. }
  5207. if (!propertiesAndGettersByKey[key]) {
  5208. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5209. }
  5210. }
  5211. }
  5212. }
  5213. }
  5214. deoptimizeCachedEntities() {
  5215. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  5216. for (const expression of expressionsToBeDeoptimized) {
  5217. expression.deoptimizeCache();
  5218. }
  5219. }
  5220. for (const expression of this.thisParametersToBeDeoptimized) {
  5221. expression.deoptimizePath(UNKNOWN_PATH);
  5222. }
  5223. }
  5224. deoptimizeCachedIntegerEntities() {
  5225. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  5226. if (INTEGER_REG_EXP.test(key)) {
  5227. for (const expression of expressionsToBeDeoptimized) {
  5228. expression.deoptimizeCache();
  5229. }
  5230. }
  5231. }
  5232. for (const expression of this.thisParametersToBeDeoptimized) {
  5233. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5234. }
  5235. }
  5236. getMemberExpression(key) {
  5237. if (this.hasLostTrack ||
  5238. this.hasUnknownDeoptimizedProperty ||
  5239. typeof key !== 'string' ||
  5240. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  5241. this.deoptimizedPaths[key]) {
  5242. return UNKNOWN_EXPRESSION;
  5243. }
  5244. const properties = this.propertiesAndGettersByKey[key];
  5245. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  5246. return properties[0];
  5247. }
  5248. if (properties ||
  5249. this.unmatchablePropertiesAndGetters.length > 0 ||
  5250. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  5251. return UNKNOWN_EXPRESSION;
  5252. }
  5253. return null;
  5254. }
  5255. getMemberExpressionAndTrackDeopt(key, origin) {
  5256. if (typeof key !== 'string') {
  5257. return UNKNOWN_EXPRESSION;
  5258. }
  5259. const expression = this.getMemberExpression(key);
  5260. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  5261. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  5262. this.expressionsToBeDeoptimizedByKey[key] || []);
  5263. expressionsToBeDeoptimized.push(origin);
  5264. }
  5265. return expression;
  5266. }
  5267. }
  5268. const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
  5269. // This makes sure unknown properties are not handled as "undefined" but as
  5270. // "unknown" but without access side effects. An exception is done for numeric
  5271. // properties as we do not expect new builtin properties to be numbers, this
  5272. // will improve tree-shaking for out-of-bounds array properties
  5273. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  5274. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  5275. if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  5276. thisArg.deoptimizePath(UNKNOWN_PATH);
  5277. }
  5278. }
  5279. getLiteralValueAtPath(path) {
  5280. // We ignore number properties as we do not expect new properties to be
  5281. // numbers and also want to keep handling out-of-bound array elements as
  5282. // "undefined"
  5283. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  5284. }
  5285. hasEffectsOnInteractionAtPath(path, { type }) {
  5286. return path.length > 1 || type === INTERACTION_CALLED;
  5287. }
  5288. })();
  5289. const OBJECT_PROTOTYPE = new ObjectEntity({
  5290. __proto__: null,
  5291. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  5292. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  5293. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  5294. toLocaleString: METHOD_RETURNS_STRING,
  5295. toString: METHOD_RETURNS_STRING,
  5296. valueOf: METHOD_RETURNS_UNKNOWN
  5297. }, OBJECT_PROTOTYPE_FALLBACK, true);
  5298. const NEW_ARRAY_PROPERTIES = [
  5299. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5300. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5301. ];
  5302. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5303. new Method({
  5304. callsArgs: [0],
  5305. mutatesSelfAsArray: 'deopt-only',
  5306. returns: null,
  5307. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5308. })
  5309. ];
  5310. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5311. new Method({
  5312. callsArgs: [0],
  5313. mutatesSelfAsArray: 'deopt-only',
  5314. returns: null,
  5315. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5316. })
  5317. ];
  5318. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5319. new Method({
  5320. callsArgs: null,
  5321. mutatesSelfAsArray: true,
  5322. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5323. returnsPrimitive: null
  5324. })
  5325. ];
  5326. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5327. new Method({
  5328. callsArgs: null,
  5329. mutatesSelfAsArray: 'deopt-only',
  5330. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5331. returnsPrimitive: null
  5332. })
  5333. ];
  5334. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5335. new Method({
  5336. callsArgs: [0],
  5337. mutatesSelfAsArray: 'deopt-only',
  5338. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5339. returnsPrimitive: null
  5340. })
  5341. ];
  5342. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5343. new Method({
  5344. callsArgs: null,
  5345. mutatesSelfAsArray: true,
  5346. returns: null,
  5347. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5348. })
  5349. ];
  5350. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5351. new Method({
  5352. callsArgs: null,
  5353. mutatesSelfAsArray: true,
  5354. returns: null,
  5355. returnsPrimitive: UNKNOWN_EXPRESSION
  5356. })
  5357. ];
  5358. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5359. new Method({
  5360. callsArgs: null,
  5361. mutatesSelfAsArray: 'deopt-only',
  5362. returns: null,
  5363. returnsPrimitive: UNKNOWN_EXPRESSION
  5364. })
  5365. ];
  5366. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5367. new Method({
  5368. callsArgs: [0],
  5369. mutatesSelfAsArray: 'deopt-only',
  5370. returns: null,
  5371. returnsPrimitive: UNKNOWN_EXPRESSION
  5372. })
  5373. ];
  5374. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5375. new Method({
  5376. callsArgs: null,
  5377. mutatesSelfAsArray: true,
  5378. returns: 'self',
  5379. returnsPrimitive: null
  5380. })
  5381. ];
  5382. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5383. new Method({
  5384. callsArgs: [0],
  5385. mutatesSelfAsArray: true,
  5386. returns: 'self',
  5387. returnsPrimitive: null
  5388. })
  5389. ];
  5390. const ARRAY_PROTOTYPE = new ObjectEntity({
  5391. __proto__: null,
  5392. // We assume that accessors have effects as we do not track the accessed value afterwards
  5393. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5394. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5395. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5396. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5397. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5398. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5399. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5400. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5401. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5402. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5403. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5404. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5405. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5406. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5407. group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5408. groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5409. includes: METHOD_RETURNS_BOOLEAN,
  5410. indexOf: METHOD_RETURNS_NUMBER,
  5411. join: METHOD_RETURNS_STRING,
  5412. keys: METHOD_RETURNS_UNKNOWN,
  5413. lastIndexOf: METHOD_RETURNS_NUMBER,
  5414. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5415. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5416. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5417. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5418. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5419. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5420. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5421. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5422. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5423. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5424. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5425. toLocaleString: METHOD_RETURNS_STRING,
  5426. toString: METHOD_RETURNS_STRING,
  5427. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5428. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5429. }, OBJECT_PROTOTYPE, true);
  5430. class ArrayExpression extends NodeBase {
  5431. constructor() {
  5432. super(...arguments);
  5433. this.objectEntity = null;
  5434. }
  5435. deoptimizePath(path) {
  5436. this.getObjectEntity().deoptimizePath(path);
  5437. }
  5438. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5439. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5440. }
  5441. getLiteralValueAtPath(path, recursionTracker, origin) {
  5442. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5443. }
  5444. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5445. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5446. }
  5447. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5448. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5449. }
  5450. applyDeoptimizations() {
  5451. this.deoptimized = true;
  5452. let hasSpread = false;
  5453. for (let index = 0; index < this.elements.length; index++) {
  5454. const element = this.elements[index];
  5455. if (element) {
  5456. if (hasSpread || element instanceof SpreadElement) {
  5457. hasSpread = true;
  5458. element.deoptimizePath(UNKNOWN_PATH);
  5459. }
  5460. }
  5461. }
  5462. this.context.requestTreeshakingPass();
  5463. }
  5464. getObjectEntity() {
  5465. if (this.objectEntity !== null) {
  5466. return this.objectEntity;
  5467. }
  5468. const properties = [
  5469. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5470. ];
  5471. let hasSpread = false;
  5472. for (let index = 0; index < this.elements.length; index++) {
  5473. const element = this.elements[index];
  5474. if (hasSpread || element instanceof SpreadElement) {
  5475. if (element) {
  5476. hasSpread = true;
  5477. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5478. }
  5479. }
  5480. else if (!element) {
  5481. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5482. }
  5483. else {
  5484. properties.push({ key: String(index), kind: 'init', property: element });
  5485. }
  5486. }
  5487. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5488. }
  5489. }
  5490. class ArrayPattern extends NodeBase {
  5491. addExportedVariables(variables, exportNamesByVariable) {
  5492. for (const element of this.elements) {
  5493. element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
  5494. }
  5495. }
  5496. declare(kind) {
  5497. const variables = [];
  5498. for (const element of this.elements) {
  5499. if (element !== null) {
  5500. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5501. }
  5502. }
  5503. return variables;
  5504. }
  5505. // Patterns can only be deoptimized at the empty path at the moment
  5506. deoptimizePath() {
  5507. for (const element of this.elements) {
  5508. element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
  5509. }
  5510. }
  5511. // Patterns are only checked at the emtpy path at the moment
  5512. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  5513. for (const element of this.elements) {
  5514. if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  5515. return true;
  5516. }
  5517. return false;
  5518. }
  5519. markDeclarationReached() {
  5520. for (const element of this.elements) {
  5521. element === null || element === void 0 ? void 0 : element.markDeclarationReached();
  5522. }
  5523. }
  5524. }
  5525. class LocalVariable extends Variable {
  5526. constructor(name, declarator, init, context) {
  5527. super(name);
  5528. this.calledFromTryStatement = false;
  5529. this.additionalInitializers = null;
  5530. this.expressionsToBeDeoptimized = [];
  5531. this.declarations = declarator ? [declarator] : [];
  5532. this.init = init;
  5533. this.deoptimizationTracker = context.deoptimizationTracker;
  5534. this.module = context.module;
  5535. }
  5536. addDeclaration(identifier, init) {
  5537. this.declarations.push(identifier);
  5538. const additionalInitializers = this.markInitializersForDeoptimization();
  5539. if (init !== null) {
  5540. additionalInitializers.push(init);
  5541. }
  5542. }
  5543. consolidateInitializers() {
  5544. if (this.additionalInitializers !== null) {
  5545. for (const initializer of this.additionalInitializers) {
  5546. initializer.deoptimizePath(UNKNOWN_PATH);
  5547. }
  5548. this.additionalInitializers = null;
  5549. }
  5550. }
  5551. deoptimizePath(path) {
  5552. var _a, _b;
  5553. if (this.isReassigned ||
  5554. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5555. return;
  5556. }
  5557. if (path.length === 0) {
  5558. if (!this.isReassigned) {
  5559. this.isReassigned = true;
  5560. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  5561. this.expressionsToBeDeoptimized = [];
  5562. for (const expression of expressionsToBeDeoptimized) {
  5563. expression.deoptimizeCache();
  5564. }
  5565. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  5566. }
  5567. }
  5568. else {
  5569. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  5570. }
  5571. }
  5572. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5573. if (this.isReassigned || !this.init) {
  5574. return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5575. }
  5576. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  5577. }
  5578. getLiteralValueAtPath(path, recursionTracker, origin) {
  5579. if (this.isReassigned || !this.init) {
  5580. return UnknownValue;
  5581. }
  5582. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5583. this.expressionsToBeDeoptimized.push(origin);
  5584. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5585. }, UnknownValue);
  5586. }
  5587. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5588. if (this.isReassigned || !this.init) {
  5589. return UNKNOWN_EXPRESSION;
  5590. }
  5591. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5592. this.expressionsToBeDeoptimized.push(origin);
  5593. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5594. }, UNKNOWN_EXPRESSION);
  5595. }
  5596. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5597. switch (interaction.type) {
  5598. case INTERACTION_ACCESSED:
  5599. if (this.isReassigned)
  5600. return true;
  5601. return (this.init &&
  5602. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5603. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5604. case INTERACTION_ASSIGNED:
  5605. if (this.included)
  5606. return true;
  5607. if (path.length === 0)
  5608. return false;
  5609. if (this.isReassigned)
  5610. return true;
  5611. return (this.init &&
  5612. !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5613. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5614. case INTERACTION_CALLED:
  5615. if (this.isReassigned)
  5616. return true;
  5617. return (this.init &&
  5618. !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5619. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5620. }
  5621. }
  5622. include() {
  5623. if (!this.included) {
  5624. this.included = true;
  5625. for (const declaration of this.declarations) {
  5626. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5627. if (!declaration.included)
  5628. declaration.include(createInclusionContext(), false);
  5629. let node = declaration.parent;
  5630. while (!node.included) {
  5631. // We do not want to properly include parents in case they are part of a dead branch
  5632. // in which case .include() might pull in more dead code
  5633. node.included = true;
  5634. if (node.type === Program$1)
  5635. break;
  5636. node = node.parent;
  5637. }
  5638. }
  5639. }
  5640. }
  5641. includeCallArguments(context, args) {
  5642. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  5643. for (const arg of args) {
  5644. arg.include(context, false);
  5645. }
  5646. }
  5647. else if (this.init) {
  5648. context.includedCallArguments.add(this.init);
  5649. this.init.includeCallArguments(context, args);
  5650. context.includedCallArguments.delete(this.init);
  5651. }
  5652. }
  5653. markCalledFromTryStatement() {
  5654. this.calledFromTryStatement = true;
  5655. }
  5656. markInitializersForDeoptimization() {
  5657. if (this.additionalInitializers === null) {
  5658. this.additionalInitializers = this.init === null ? [] : [this.init];
  5659. this.init = UNKNOWN_EXPRESSION;
  5660. this.isReassigned = true;
  5661. }
  5662. return this.additionalInitializers;
  5663. }
  5664. }
  5665. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5666. const base = 64;
  5667. function toBase64(num) {
  5668. let outStr = '';
  5669. do {
  5670. const curDigit = num % base;
  5671. num = Math.floor(num / base);
  5672. outStr = chars[curDigit] + outStr;
  5673. } while (num !== 0);
  5674. return outStr;
  5675. }
  5676. function getSafeName(baseName, usedNames) {
  5677. let safeName = baseName;
  5678. let count = 1;
  5679. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
  5680. safeName = `${baseName}$${toBase64(count++)}`;
  5681. }
  5682. usedNames.add(safeName);
  5683. return safeName;
  5684. }
  5685. class Scope$1 {
  5686. constructor() {
  5687. this.children = [];
  5688. this.variables = new Map();
  5689. }
  5690. addDeclaration(identifier, context, init, _isHoisted) {
  5691. const name = identifier.name;
  5692. let variable = this.variables.get(name);
  5693. if (variable) {
  5694. variable.addDeclaration(identifier, init);
  5695. }
  5696. else {
  5697. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  5698. this.variables.set(name, variable);
  5699. }
  5700. return variable;
  5701. }
  5702. contains(name) {
  5703. return this.variables.has(name);
  5704. }
  5705. findVariable(_name) {
  5706. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5707. }
  5708. }
  5709. class ChildScope extends Scope$1 {
  5710. constructor(parent) {
  5711. super();
  5712. this.accessedOutsideVariables = new Map();
  5713. this.parent = parent;
  5714. parent.children.push(this);
  5715. }
  5716. addAccessedDynamicImport(importExpression) {
  5717. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5718. if (this.parent instanceof ChildScope) {
  5719. this.parent.addAccessedDynamicImport(importExpression);
  5720. }
  5721. }
  5722. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5723. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5724. for (const name of globals) {
  5725. accessedGlobals.add(name);
  5726. }
  5727. accessedGlobalsByScope.set(this, accessedGlobals);
  5728. if (this.parent instanceof ChildScope) {
  5729. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5730. }
  5731. }
  5732. addNamespaceMemberAccess(name, variable) {
  5733. this.accessedOutsideVariables.set(name, variable);
  5734. this.parent.addNamespaceMemberAccess(name, variable);
  5735. }
  5736. addReturnExpression(expression) {
  5737. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  5738. }
  5739. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5740. for (const variable of this.accessedOutsideVariables.values()) {
  5741. if (variable.included) {
  5742. usedNames.add(variable.getBaseVariableName());
  5743. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5744. usedNames.add('exports');
  5745. }
  5746. }
  5747. }
  5748. const accessedGlobals = accessedGlobalsByScope.get(this);
  5749. if (accessedGlobals) {
  5750. for (const name of accessedGlobals) {
  5751. usedNames.add(name);
  5752. }
  5753. }
  5754. }
  5755. contains(name) {
  5756. return this.variables.has(name) || this.parent.contains(name);
  5757. }
  5758. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5759. const usedNames = new Set();
  5760. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5761. if (this.accessedDynamicImports) {
  5762. for (const importExpression of this.accessedDynamicImports) {
  5763. if (importExpression.inlineNamespace) {
  5764. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5765. }
  5766. }
  5767. }
  5768. for (const [name, variable] of this.variables) {
  5769. if (variable.included || variable.alwaysRendered) {
  5770. variable.setRenderNames(null, getSafeName(name, usedNames));
  5771. }
  5772. }
  5773. for (const scope of this.children) {
  5774. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5775. }
  5776. }
  5777. findLexicalBoundary() {
  5778. return this.parent.findLexicalBoundary();
  5779. }
  5780. findVariable(name) {
  5781. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5782. if (knownVariable) {
  5783. return knownVariable;
  5784. }
  5785. const variable = this.parent.findVariable(name);
  5786. this.accessedOutsideVariables.set(name, variable);
  5787. return variable;
  5788. }
  5789. }
  5790. class ParameterScope extends ChildScope {
  5791. constructor(parent, context) {
  5792. super(parent);
  5793. this.parameters = [];
  5794. this.hasRest = false;
  5795. this.context = context;
  5796. this.hoistedBodyVarScope = new ChildScope(this);
  5797. }
  5798. /**
  5799. * Adds a parameter to this scope. Parameters must be added in the correct
  5800. * order, e.g. from left to right.
  5801. */
  5802. addParameterDeclaration(identifier) {
  5803. const name = identifier.name;
  5804. let variable = this.hoistedBodyVarScope.variables.get(name);
  5805. if (variable) {
  5806. variable.addDeclaration(identifier, null);
  5807. }
  5808. else {
  5809. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  5810. }
  5811. this.variables.set(name, variable);
  5812. return variable;
  5813. }
  5814. addParameterVariables(parameters, hasRest) {
  5815. this.parameters = parameters;
  5816. for (const parameterList of parameters) {
  5817. for (const parameter of parameterList) {
  5818. parameter.alwaysRendered = true;
  5819. }
  5820. }
  5821. this.hasRest = hasRest;
  5822. }
  5823. includeCallArguments(context, args) {
  5824. let calledFromTryStatement = false;
  5825. let argIncluded = false;
  5826. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  5827. for (const checkedArg of args) {
  5828. if (checkedArg instanceof SpreadElement) {
  5829. for (const arg of args) {
  5830. arg.include(context, false);
  5831. }
  5832. break;
  5833. }
  5834. }
  5835. for (let index = args.length - 1; index >= 0; index--) {
  5836. const paramVars = this.parameters[index] || restParam;
  5837. const arg = args[index];
  5838. if (paramVars) {
  5839. calledFromTryStatement = false;
  5840. if (paramVars.length === 0) {
  5841. // handle empty destructuring
  5842. argIncluded = true;
  5843. }
  5844. else {
  5845. for (const variable of paramVars) {
  5846. if (variable.included) {
  5847. argIncluded = true;
  5848. }
  5849. if (variable.calledFromTryStatement) {
  5850. calledFromTryStatement = true;
  5851. }
  5852. }
  5853. }
  5854. }
  5855. if (!argIncluded && arg.shouldBeIncluded(context)) {
  5856. argIncluded = true;
  5857. }
  5858. if (argIncluded) {
  5859. arg.include(context, calledFromTryStatement);
  5860. }
  5861. }
  5862. }
  5863. }
  5864. class ReturnValueScope extends ParameterScope {
  5865. constructor() {
  5866. super(...arguments);
  5867. this.returnExpression = null;
  5868. this.returnExpressions = [];
  5869. }
  5870. addReturnExpression(expression) {
  5871. this.returnExpressions.push(expression);
  5872. }
  5873. getReturnExpression() {
  5874. if (this.returnExpression === null)
  5875. this.updateReturnExpression();
  5876. return this.returnExpression;
  5877. }
  5878. updateReturnExpression() {
  5879. if (this.returnExpressions.length === 1) {
  5880. this.returnExpression = this.returnExpressions[0];
  5881. }
  5882. else {
  5883. this.returnExpression = UNKNOWN_EXPRESSION;
  5884. for (const expression of this.returnExpressions) {
  5885. expression.deoptimizePath(UNKNOWN_PATH);
  5886. }
  5887. }
  5888. }
  5889. }
  5890. //@ts-check
  5891. /** @typedef { import('estree').Node} Node */
  5892. /** @typedef {Node | {
  5893. * type: 'PropertyDefinition';
  5894. * computed: boolean;
  5895. * value: Node
  5896. * }} NodeWithPropertyDefinition */
  5897. /**
  5898. *
  5899. * @param {NodeWithPropertyDefinition} node
  5900. * @param {NodeWithPropertyDefinition} parent
  5901. * @returns boolean
  5902. */
  5903. function is_reference (node, parent) {
  5904. if (node.type === 'MemberExpression') {
  5905. return !node.computed && is_reference(node.object, node);
  5906. }
  5907. if (node.type === 'Identifier') {
  5908. if (!parent) return true;
  5909. switch (parent.type) {
  5910. // disregard `bar` in `foo.bar`
  5911. case 'MemberExpression': return parent.computed || node === parent.object;
  5912. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5913. case 'MethodDefinition': return parent.computed;
  5914. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5915. case 'PropertyDefinition': return parent.computed || node === parent.value;
  5916. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5917. case 'Property': return parent.computed || node === parent.value;
  5918. // disregard the `bar` in `export { foo as bar }` or
  5919. // the foo in `import { foo as bar }`
  5920. case 'ExportSpecifier':
  5921. case 'ImportSpecifier': return node === parent.local;
  5922. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5923. case 'LabeledStatement':
  5924. case 'BreakStatement':
  5925. case 'ContinueStatement': return false;
  5926. default: return true;
  5927. }
  5928. }
  5929. return false;
  5930. }
  5931. /* eslint sort-keys: "off" */
  5932. const ValueProperties = Symbol('Value Properties');
  5933. const PURE = {
  5934. hasEffectsWhenCalled() {
  5935. return false;
  5936. }
  5937. };
  5938. const IMPURE = {
  5939. hasEffectsWhenCalled() {
  5940. return true;
  5941. }
  5942. };
  5943. // We use shortened variables to reduce file size here
  5944. /* OBJECT */
  5945. const O = {
  5946. __proto__: null,
  5947. [ValueProperties]: IMPURE
  5948. };
  5949. /* PURE FUNCTION */
  5950. const PF = {
  5951. __proto__: null,
  5952. [ValueProperties]: PURE
  5953. };
  5954. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5955. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5956. __proto__: null,
  5957. [ValueProperties]: {
  5958. hasEffectsWhenCalled({ args }, context) {
  5959. return (!args.length ||
  5960. args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5961. }
  5962. }
  5963. };
  5964. /* CONSTRUCTOR */
  5965. const C = {
  5966. __proto__: null,
  5967. [ValueProperties]: IMPURE,
  5968. prototype: O
  5969. };
  5970. /* PURE CONSTRUCTOR */
  5971. const PC = {
  5972. __proto__: null,
  5973. [ValueProperties]: PURE,
  5974. prototype: O
  5975. };
  5976. const ARRAY_TYPE = {
  5977. __proto__: null,
  5978. [ValueProperties]: PURE,
  5979. from: PF,
  5980. of: PF,
  5981. prototype: O
  5982. };
  5983. const INTL_MEMBER = {
  5984. __proto__: null,
  5985. [ValueProperties]: PURE,
  5986. supportedLocalesOf: PC
  5987. };
  5988. const knownGlobals = {
  5989. // Placeholders for global objects to avoid shape mutations
  5990. global: O,
  5991. globalThis: O,
  5992. self: O,
  5993. window: O,
  5994. // Common globals
  5995. __proto__: null,
  5996. [ValueProperties]: IMPURE,
  5997. Array: {
  5998. __proto__: null,
  5999. [ValueProperties]: IMPURE,
  6000. from: O,
  6001. isArray: PF,
  6002. of: PF,
  6003. prototype: O
  6004. },
  6005. ArrayBuffer: {
  6006. __proto__: null,
  6007. [ValueProperties]: PURE,
  6008. isView: PF,
  6009. prototype: O
  6010. },
  6011. Atomics: O,
  6012. BigInt: C,
  6013. BigInt64Array: C,
  6014. BigUint64Array: C,
  6015. Boolean: PC,
  6016. constructor: C,
  6017. DataView: PC,
  6018. Date: {
  6019. __proto__: null,
  6020. [ValueProperties]: PURE,
  6021. now: PF,
  6022. parse: PF,
  6023. prototype: O,
  6024. UTC: PF
  6025. },
  6026. decodeURI: PF,
  6027. decodeURIComponent: PF,
  6028. encodeURI: PF,
  6029. encodeURIComponent: PF,
  6030. Error: PC,
  6031. escape: PF,
  6032. eval: O,
  6033. EvalError: PC,
  6034. Float32Array: ARRAY_TYPE,
  6035. Float64Array: ARRAY_TYPE,
  6036. Function: C,
  6037. hasOwnProperty: O,
  6038. Infinity: O,
  6039. Int16Array: ARRAY_TYPE,
  6040. Int32Array: ARRAY_TYPE,
  6041. Int8Array: ARRAY_TYPE,
  6042. isFinite: PF,
  6043. isNaN: PF,
  6044. isPrototypeOf: O,
  6045. JSON: O,
  6046. Map: PC,
  6047. Math: {
  6048. __proto__: null,
  6049. [ValueProperties]: IMPURE,
  6050. abs: PF,
  6051. acos: PF,
  6052. acosh: PF,
  6053. asin: PF,
  6054. asinh: PF,
  6055. atan: PF,
  6056. atan2: PF,
  6057. atanh: PF,
  6058. cbrt: PF,
  6059. ceil: PF,
  6060. clz32: PF,
  6061. cos: PF,
  6062. cosh: PF,
  6063. exp: PF,
  6064. expm1: PF,
  6065. floor: PF,
  6066. fround: PF,
  6067. hypot: PF,
  6068. imul: PF,
  6069. log: PF,
  6070. log10: PF,
  6071. log1p: PF,
  6072. log2: PF,
  6073. max: PF,
  6074. min: PF,
  6075. pow: PF,
  6076. random: PF,
  6077. round: PF,
  6078. sign: PF,
  6079. sin: PF,
  6080. sinh: PF,
  6081. sqrt: PF,
  6082. tan: PF,
  6083. tanh: PF,
  6084. trunc: PF
  6085. },
  6086. NaN: O,
  6087. Number: {
  6088. __proto__: null,
  6089. [ValueProperties]: PURE,
  6090. isFinite: PF,
  6091. isInteger: PF,
  6092. isNaN: PF,
  6093. isSafeInteger: PF,
  6094. parseFloat: PF,
  6095. parseInt: PF,
  6096. prototype: O
  6097. },
  6098. Object: {
  6099. __proto__: null,
  6100. [ValueProperties]: PURE,
  6101. create: PF,
  6102. // Technically those can throw in certain situations, but we ignore this as
  6103. // code that relies on this will hopefully wrap this in a try-catch, which
  6104. // deoptimizes everything anyway
  6105. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  6106. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  6107. getOwnPropertyDescriptor: PF,
  6108. getOwnPropertyNames: PF,
  6109. getOwnPropertySymbols: PF,
  6110. getPrototypeOf: PF,
  6111. hasOwn: PF,
  6112. is: PF,
  6113. isExtensible: PF,
  6114. isFrozen: PF,
  6115. isSealed: PF,
  6116. keys: PF,
  6117. fromEntries: PF,
  6118. entries: PF,
  6119. prototype: O
  6120. },
  6121. parseFloat: PF,
  6122. parseInt: PF,
  6123. Promise: {
  6124. __proto__: null,
  6125. [ValueProperties]: IMPURE,
  6126. all: O,
  6127. prototype: O,
  6128. race: O,
  6129. reject: O,
  6130. resolve: O
  6131. },
  6132. propertyIsEnumerable: O,
  6133. Proxy: O,
  6134. RangeError: PC,
  6135. ReferenceError: PC,
  6136. Reflect: O,
  6137. RegExp: PC,
  6138. Set: PC,
  6139. SharedArrayBuffer: C,
  6140. String: {
  6141. __proto__: null,
  6142. [ValueProperties]: PURE,
  6143. fromCharCode: PF,
  6144. fromCodePoint: PF,
  6145. prototype: O,
  6146. raw: PF
  6147. },
  6148. Symbol: {
  6149. __proto__: null,
  6150. [ValueProperties]: PURE,
  6151. for: PF,
  6152. keyFor: PF,
  6153. prototype: O
  6154. },
  6155. SyntaxError: PC,
  6156. toLocaleString: O,
  6157. toString: O,
  6158. TypeError: PC,
  6159. Uint16Array: ARRAY_TYPE,
  6160. Uint32Array: ARRAY_TYPE,
  6161. Uint8Array: ARRAY_TYPE,
  6162. Uint8ClampedArray: ARRAY_TYPE,
  6163. // Technically, this is a global, but it needs special handling
  6164. // undefined: ?,
  6165. unescape: PF,
  6166. URIError: PC,
  6167. valueOf: O,
  6168. WeakMap: PC,
  6169. WeakSet: PC,
  6170. // Additional globals shared by Node and Browser that are not strictly part of the language
  6171. clearInterval: C,
  6172. clearTimeout: C,
  6173. console: O,
  6174. Intl: {
  6175. __proto__: null,
  6176. [ValueProperties]: IMPURE,
  6177. Collator: INTL_MEMBER,
  6178. DateTimeFormat: INTL_MEMBER,
  6179. ListFormat: INTL_MEMBER,
  6180. NumberFormat: INTL_MEMBER,
  6181. PluralRules: INTL_MEMBER,
  6182. RelativeTimeFormat: INTL_MEMBER
  6183. },
  6184. setInterval: C,
  6185. setTimeout: C,
  6186. TextDecoder: C,
  6187. TextEncoder: C,
  6188. URL: C,
  6189. URLSearchParams: C,
  6190. // Browser specific globals
  6191. AbortController: C,
  6192. AbortSignal: C,
  6193. addEventListener: O,
  6194. alert: O,
  6195. AnalyserNode: C,
  6196. Animation: C,
  6197. AnimationEvent: C,
  6198. applicationCache: O,
  6199. ApplicationCache: C,
  6200. ApplicationCacheErrorEvent: C,
  6201. atob: O,
  6202. Attr: C,
  6203. Audio: C,
  6204. AudioBuffer: C,
  6205. AudioBufferSourceNode: C,
  6206. AudioContext: C,
  6207. AudioDestinationNode: C,
  6208. AudioListener: C,
  6209. AudioNode: C,
  6210. AudioParam: C,
  6211. AudioProcessingEvent: C,
  6212. AudioScheduledSourceNode: C,
  6213. AudioWorkletNode: C,
  6214. BarProp: C,
  6215. BaseAudioContext: C,
  6216. BatteryManager: C,
  6217. BeforeUnloadEvent: C,
  6218. BiquadFilterNode: C,
  6219. Blob: C,
  6220. BlobEvent: C,
  6221. blur: O,
  6222. BroadcastChannel: C,
  6223. btoa: O,
  6224. ByteLengthQueuingStrategy: C,
  6225. Cache: C,
  6226. caches: O,
  6227. CacheStorage: C,
  6228. cancelAnimationFrame: O,
  6229. cancelIdleCallback: O,
  6230. CanvasCaptureMediaStreamTrack: C,
  6231. CanvasGradient: C,
  6232. CanvasPattern: C,
  6233. CanvasRenderingContext2D: C,
  6234. ChannelMergerNode: C,
  6235. ChannelSplitterNode: C,
  6236. CharacterData: C,
  6237. clientInformation: O,
  6238. ClipboardEvent: C,
  6239. close: O,
  6240. closed: O,
  6241. CloseEvent: C,
  6242. Comment: C,
  6243. CompositionEvent: C,
  6244. confirm: O,
  6245. ConstantSourceNode: C,
  6246. ConvolverNode: C,
  6247. CountQueuingStrategy: C,
  6248. createImageBitmap: O,
  6249. Credential: C,
  6250. CredentialsContainer: C,
  6251. crypto: O,
  6252. Crypto: C,
  6253. CryptoKey: C,
  6254. CSS: C,
  6255. CSSConditionRule: C,
  6256. CSSFontFaceRule: C,
  6257. CSSGroupingRule: C,
  6258. CSSImportRule: C,
  6259. CSSKeyframeRule: C,
  6260. CSSKeyframesRule: C,
  6261. CSSMediaRule: C,
  6262. CSSNamespaceRule: C,
  6263. CSSPageRule: C,
  6264. CSSRule: C,
  6265. CSSRuleList: C,
  6266. CSSStyleDeclaration: C,
  6267. CSSStyleRule: C,
  6268. CSSStyleSheet: C,
  6269. CSSSupportsRule: C,
  6270. CustomElementRegistry: C,
  6271. customElements: O,
  6272. CustomEvent: C,
  6273. DataTransfer: C,
  6274. DataTransferItem: C,
  6275. DataTransferItemList: C,
  6276. defaultstatus: O,
  6277. defaultStatus: O,
  6278. DelayNode: C,
  6279. DeviceMotionEvent: C,
  6280. DeviceOrientationEvent: C,
  6281. devicePixelRatio: O,
  6282. dispatchEvent: O,
  6283. document: O,
  6284. Document: C,
  6285. DocumentFragment: C,
  6286. DocumentType: C,
  6287. DOMError: C,
  6288. DOMException: C,
  6289. DOMImplementation: C,
  6290. DOMMatrix: C,
  6291. DOMMatrixReadOnly: C,
  6292. DOMParser: C,
  6293. DOMPoint: C,
  6294. DOMPointReadOnly: C,
  6295. DOMQuad: C,
  6296. DOMRect: C,
  6297. DOMRectReadOnly: C,
  6298. DOMStringList: C,
  6299. DOMStringMap: C,
  6300. DOMTokenList: C,
  6301. DragEvent: C,
  6302. DynamicsCompressorNode: C,
  6303. Element: C,
  6304. ErrorEvent: C,
  6305. Event: C,
  6306. EventSource: C,
  6307. EventTarget: C,
  6308. external: O,
  6309. fetch: O,
  6310. File: C,
  6311. FileList: C,
  6312. FileReader: C,
  6313. find: O,
  6314. focus: O,
  6315. FocusEvent: C,
  6316. FontFace: C,
  6317. FontFaceSetLoadEvent: C,
  6318. FormData: C,
  6319. frames: O,
  6320. GainNode: C,
  6321. Gamepad: C,
  6322. GamepadButton: C,
  6323. GamepadEvent: C,
  6324. getComputedStyle: O,
  6325. getSelection: O,
  6326. HashChangeEvent: C,
  6327. Headers: C,
  6328. history: O,
  6329. History: C,
  6330. HTMLAllCollection: C,
  6331. HTMLAnchorElement: C,
  6332. HTMLAreaElement: C,
  6333. HTMLAudioElement: C,
  6334. HTMLBaseElement: C,
  6335. HTMLBodyElement: C,
  6336. HTMLBRElement: C,
  6337. HTMLButtonElement: C,
  6338. HTMLCanvasElement: C,
  6339. HTMLCollection: C,
  6340. HTMLContentElement: C,
  6341. HTMLDataElement: C,
  6342. HTMLDataListElement: C,
  6343. HTMLDetailsElement: C,
  6344. HTMLDialogElement: C,
  6345. HTMLDirectoryElement: C,
  6346. HTMLDivElement: C,
  6347. HTMLDListElement: C,
  6348. HTMLDocument: C,
  6349. HTMLElement: C,
  6350. HTMLEmbedElement: C,
  6351. HTMLFieldSetElement: C,
  6352. HTMLFontElement: C,
  6353. HTMLFormControlsCollection: C,
  6354. HTMLFormElement: C,
  6355. HTMLFrameElement: C,
  6356. HTMLFrameSetElement: C,
  6357. HTMLHeadElement: C,
  6358. HTMLHeadingElement: C,
  6359. HTMLHRElement: C,
  6360. HTMLHtmlElement: C,
  6361. HTMLIFrameElement: C,
  6362. HTMLImageElement: C,
  6363. HTMLInputElement: C,
  6364. HTMLLabelElement: C,
  6365. HTMLLegendElement: C,
  6366. HTMLLIElement: C,
  6367. HTMLLinkElement: C,
  6368. HTMLMapElement: C,
  6369. HTMLMarqueeElement: C,
  6370. HTMLMediaElement: C,
  6371. HTMLMenuElement: C,
  6372. HTMLMetaElement: C,
  6373. HTMLMeterElement: C,
  6374. HTMLModElement: C,
  6375. HTMLObjectElement: C,
  6376. HTMLOListElement: C,
  6377. HTMLOptGroupElement: C,
  6378. HTMLOptionElement: C,
  6379. HTMLOptionsCollection: C,
  6380. HTMLOutputElement: C,
  6381. HTMLParagraphElement: C,
  6382. HTMLParamElement: C,
  6383. HTMLPictureElement: C,
  6384. HTMLPreElement: C,
  6385. HTMLProgressElement: C,
  6386. HTMLQuoteElement: C,
  6387. HTMLScriptElement: C,
  6388. HTMLSelectElement: C,
  6389. HTMLShadowElement: C,
  6390. HTMLSlotElement: C,
  6391. HTMLSourceElement: C,
  6392. HTMLSpanElement: C,
  6393. HTMLStyleElement: C,
  6394. HTMLTableCaptionElement: C,
  6395. HTMLTableCellElement: C,
  6396. HTMLTableColElement: C,
  6397. HTMLTableElement: C,
  6398. HTMLTableRowElement: C,
  6399. HTMLTableSectionElement: C,
  6400. HTMLTemplateElement: C,
  6401. HTMLTextAreaElement: C,
  6402. HTMLTimeElement: C,
  6403. HTMLTitleElement: C,
  6404. HTMLTrackElement: C,
  6405. HTMLUListElement: C,
  6406. HTMLUnknownElement: C,
  6407. HTMLVideoElement: C,
  6408. IDBCursor: C,
  6409. IDBCursorWithValue: C,
  6410. IDBDatabase: C,
  6411. IDBFactory: C,
  6412. IDBIndex: C,
  6413. IDBKeyRange: C,
  6414. IDBObjectStore: C,
  6415. IDBOpenDBRequest: C,
  6416. IDBRequest: C,
  6417. IDBTransaction: C,
  6418. IDBVersionChangeEvent: C,
  6419. IdleDeadline: C,
  6420. IIRFilterNode: C,
  6421. Image: C,
  6422. ImageBitmap: C,
  6423. ImageBitmapRenderingContext: C,
  6424. ImageCapture: C,
  6425. ImageData: C,
  6426. indexedDB: O,
  6427. innerHeight: O,
  6428. innerWidth: O,
  6429. InputEvent: C,
  6430. IntersectionObserver: C,
  6431. IntersectionObserverEntry: C,
  6432. isSecureContext: O,
  6433. KeyboardEvent: C,
  6434. KeyframeEffect: C,
  6435. length: O,
  6436. localStorage: O,
  6437. location: O,
  6438. Location: C,
  6439. locationbar: O,
  6440. matchMedia: O,
  6441. MediaDeviceInfo: C,
  6442. MediaDevices: C,
  6443. MediaElementAudioSourceNode: C,
  6444. MediaEncryptedEvent: C,
  6445. MediaError: C,
  6446. MediaKeyMessageEvent: C,
  6447. MediaKeySession: C,
  6448. MediaKeyStatusMap: C,
  6449. MediaKeySystemAccess: C,
  6450. MediaList: C,
  6451. MediaQueryList: C,
  6452. MediaQueryListEvent: C,
  6453. MediaRecorder: C,
  6454. MediaSettingsRange: C,
  6455. MediaSource: C,
  6456. MediaStream: C,
  6457. MediaStreamAudioDestinationNode: C,
  6458. MediaStreamAudioSourceNode: C,
  6459. MediaStreamEvent: C,
  6460. MediaStreamTrack: C,
  6461. MediaStreamTrackEvent: C,
  6462. menubar: O,
  6463. MessageChannel: C,
  6464. MessageEvent: C,
  6465. MessagePort: C,
  6466. MIDIAccess: C,
  6467. MIDIConnectionEvent: C,
  6468. MIDIInput: C,
  6469. MIDIInputMap: C,
  6470. MIDIMessageEvent: C,
  6471. MIDIOutput: C,
  6472. MIDIOutputMap: C,
  6473. MIDIPort: C,
  6474. MimeType: C,
  6475. MimeTypeArray: C,
  6476. MouseEvent: C,
  6477. moveBy: O,
  6478. moveTo: O,
  6479. MutationEvent: C,
  6480. MutationObserver: C,
  6481. MutationRecord: C,
  6482. name: O,
  6483. NamedNodeMap: C,
  6484. NavigationPreloadManager: C,
  6485. navigator: O,
  6486. Navigator: C,
  6487. NetworkInformation: C,
  6488. Node: C,
  6489. NodeFilter: O,
  6490. NodeIterator: C,
  6491. NodeList: C,
  6492. Notification: C,
  6493. OfflineAudioCompletionEvent: C,
  6494. OfflineAudioContext: C,
  6495. offscreenBuffering: O,
  6496. OffscreenCanvas: C,
  6497. open: O,
  6498. openDatabase: O,
  6499. Option: C,
  6500. origin: O,
  6501. OscillatorNode: C,
  6502. outerHeight: O,
  6503. outerWidth: O,
  6504. PageTransitionEvent: C,
  6505. pageXOffset: O,
  6506. pageYOffset: O,
  6507. PannerNode: C,
  6508. parent: O,
  6509. Path2D: C,
  6510. PaymentAddress: C,
  6511. PaymentRequest: C,
  6512. PaymentRequestUpdateEvent: C,
  6513. PaymentResponse: C,
  6514. performance: O,
  6515. Performance: C,
  6516. PerformanceEntry: C,
  6517. PerformanceLongTaskTiming: C,
  6518. PerformanceMark: C,
  6519. PerformanceMeasure: C,
  6520. PerformanceNavigation: C,
  6521. PerformanceNavigationTiming: C,
  6522. PerformanceObserver: C,
  6523. PerformanceObserverEntryList: C,
  6524. PerformancePaintTiming: C,
  6525. PerformanceResourceTiming: C,
  6526. PerformanceTiming: C,
  6527. PeriodicWave: C,
  6528. Permissions: C,
  6529. PermissionStatus: C,
  6530. personalbar: O,
  6531. PhotoCapabilities: C,
  6532. Plugin: C,
  6533. PluginArray: C,
  6534. PointerEvent: C,
  6535. PopStateEvent: C,
  6536. postMessage: O,
  6537. Presentation: C,
  6538. PresentationAvailability: C,
  6539. PresentationConnection: C,
  6540. PresentationConnectionAvailableEvent: C,
  6541. PresentationConnectionCloseEvent: C,
  6542. PresentationConnectionList: C,
  6543. PresentationReceiver: C,
  6544. PresentationRequest: C,
  6545. print: O,
  6546. ProcessingInstruction: C,
  6547. ProgressEvent: C,
  6548. PromiseRejectionEvent: C,
  6549. prompt: O,
  6550. PushManager: C,
  6551. PushSubscription: C,
  6552. PushSubscriptionOptions: C,
  6553. queueMicrotask: O,
  6554. RadioNodeList: C,
  6555. Range: C,
  6556. ReadableStream: C,
  6557. RemotePlayback: C,
  6558. removeEventListener: O,
  6559. Request: C,
  6560. requestAnimationFrame: O,
  6561. requestIdleCallback: O,
  6562. resizeBy: O,
  6563. ResizeObserver: C,
  6564. ResizeObserverEntry: C,
  6565. resizeTo: O,
  6566. Response: C,
  6567. RTCCertificate: C,
  6568. RTCDataChannel: C,
  6569. RTCDataChannelEvent: C,
  6570. RTCDtlsTransport: C,
  6571. RTCIceCandidate: C,
  6572. RTCIceTransport: C,
  6573. RTCPeerConnection: C,
  6574. RTCPeerConnectionIceEvent: C,
  6575. RTCRtpReceiver: C,
  6576. RTCRtpSender: C,
  6577. RTCSctpTransport: C,
  6578. RTCSessionDescription: C,
  6579. RTCStatsReport: C,
  6580. RTCTrackEvent: C,
  6581. screen: O,
  6582. Screen: C,
  6583. screenLeft: O,
  6584. ScreenOrientation: C,
  6585. screenTop: O,
  6586. screenX: O,
  6587. screenY: O,
  6588. ScriptProcessorNode: C,
  6589. scroll: O,
  6590. scrollbars: O,
  6591. scrollBy: O,
  6592. scrollTo: O,
  6593. scrollX: O,
  6594. scrollY: O,
  6595. SecurityPolicyViolationEvent: C,
  6596. Selection: C,
  6597. ServiceWorker: C,
  6598. ServiceWorkerContainer: C,
  6599. ServiceWorkerRegistration: C,
  6600. sessionStorage: O,
  6601. ShadowRoot: C,
  6602. SharedWorker: C,
  6603. SourceBuffer: C,
  6604. SourceBufferList: C,
  6605. speechSynthesis: O,
  6606. SpeechSynthesisEvent: C,
  6607. SpeechSynthesisUtterance: C,
  6608. StaticRange: C,
  6609. status: O,
  6610. statusbar: O,
  6611. StereoPannerNode: C,
  6612. stop: O,
  6613. Storage: C,
  6614. StorageEvent: C,
  6615. StorageManager: C,
  6616. styleMedia: O,
  6617. StyleSheet: C,
  6618. StyleSheetList: C,
  6619. SubtleCrypto: C,
  6620. SVGAElement: C,
  6621. SVGAngle: C,
  6622. SVGAnimatedAngle: C,
  6623. SVGAnimatedBoolean: C,
  6624. SVGAnimatedEnumeration: C,
  6625. SVGAnimatedInteger: C,
  6626. SVGAnimatedLength: C,
  6627. SVGAnimatedLengthList: C,
  6628. SVGAnimatedNumber: C,
  6629. SVGAnimatedNumberList: C,
  6630. SVGAnimatedPreserveAspectRatio: C,
  6631. SVGAnimatedRect: C,
  6632. SVGAnimatedString: C,
  6633. SVGAnimatedTransformList: C,
  6634. SVGAnimateElement: C,
  6635. SVGAnimateMotionElement: C,
  6636. SVGAnimateTransformElement: C,
  6637. SVGAnimationElement: C,
  6638. SVGCircleElement: C,
  6639. SVGClipPathElement: C,
  6640. SVGComponentTransferFunctionElement: C,
  6641. SVGDefsElement: C,
  6642. SVGDescElement: C,
  6643. SVGDiscardElement: C,
  6644. SVGElement: C,
  6645. SVGEllipseElement: C,
  6646. SVGFEBlendElement: C,
  6647. SVGFEColorMatrixElement: C,
  6648. SVGFEComponentTransferElement: C,
  6649. SVGFECompositeElement: C,
  6650. SVGFEConvolveMatrixElement: C,
  6651. SVGFEDiffuseLightingElement: C,
  6652. SVGFEDisplacementMapElement: C,
  6653. SVGFEDistantLightElement: C,
  6654. SVGFEDropShadowElement: C,
  6655. SVGFEFloodElement: C,
  6656. SVGFEFuncAElement: C,
  6657. SVGFEFuncBElement: C,
  6658. SVGFEFuncGElement: C,
  6659. SVGFEFuncRElement: C,
  6660. SVGFEGaussianBlurElement: C,
  6661. SVGFEImageElement: C,
  6662. SVGFEMergeElement: C,
  6663. SVGFEMergeNodeElement: C,
  6664. SVGFEMorphologyElement: C,
  6665. SVGFEOffsetElement: C,
  6666. SVGFEPointLightElement: C,
  6667. SVGFESpecularLightingElement: C,
  6668. SVGFESpotLightElement: C,
  6669. SVGFETileElement: C,
  6670. SVGFETurbulenceElement: C,
  6671. SVGFilterElement: C,
  6672. SVGForeignObjectElement: C,
  6673. SVGGElement: C,
  6674. SVGGeometryElement: C,
  6675. SVGGradientElement: C,
  6676. SVGGraphicsElement: C,
  6677. SVGImageElement: C,
  6678. SVGLength: C,
  6679. SVGLengthList: C,
  6680. SVGLinearGradientElement: C,
  6681. SVGLineElement: C,
  6682. SVGMarkerElement: C,
  6683. SVGMaskElement: C,
  6684. SVGMatrix: C,
  6685. SVGMetadataElement: C,
  6686. SVGMPathElement: C,
  6687. SVGNumber: C,
  6688. SVGNumberList: C,
  6689. SVGPathElement: C,
  6690. SVGPatternElement: C,
  6691. SVGPoint: C,
  6692. SVGPointList: C,
  6693. SVGPolygonElement: C,
  6694. SVGPolylineElement: C,
  6695. SVGPreserveAspectRatio: C,
  6696. SVGRadialGradientElement: C,
  6697. SVGRect: C,
  6698. SVGRectElement: C,
  6699. SVGScriptElement: C,
  6700. SVGSetElement: C,
  6701. SVGStopElement: C,
  6702. SVGStringList: C,
  6703. SVGStyleElement: C,
  6704. SVGSVGElement: C,
  6705. SVGSwitchElement: C,
  6706. SVGSymbolElement: C,
  6707. SVGTextContentElement: C,
  6708. SVGTextElement: C,
  6709. SVGTextPathElement: C,
  6710. SVGTextPositioningElement: C,
  6711. SVGTitleElement: C,
  6712. SVGTransform: C,
  6713. SVGTransformList: C,
  6714. SVGTSpanElement: C,
  6715. SVGUnitTypes: C,
  6716. SVGUseElement: C,
  6717. SVGViewElement: C,
  6718. TaskAttributionTiming: C,
  6719. Text: C,
  6720. TextEvent: C,
  6721. TextMetrics: C,
  6722. TextTrack: C,
  6723. TextTrackCue: C,
  6724. TextTrackCueList: C,
  6725. TextTrackList: C,
  6726. TimeRanges: C,
  6727. toolbar: O,
  6728. top: O,
  6729. Touch: C,
  6730. TouchEvent: C,
  6731. TouchList: C,
  6732. TrackEvent: C,
  6733. TransitionEvent: C,
  6734. TreeWalker: C,
  6735. UIEvent: C,
  6736. ValidityState: C,
  6737. visualViewport: O,
  6738. VisualViewport: C,
  6739. VTTCue: C,
  6740. WaveShaperNode: C,
  6741. WebAssembly: O,
  6742. WebGL2RenderingContext: C,
  6743. WebGLActiveInfo: C,
  6744. WebGLBuffer: C,
  6745. WebGLContextEvent: C,
  6746. WebGLFramebuffer: C,
  6747. WebGLProgram: C,
  6748. WebGLQuery: C,
  6749. WebGLRenderbuffer: C,
  6750. WebGLRenderingContext: C,
  6751. WebGLSampler: C,
  6752. WebGLShader: C,
  6753. WebGLShaderPrecisionFormat: C,
  6754. WebGLSync: C,
  6755. WebGLTexture: C,
  6756. WebGLTransformFeedback: C,
  6757. WebGLUniformLocation: C,
  6758. WebGLVertexArrayObject: C,
  6759. WebSocket: C,
  6760. WheelEvent: C,
  6761. Window: C,
  6762. Worker: C,
  6763. WritableStream: C,
  6764. XMLDocument: C,
  6765. XMLHttpRequest: C,
  6766. XMLHttpRequestEventTarget: C,
  6767. XMLHttpRequestUpload: C,
  6768. XMLSerializer: C,
  6769. XPathEvaluator: C,
  6770. XPathExpression: C,
  6771. XPathResult: C,
  6772. XSLTProcessor: C
  6773. };
  6774. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6775. knownGlobals[global] = knownGlobals;
  6776. }
  6777. function getGlobalAtPath(path) {
  6778. let currentGlobal = knownGlobals;
  6779. for (const pathSegment of path) {
  6780. if (typeof pathSegment !== 'string') {
  6781. return null;
  6782. }
  6783. currentGlobal = currentGlobal[pathSegment];
  6784. if (!currentGlobal) {
  6785. return null;
  6786. }
  6787. }
  6788. return currentGlobal[ValueProperties];
  6789. }
  6790. class GlobalVariable extends Variable {
  6791. constructor() {
  6792. super(...arguments);
  6793. // Ensure we use live-bindings for globals as we do not know if they have
  6794. // been reassigned
  6795. this.isReassigned = true;
  6796. }
  6797. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6798. return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
  6799. }
  6800. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6801. switch (interaction.type) {
  6802. case INTERACTION_ACCESSED:
  6803. if (path.length === 0) {
  6804. // Technically, "undefined" is a global variable of sorts
  6805. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6806. }
  6807. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6808. case INTERACTION_ASSIGNED:
  6809. return true;
  6810. case INTERACTION_CALLED: {
  6811. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6812. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6813. }
  6814. }
  6815. }
  6816. }
  6817. const tdzVariableKinds = {
  6818. __proto__: null,
  6819. class: true,
  6820. const: true,
  6821. let: true,
  6822. var: true
  6823. };
  6824. class Identifier extends NodeBase {
  6825. constructor() {
  6826. super(...arguments);
  6827. this.variable = null;
  6828. this.isTDZAccess = null;
  6829. }
  6830. addExportedVariables(variables, exportNamesByVariable) {
  6831. if (exportNamesByVariable.has(this.variable)) {
  6832. variables.push(this.variable);
  6833. }
  6834. }
  6835. bind() {
  6836. if (!this.variable && is_reference(this, this.parent)) {
  6837. this.variable = this.scope.findVariable(this.name);
  6838. this.variable.addReference(this);
  6839. }
  6840. }
  6841. declare(kind, init) {
  6842. let variable;
  6843. const { treeshake } = this.context.options;
  6844. switch (kind) {
  6845. case 'var':
  6846. variable = this.scope.addDeclaration(this, this.context, init, true);
  6847. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6848. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6849. variable.markInitializersForDeoptimization();
  6850. }
  6851. break;
  6852. case 'function':
  6853. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6854. variable = this.scope.addDeclaration(this, this.context, init, false);
  6855. break;
  6856. case 'let':
  6857. case 'const':
  6858. case 'class':
  6859. variable = this.scope.addDeclaration(this, this.context, init, false);
  6860. break;
  6861. case 'parameter':
  6862. variable = this.scope.addParameterDeclaration(this);
  6863. break;
  6864. /* istanbul ignore next */
  6865. default:
  6866. /* istanbul ignore next */
  6867. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6868. }
  6869. variable.kind = kind;
  6870. return [(this.variable = variable)];
  6871. }
  6872. deoptimizePath(path) {
  6873. var _a;
  6874. if (path.length === 0 && !this.scope.contains(this.name)) {
  6875. this.disallowImportReassignment();
  6876. }
  6877. // We keep conditional chaining because an unknown Node could have an
  6878. // Identifier as property that might be deoptimized by default
  6879. (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  6880. }
  6881. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6882. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  6883. }
  6884. getLiteralValueAtPath(path, recursionTracker, origin) {
  6885. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6886. }
  6887. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6888. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6889. }
  6890. hasEffects(context) {
  6891. if (!this.deoptimized)
  6892. this.applyDeoptimizations();
  6893. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6894. return true;
  6895. }
  6896. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  6897. this.variable instanceof GlobalVariable &&
  6898. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6899. }
  6900. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6901. switch (interaction.type) {
  6902. case INTERACTION_ACCESSED:
  6903. return (this.variable !== null &&
  6904. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6905. case INTERACTION_ASSIGNED:
  6906. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6907. case INTERACTION_CALLED:
  6908. return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
  6909. }
  6910. }
  6911. include() {
  6912. if (!this.deoptimized)
  6913. this.applyDeoptimizations();
  6914. if (!this.included) {
  6915. this.included = true;
  6916. if (this.variable !== null) {
  6917. this.context.includeVariableInModule(this.variable);
  6918. }
  6919. }
  6920. }
  6921. includeCallArguments(context, args) {
  6922. this.variable.includeCallArguments(context, args);
  6923. }
  6924. isPossibleTDZ() {
  6925. // return cached value to avoid issues with the next tree-shaking pass
  6926. if (this.isTDZAccess !== null)
  6927. return this.isTDZAccess;
  6928. if (!(this.variable instanceof LocalVariable) ||
  6929. !this.variable.kind ||
  6930. !(this.variable.kind in tdzVariableKinds)) {
  6931. return (this.isTDZAccess = false);
  6932. }
  6933. let decl_id;
  6934. if (this.variable.declarations &&
  6935. this.variable.declarations.length === 1 &&
  6936. (decl_id = this.variable.declarations[0]) &&
  6937. this.start < decl_id.start &&
  6938. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6939. // a variable accessed before its declaration
  6940. // in the same function or at top level of module
  6941. return (this.isTDZAccess = true);
  6942. }
  6943. if (!this.variable.initReached) {
  6944. // Either a const/let TDZ violation or
  6945. // var use before declaration was encountered.
  6946. return (this.isTDZAccess = true);
  6947. }
  6948. return (this.isTDZAccess = false);
  6949. }
  6950. markDeclarationReached() {
  6951. this.variable.initReached = true;
  6952. }
  6953. render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  6954. if (this.variable) {
  6955. const name = this.variable.getName(getPropertyAccess);
  6956. if (name !== this.name) {
  6957. code.overwrite(this.start, this.end, name, {
  6958. contentOnly: true,
  6959. storeName: true
  6960. });
  6961. if (isShorthandProperty) {
  6962. code.prependRight(this.start, `${this.name}: `);
  6963. }
  6964. }
  6965. // In strict mode, any variable named "eval" must be the actual "eval" function
  6966. if (name === 'eval' &&
  6967. renderedParentType === CallExpression$1 &&
  6968. isCalleeOfRenderedParent) {
  6969. code.appendRight(this.start, '0, ');
  6970. }
  6971. }
  6972. }
  6973. applyDeoptimizations() {
  6974. this.deoptimized = true;
  6975. if (this.variable instanceof LocalVariable) {
  6976. this.variable.consolidateInitializers();
  6977. this.context.requestTreeshakingPass();
  6978. }
  6979. }
  6980. disallowImportReassignment() {
  6981. return this.context.error({
  6982. code: 'ILLEGAL_REASSIGNMENT',
  6983. message: `Illegal reassignment to import '${this.name}'`
  6984. }, this.start);
  6985. }
  6986. getVariableRespectingTDZ() {
  6987. if (this.isPossibleTDZ()) {
  6988. return UNKNOWN_EXPRESSION;
  6989. }
  6990. return this.variable;
  6991. }
  6992. }
  6993. function closestParentFunctionOrProgram(node) {
  6994. while (node && !/^Program|Function/.test(node.type)) {
  6995. node = node.parent;
  6996. }
  6997. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6998. return node;
  6999. }
  7000. function treeshakeNode(node, code, start, end) {
  7001. code.remove(start, end);
  7002. if (node.annotations) {
  7003. for (const annotation of node.annotations) {
  7004. if (annotation.start < start) {
  7005. code.remove(annotation.start, annotation.end);
  7006. }
  7007. else {
  7008. return;
  7009. }
  7010. }
  7011. }
  7012. }
  7013. function removeAnnotations(node, code) {
  7014. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  7015. node = node.parent;
  7016. }
  7017. if (node.annotations) {
  7018. for (const annotation of node.annotations) {
  7019. code.remove(annotation.start, annotation.end);
  7020. }
  7021. }
  7022. }
  7023. const NO_SEMICOLON = { isNoStatement: true };
  7024. // This assumes there are only white-space and comments between start and the string we are looking for
  7025. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  7026. let searchPos, charCodeAfterSlash;
  7027. searchPos = code.indexOf(searchString, start);
  7028. while (true) {
  7029. start = code.indexOf('/', start);
  7030. if (start === -1 || start >= searchPos)
  7031. return searchPos;
  7032. charCodeAfterSlash = code.charCodeAt(++start);
  7033. ++start;
  7034. // With our assumption, '/' always starts a comment. Determine comment type:
  7035. start =
  7036. charCodeAfterSlash === 47 /*"/"*/
  7037. ? code.indexOf('\n', start) + 1
  7038. : code.indexOf('*/', start) + 2;
  7039. if (start > searchPos) {
  7040. searchPos = code.indexOf(searchString, start);
  7041. }
  7042. }
  7043. }
  7044. const NON_WHITESPACE = /\S/g;
  7045. function findNonWhiteSpace(code, index) {
  7046. NON_WHITESPACE.lastIndex = index;
  7047. const result = NON_WHITESPACE.exec(code);
  7048. return result.index;
  7049. }
  7050. // This assumes "code" only contains white-space and comments
  7051. // Returns position of line-comment if applicable
  7052. function findFirstLineBreakOutsideComment(code) {
  7053. let lineBreakPos, charCodeAfterSlash, start = 0;
  7054. lineBreakPos = code.indexOf('\n', start);
  7055. while (true) {
  7056. start = code.indexOf('/', start);
  7057. if (start === -1 || start > lineBreakPos)
  7058. return [lineBreakPos, lineBreakPos + 1];
  7059. // With our assumption, '/' always starts a comment. Determine comment type:
  7060. charCodeAfterSlash = code.charCodeAt(start + 1);
  7061. if (charCodeAfterSlash === 47 /*"/"*/)
  7062. return [start, lineBreakPos + 1];
  7063. start = code.indexOf('*/', start + 3) + 2;
  7064. if (start > lineBreakPos) {
  7065. lineBreakPos = code.indexOf('\n', start);
  7066. }
  7067. }
  7068. }
  7069. function renderStatementList(statements, code, start, end, options) {
  7070. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  7071. let nextNode = statements[0];
  7072. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  7073. if (nextNodeNeedsBoundaries) {
  7074. nextNodeStart =
  7075. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  7076. }
  7077. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  7078. currentNode = nextNode;
  7079. currentNodeStart = nextNodeStart;
  7080. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  7081. nextNode = statements[nextIndex];
  7082. nextNodeNeedsBoundaries =
  7083. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  7084. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  7085. nextNodeStart =
  7086. currentNode.end +
  7087. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  7088. if (currentNode.included) {
  7089. currentNodeNeedsBoundaries
  7090. ? currentNode.render(code, options, {
  7091. end: nextNodeStart,
  7092. start: currentNodeStart
  7093. })
  7094. : currentNode.render(code, options);
  7095. }
  7096. else {
  7097. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  7098. }
  7099. }
  7100. else {
  7101. currentNode.render(code, options);
  7102. }
  7103. }
  7104. }
  7105. // This assumes that the first character is not part of the first node
  7106. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  7107. const splitUpNodes = [];
  7108. let node, nextNode, nextNodeStart, contentEnd, char;
  7109. let separator = start - 1;
  7110. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  7111. nextNode = nodes[nextIndex];
  7112. if (node !== undefined) {
  7113. separator =
  7114. node.end +
  7115. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  7116. }
  7117. nextNodeStart = contentEnd =
  7118. separator +
  7119. 1 +
  7120. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  7121. while (((char = code.original.charCodeAt(nextNodeStart)),
  7122. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  7123. nextNodeStart++;
  7124. if (node !== undefined) {
  7125. splitUpNodes.push({
  7126. contentEnd,
  7127. end: nextNodeStart,
  7128. node,
  7129. separator,
  7130. start
  7131. });
  7132. }
  7133. node = nextNode;
  7134. start = nextNodeStart;
  7135. }
  7136. splitUpNodes.push({
  7137. contentEnd: end,
  7138. end,
  7139. node: node,
  7140. separator: null,
  7141. start
  7142. });
  7143. return splitUpNodes;
  7144. }
  7145. // This assumes there are only white-space and comments between start and end
  7146. function removeLineBreaks(code, start, end) {
  7147. while (true) {
  7148. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  7149. if (removeStart === -1) {
  7150. break;
  7151. }
  7152. code.remove(start + removeStart, (start += removeEnd));
  7153. }
  7154. }
  7155. class BlockScope extends ChildScope {
  7156. addDeclaration(identifier, context, init, isHoisted) {
  7157. if (isHoisted) {
  7158. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  7159. // Necessary to make sure the init is deoptimized for conditional declarations.
  7160. // We cannot call deoptimizePath here.
  7161. variable.markInitializersForDeoptimization();
  7162. return variable;
  7163. }
  7164. else {
  7165. return super.addDeclaration(identifier, context, init, false);
  7166. }
  7167. }
  7168. }
  7169. class ExpressionStatement extends NodeBase {
  7170. initialise() {
  7171. if (this.directive &&
  7172. this.directive !== 'use strict' &&
  7173. this.parent.type === Program$1) {
  7174. this.context.warn(
  7175. // This is necessary, because either way (deleting or not) can lead to errors.
  7176. {
  7177. code: 'MODULE_LEVEL_DIRECTIVE',
  7178. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  7179. }, this.start);
  7180. }
  7181. }
  7182. render(code, options) {
  7183. super.render(code, options);
  7184. if (this.included)
  7185. this.insertSemicolon(code);
  7186. }
  7187. shouldBeIncluded(context) {
  7188. if (this.directive && this.directive !== 'use strict')
  7189. return this.parent.type !== Program$1;
  7190. return super.shouldBeIncluded(context);
  7191. }
  7192. applyDeoptimizations() { }
  7193. }
  7194. class BlockStatement extends NodeBase {
  7195. constructor() {
  7196. super(...arguments);
  7197. this.directlyIncluded = false;
  7198. }
  7199. addImplicitReturnExpressionToScope() {
  7200. const lastStatement = this.body[this.body.length - 1];
  7201. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  7202. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7203. }
  7204. }
  7205. createScope(parentScope) {
  7206. this.scope = this.parent.preventChildBlockScope
  7207. ? parentScope
  7208. : new BlockScope(parentScope);
  7209. }
  7210. hasEffects(context) {
  7211. if (this.deoptimizeBody)
  7212. return true;
  7213. for (const node of this.body) {
  7214. if (context.brokenFlow)
  7215. break;
  7216. if (node.hasEffects(context))
  7217. return true;
  7218. }
  7219. return false;
  7220. }
  7221. include(context, includeChildrenRecursively) {
  7222. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7223. this.included = true;
  7224. this.directlyIncluded = true;
  7225. if (this.deoptimizeBody)
  7226. includeChildrenRecursively = true;
  7227. for (const node of this.body) {
  7228. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7229. node.include(context, includeChildrenRecursively);
  7230. }
  7231. }
  7232. }
  7233. initialise() {
  7234. const firstBodyStatement = this.body[0];
  7235. this.deoptimizeBody =
  7236. firstBodyStatement instanceof ExpressionStatement &&
  7237. firstBodyStatement.directive === 'use asm';
  7238. }
  7239. render(code, options) {
  7240. if (this.body.length) {
  7241. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7242. }
  7243. else {
  7244. super.render(code, options);
  7245. }
  7246. }
  7247. }
  7248. class RestElement extends NodeBase {
  7249. constructor() {
  7250. super(...arguments);
  7251. this.declarationInit = null;
  7252. }
  7253. addExportedVariables(variables, exportNamesByVariable) {
  7254. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7255. }
  7256. declare(kind, init) {
  7257. this.declarationInit = init;
  7258. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7259. }
  7260. deoptimizePath(path) {
  7261. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  7262. }
  7263. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7264. return (path.length > 0 ||
  7265. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7266. }
  7267. markDeclarationReached() {
  7268. this.argument.markDeclarationReached();
  7269. }
  7270. applyDeoptimizations() {
  7271. this.deoptimized = true;
  7272. if (this.declarationInit !== null) {
  7273. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7274. this.context.requestTreeshakingPass();
  7275. }
  7276. }
  7277. }
  7278. class FunctionBase extends NodeBase {
  7279. constructor() {
  7280. super(...arguments);
  7281. this.objectEntity = null;
  7282. this.deoptimizedReturn = false;
  7283. }
  7284. deoptimizePath(path) {
  7285. this.getObjectEntity().deoptimizePath(path);
  7286. if (path.length === 1 && path[0] === UnknownKey) {
  7287. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7288. // which means the return expression needs to be reassigned
  7289. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7290. }
  7291. }
  7292. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7293. if (path.length > 0) {
  7294. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7295. }
  7296. }
  7297. getLiteralValueAtPath(path, recursionTracker, origin) {
  7298. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7299. }
  7300. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7301. if (path.length > 0) {
  7302. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7303. }
  7304. if (this.async) {
  7305. if (!this.deoptimizedReturn) {
  7306. this.deoptimizedReturn = true;
  7307. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7308. this.context.requestTreeshakingPass();
  7309. }
  7310. return UNKNOWN_EXPRESSION;
  7311. }
  7312. return this.scope.getReturnExpression();
  7313. }
  7314. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7315. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7316. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7317. }
  7318. if (this.async) {
  7319. const { propertyReadSideEffects } = this.context.options
  7320. .treeshake;
  7321. const returnExpression = this.scope.getReturnExpression();
  7322. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7323. (propertyReadSideEffects &&
  7324. (propertyReadSideEffects === 'always' ||
  7325. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7326. return true;
  7327. }
  7328. }
  7329. for (const param of this.params) {
  7330. if (param.hasEffects(context))
  7331. return true;
  7332. }
  7333. return false;
  7334. }
  7335. include(context, includeChildrenRecursively) {
  7336. if (!this.deoptimized)
  7337. this.applyDeoptimizations();
  7338. this.included = true;
  7339. const { brokenFlow } = context;
  7340. context.brokenFlow = BROKEN_FLOW_NONE;
  7341. this.body.include(context, includeChildrenRecursively);
  7342. context.brokenFlow = brokenFlow;
  7343. }
  7344. includeCallArguments(context, args) {
  7345. this.scope.includeCallArguments(context, args);
  7346. }
  7347. initialise() {
  7348. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  7349. if (this.body instanceof BlockStatement) {
  7350. this.body.addImplicitReturnExpressionToScope();
  7351. }
  7352. else {
  7353. this.scope.addReturnExpression(this.body);
  7354. }
  7355. }
  7356. parseNode(esTreeNode) {
  7357. if (esTreeNode.body.type === BlockStatement$1) {
  7358. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  7359. }
  7360. super.parseNode(esTreeNode);
  7361. }
  7362. applyDeoptimizations() { }
  7363. }
  7364. FunctionBase.prototype.preventChildBlockScope = true;
  7365. class ArrowFunctionExpression extends FunctionBase {
  7366. constructor() {
  7367. super(...arguments);
  7368. this.objectEntity = null;
  7369. }
  7370. createScope(parentScope) {
  7371. this.scope = new ReturnValueScope(parentScope, this.context);
  7372. }
  7373. hasEffects() {
  7374. if (!this.deoptimized)
  7375. this.applyDeoptimizations();
  7376. return false;
  7377. }
  7378. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7379. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7380. return true;
  7381. if (interaction.type === INTERACTION_CALLED) {
  7382. const { ignore, brokenFlow } = context;
  7383. context.ignore = {
  7384. breaks: false,
  7385. continues: false,
  7386. labels: new Set(),
  7387. returnYield: true
  7388. };
  7389. if (this.body.hasEffects(context))
  7390. return true;
  7391. context.ignore = ignore;
  7392. context.brokenFlow = brokenFlow;
  7393. }
  7394. return false;
  7395. }
  7396. include(context, includeChildrenRecursively) {
  7397. super.include(context, includeChildrenRecursively);
  7398. for (const param of this.params) {
  7399. if (!(param instanceof Identifier)) {
  7400. param.include(context, includeChildrenRecursively);
  7401. }
  7402. }
  7403. }
  7404. getObjectEntity() {
  7405. if (this.objectEntity !== null) {
  7406. return this.objectEntity;
  7407. }
  7408. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  7409. }
  7410. }
  7411. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  7412. if (exportedVariables.length === 1 &&
  7413. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  7414. const variable = exportedVariables[0];
  7415. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  7416. }
  7417. else {
  7418. const fields = [];
  7419. for (const variable of exportedVariables) {
  7420. for (const exportName of exportNamesByVariable.get(variable)) {
  7421. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  7422. }
  7423. }
  7424. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  7425. }
  7426. }
  7427. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  7428. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  7429. code.appendLeft(expressionEnd, ')');
  7430. }
  7431. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  7432. const { _, getDirectReturnIifeLeft } = options.snippets;
  7433. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  7434. code.appendLeft(expressionEnd, ')');
  7435. }
  7436. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  7437. const { _, getPropertyAccess } = options.snippets;
  7438. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  7439. if (needsParens) {
  7440. code.prependRight(expressionStart, '(');
  7441. code.appendLeft(expressionEnd, ')');
  7442. }
  7443. }
  7444. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  7445. const { _ } = options.snippets;
  7446. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  7447. if (needsParens) {
  7448. code.prependRight(expressionStart, '(');
  7449. code.appendLeft(expressionEnd, ')');
  7450. }
  7451. }
  7452. class ObjectPattern extends NodeBase {
  7453. addExportedVariables(variables, exportNamesByVariable) {
  7454. for (const property of this.properties) {
  7455. if (property.type === Property$1) {
  7456. property.value.addExportedVariables(variables, exportNamesByVariable);
  7457. }
  7458. else {
  7459. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7460. }
  7461. }
  7462. }
  7463. declare(kind, init) {
  7464. const variables = [];
  7465. for (const property of this.properties) {
  7466. variables.push(...property.declare(kind, init));
  7467. }
  7468. return variables;
  7469. }
  7470. deoptimizePath(path) {
  7471. if (path.length === 0) {
  7472. for (const property of this.properties) {
  7473. property.deoptimizePath(path);
  7474. }
  7475. }
  7476. }
  7477. hasEffectsOnInteractionAtPath(
  7478. // At the moment, this is only triggered for assignment left-hand sides,
  7479. // where the path is empty
  7480. _path, interaction, context) {
  7481. for (const property of this.properties) {
  7482. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7483. return true;
  7484. }
  7485. return false;
  7486. }
  7487. markDeclarationReached() {
  7488. for (const property of this.properties) {
  7489. property.markDeclarationReached();
  7490. }
  7491. }
  7492. }
  7493. class AssignmentExpression extends NodeBase {
  7494. hasEffects(context) {
  7495. const { deoptimized, left, right } = this;
  7496. if (!deoptimized)
  7497. this.applyDeoptimizations();
  7498. // MemberExpressions do not access the property before assignments if the
  7499. // operator is '='.
  7500. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
  7501. }
  7502. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7503. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  7504. }
  7505. include(context, includeChildrenRecursively) {
  7506. const { deoptimized, left, right, operator } = this;
  7507. if (!deoptimized)
  7508. this.applyDeoptimizations();
  7509. this.included = true;
  7510. if (includeChildrenRecursively ||
  7511. operator !== '=' ||
  7512. left.included ||
  7513. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  7514. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  7515. }
  7516. right.include(context, includeChildrenRecursively);
  7517. }
  7518. initialise() {
  7519. this.left.setAssignedValue(this.right);
  7520. }
  7521. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7522. const { left, right, start, end, parent } = this;
  7523. if (left.included) {
  7524. left.render(code, options);
  7525. right.render(code, options);
  7526. }
  7527. else {
  7528. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  7529. code.remove(start, inclusionStart);
  7530. if (preventASI) {
  7531. removeLineBreaks(code, inclusionStart, right.start);
  7532. }
  7533. right.render(code, options, {
  7534. renderedParentType: renderedParentType || parent.type,
  7535. renderedSurroundingElement: renderedSurroundingElement || parent.type
  7536. });
  7537. }
  7538. if (options.format === 'system') {
  7539. if (left instanceof Identifier) {
  7540. const variable = left.variable;
  7541. const exportNames = options.exportNamesByVariable.get(variable);
  7542. if (exportNames) {
  7543. if (exportNames.length === 1) {
  7544. renderSystemExportExpression(variable, start, end, code, options);
  7545. }
  7546. else {
  7547. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  7548. }
  7549. return;
  7550. }
  7551. }
  7552. else {
  7553. const systemPatternExports = [];
  7554. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  7555. if (systemPatternExports.length > 0) {
  7556. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  7557. return;
  7558. }
  7559. }
  7560. }
  7561. if (left.included &&
  7562. left instanceof ObjectPattern &&
  7563. (renderedSurroundingElement === ExpressionStatement$1 ||
  7564. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  7565. code.appendRight(start, '(');
  7566. code.prependLeft(end, ')');
  7567. }
  7568. }
  7569. applyDeoptimizations() {
  7570. this.deoptimized = true;
  7571. this.left.deoptimizePath(EMPTY_PATH);
  7572. this.right.deoptimizePath(UNKNOWN_PATH);
  7573. this.context.requestTreeshakingPass();
  7574. }
  7575. }
  7576. class AssignmentPattern extends NodeBase {
  7577. addExportedVariables(variables, exportNamesByVariable) {
  7578. this.left.addExportedVariables(variables, exportNamesByVariable);
  7579. }
  7580. declare(kind, init) {
  7581. return this.left.declare(kind, init);
  7582. }
  7583. deoptimizePath(path) {
  7584. path.length === 0 && this.left.deoptimizePath(path);
  7585. }
  7586. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7587. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7588. }
  7589. markDeclarationReached() {
  7590. this.left.markDeclarationReached();
  7591. }
  7592. render(code, options, { isShorthandProperty } = BLANK) {
  7593. this.left.render(code, options, { isShorthandProperty });
  7594. this.right.render(code, options);
  7595. }
  7596. applyDeoptimizations() {
  7597. this.deoptimized = true;
  7598. this.left.deoptimizePath(EMPTY_PATH);
  7599. this.right.deoptimizePath(UNKNOWN_PATH);
  7600. this.context.requestTreeshakingPass();
  7601. }
  7602. }
  7603. class ArgumentsVariable extends LocalVariable {
  7604. constructor(context) {
  7605. super('arguments', null, UNKNOWN_EXPRESSION, context);
  7606. }
  7607. hasEffectsOnInteractionAtPath(path, { type }) {
  7608. return type !== INTERACTION_ACCESSED || path.length > 1;
  7609. }
  7610. }
  7611. class ThisVariable extends LocalVariable {
  7612. constructor(context) {
  7613. super('this', null, null, context);
  7614. this.deoptimizedPaths = [];
  7615. this.entitiesToBeDeoptimized = new Set();
  7616. this.thisDeoptimizationList = [];
  7617. this.thisDeoptimizations = new DiscriminatedPathTracker();
  7618. }
  7619. addEntityToBeDeoptimized(entity) {
  7620. for (const path of this.deoptimizedPaths) {
  7621. entity.deoptimizePath(path);
  7622. }
  7623. for (const { interaction, path } of this.thisDeoptimizationList) {
  7624. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7625. }
  7626. this.entitiesToBeDeoptimized.add(entity);
  7627. }
  7628. deoptimizePath(path) {
  7629. if (path.length === 0 ||
  7630. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7631. return;
  7632. }
  7633. this.deoptimizedPaths.push(path);
  7634. for (const entity of this.entitiesToBeDeoptimized) {
  7635. entity.deoptimizePath(path);
  7636. }
  7637. }
  7638. deoptimizeThisOnInteractionAtPath(interaction, path) {
  7639. const thisDeoptimization = {
  7640. interaction,
  7641. path
  7642. };
  7643. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
  7644. for (const entity of this.entitiesToBeDeoptimized) {
  7645. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7646. }
  7647. this.thisDeoptimizationList.push(thisDeoptimization);
  7648. }
  7649. }
  7650. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7651. return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
  7652. super.hasEffectsOnInteractionAtPath(path, interaction, context));
  7653. }
  7654. getInit(context) {
  7655. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  7656. }
  7657. }
  7658. class FunctionScope extends ReturnValueScope {
  7659. constructor(parent, context) {
  7660. super(parent, context);
  7661. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7662. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7663. }
  7664. findLexicalBoundary() {
  7665. return this;
  7666. }
  7667. includeCallArguments(context, args) {
  7668. super.includeCallArguments(context, args);
  7669. if (this.argumentsVariable.included) {
  7670. for (const arg of args) {
  7671. if (!arg.included) {
  7672. arg.include(context, false);
  7673. }
  7674. }
  7675. }
  7676. }
  7677. }
  7678. class FunctionNode extends FunctionBase {
  7679. constructor() {
  7680. super(...arguments);
  7681. this.objectEntity = null;
  7682. }
  7683. createScope(parentScope) {
  7684. this.scope = new FunctionScope(parentScope, this.context);
  7685. }
  7686. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7687. super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7688. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  7689. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
  7690. }
  7691. }
  7692. hasEffects(context) {
  7693. var _a;
  7694. if (!this.deoptimized)
  7695. this.applyDeoptimizations();
  7696. return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  7697. }
  7698. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7699. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7700. return true;
  7701. if (interaction.type === INTERACTION_CALLED) {
  7702. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7703. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
  7704. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  7705. : UNKNOWN_EXPRESSION);
  7706. const { brokenFlow, ignore } = context;
  7707. context.ignore = {
  7708. breaks: false,
  7709. continues: false,
  7710. labels: new Set(),
  7711. returnYield: true
  7712. };
  7713. if (this.body.hasEffects(context))
  7714. return true;
  7715. context.brokenFlow = brokenFlow;
  7716. if (thisInit) {
  7717. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7718. }
  7719. else {
  7720. context.replacedVariableInits.delete(this.scope.thisVariable);
  7721. }
  7722. context.ignore = ignore;
  7723. }
  7724. return false;
  7725. }
  7726. include(context, includeChildrenRecursively) {
  7727. var _a;
  7728. super.include(context, includeChildrenRecursively);
  7729. (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
  7730. const hasArguments = this.scope.argumentsVariable.included;
  7731. for (const param of this.params) {
  7732. if (!(param instanceof Identifier) || hasArguments) {
  7733. param.include(context, includeChildrenRecursively);
  7734. }
  7735. }
  7736. }
  7737. initialise() {
  7738. var _a;
  7739. super.initialise();
  7740. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
  7741. }
  7742. getObjectEntity() {
  7743. if (this.objectEntity !== null) {
  7744. return this.objectEntity;
  7745. }
  7746. return (this.objectEntity = new ObjectEntity([
  7747. {
  7748. key: 'prototype',
  7749. kind: 'init',
  7750. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7751. }
  7752. ], OBJECT_PROTOTYPE));
  7753. }
  7754. }
  7755. class AwaitExpression extends NodeBase {
  7756. hasEffects() {
  7757. if (!this.deoptimized)
  7758. this.applyDeoptimizations();
  7759. return true;
  7760. }
  7761. include(context, includeChildrenRecursively) {
  7762. if (!this.deoptimized)
  7763. this.applyDeoptimizations();
  7764. if (!this.included) {
  7765. this.included = true;
  7766. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  7767. let parent = this.parent;
  7768. do {
  7769. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  7770. break checkTopLevelAwait;
  7771. } while ((parent = parent.parent));
  7772. this.context.usesTopLevelAwait = true;
  7773. }
  7774. }
  7775. this.argument.include(context, includeChildrenRecursively);
  7776. }
  7777. }
  7778. const binaryOperators = {
  7779. '!=': (left, right) => left != right,
  7780. '!==': (left, right) => left !== right,
  7781. '%': (left, right) => left % right,
  7782. '&': (left, right) => left & right,
  7783. '*': (left, right) => left * right,
  7784. // At the moment, "**" will be transpiled to Math.pow
  7785. '**': (left, right) => left ** right,
  7786. '+': (left, right) => left + right,
  7787. '-': (left, right) => left - right,
  7788. '/': (left, right) => left / right,
  7789. '<': (left, right) => left < right,
  7790. '<<': (left, right) => left << right,
  7791. '<=': (left, right) => left <= right,
  7792. '==': (left, right) => left == right,
  7793. '===': (left, right) => left === right,
  7794. '>': (left, right) => left > right,
  7795. '>=': (left, right) => left >= right,
  7796. '>>': (left, right) => left >> right,
  7797. '>>>': (left, right) => left >>> right,
  7798. '^': (left, right) => left ^ right,
  7799. '|': (left, right) => left | right
  7800. // We use the fallback for cases where we return something unknown
  7801. // in: () => UnknownValue,
  7802. // instanceof: () => UnknownValue,
  7803. };
  7804. class BinaryExpression extends NodeBase {
  7805. deoptimizeCache() { }
  7806. getLiteralValueAtPath(path, recursionTracker, origin) {
  7807. if (path.length > 0)
  7808. return UnknownValue;
  7809. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7810. if (typeof leftValue === 'symbol')
  7811. return UnknownValue;
  7812. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7813. if (typeof rightValue === 'symbol')
  7814. return UnknownValue;
  7815. const operatorFn = binaryOperators[this.operator];
  7816. if (!operatorFn)
  7817. return UnknownValue;
  7818. return operatorFn(leftValue, rightValue);
  7819. }
  7820. hasEffects(context) {
  7821. // support some implicit type coercion runtime errors
  7822. if (this.operator === '+' &&
  7823. this.parent instanceof ExpressionStatement &&
  7824. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  7825. return true;
  7826. }
  7827. return super.hasEffects(context);
  7828. }
  7829. hasEffectsOnInteractionAtPath(path, { type }) {
  7830. return type !== INTERACTION_ACCESSED || path.length > 1;
  7831. }
  7832. render(code, options, { renderedSurroundingElement } = BLANK) {
  7833. this.left.render(code, options, { renderedSurroundingElement });
  7834. this.right.render(code, options);
  7835. }
  7836. }
  7837. class BreakStatement extends NodeBase {
  7838. hasEffects(context) {
  7839. if (this.label) {
  7840. if (!context.ignore.labels.has(this.label.name))
  7841. return true;
  7842. context.includedLabels.add(this.label.name);
  7843. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7844. }
  7845. else {
  7846. if (!context.ignore.breaks)
  7847. return true;
  7848. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7849. }
  7850. return false;
  7851. }
  7852. include(context) {
  7853. this.included = true;
  7854. if (this.label) {
  7855. this.label.include();
  7856. context.includedLabels.add(this.label.name);
  7857. }
  7858. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7859. }
  7860. }
  7861. function renderCallArguments(code, options, node) {
  7862. if (node.arguments.length > 0) {
  7863. if (node.arguments[node.arguments.length - 1].included) {
  7864. for (const arg of node.arguments) {
  7865. arg.render(code, options);
  7866. }
  7867. }
  7868. else {
  7869. let lastIncludedIndex = node.arguments.length - 2;
  7870. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  7871. lastIncludedIndex--;
  7872. }
  7873. if (lastIncludedIndex >= 0) {
  7874. for (let index = 0; index <= lastIncludedIndex; index++) {
  7875. node.arguments[index].render(code, options);
  7876. }
  7877. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  7878. }
  7879. else {
  7880. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  7881. }
  7882. }
  7883. }
  7884. }
  7885. class Literal extends NodeBase {
  7886. deoptimizeThisOnInteractionAtPath() { }
  7887. getLiteralValueAtPath(path) {
  7888. if (path.length > 0 ||
  7889. // unknown literals can also be null but do not start with an "n"
  7890. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  7891. typeof this.value === 'bigint' ||
  7892. // to support shims for regular expressions
  7893. this.context.code.charCodeAt(this.start) === 47) {
  7894. return UnknownValue;
  7895. }
  7896. return this.value;
  7897. }
  7898. getReturnExpressionWhenCalledAtPath(path) {
  7899. if (path.length !== 1)
  7900. return UNKNOWN_EXPRESSION;
  7901. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7902. }
  7903. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7904. switch (interaction.type) {
  7905. case INTERACTION_ACCESSED:
  7906. return path.length > (this.value === null ? 0 : 1);
  7907. case INTERACTION_ASSIGNED:
  7908. return true;
  7909. case INTERACTION_CALLED:
  7910. return (path.length !== 1 ||
  7911. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7912. }
  7913. }
  7914. initialise() {
  7915. this.members = getLiteralMembersForValue(this.value);
  7916. }
  7917. parseNode(esTreeNode) {
  7918. this.value = esTreeNode.value;
  7919. this.regex = esTreeNode.regex;
  7920. super.parseNode(esTreeNode);
  7921. }
  7922. render(code) {
  7923. if (typeof this.value === 'string') {
  7924. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7925. }
  7926. }
  7927. }
  7928. // To avoid infinite recursions
  7929. const MAX_PATH_DEPTH = 7;
  7930. function getResolvablePropertyKey(memberExpression) {
  7931. return memberExpression.computed
  7932. ? getResolvableComputedPropertyKey(memberExpression.property)
  7933. : memberExpression.property.name;
  7934. }
  7935. function getResolvableComputedPropertyKey(propertyKey) {
  7936. if (propertyKey instanceof Literal) {
  7937. return String(propertyKey.value);
  7938. }
  7939. return null;
  7940. }
  7941. function getPathIfNotComputed(memberExpression) {
  7942. const nextPathKey = memberExpression.propertyKey;
  7943. const object = memberExpression.object;
  7944. if (typeof nextPathKey === 'string') {
  7945. if (object instanceof Identifier) {
  7946. return [
  7947. { key: object.name, pos: object.start },
  7948. { key: nextPathKey, pos: memberExpression.property.start }
  7949. ];
  7950. }
  7951. if (object instanceof MemberExpression) {
  7952. const parentPath = getPathIfNotComputed(object);
  7953. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7954. }
  7955. }
  7956. return null;
  7957. }
  7958. function getStringFromPath(path) {
  7959. let pathString = path[0].key;
  7960. for (let index = 1; index < path.length; index++) {
  7961. pathString += '.' + path[index].key;
  7962. }
  7963. return pathString;
  7964. }
  7965. class MemberExpression extends NodeBase {
  7966. constructor() {
  7967. super(...arguments);
  7968. this.variable = null;
  7969. this.assignmentDeoptimized = false;
  7970. this.bound = false;
  7971. this.expressionsToBeDeoptimized = [];
  7972. this.replacement = null;
  7973. }
  7974. bind() {
  7975. this.bound = true;
  7976. const path = getPathIfNotComputed(this);
  7977. const baseVariable = path && this.scope.findVariable(path[0].key);
  7978. if (baseVariable && baseVariable.isNamespace) {
  7979. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  7980. if (!resolvedVariable) {
  7981. super.bind();
  7982. }
  7983. else if (typeof resolvedVariable === 'string') {
  7984. this.replacement = resolvedVariable;
  7985. }
  7986. else {
  7987. this.variable = resolvedVariable;
  7988. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7989. }
  7990. }
  7991. else {
  7992. super.bind();
  7993. }
  7994. }
  7995. deoptimizeCache() {
  7996. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7997. this.expressionsToBeDeoptimized = [];
  7998. this.propertyKey = UnknownKey;
  7999. this.object.deoptimizePath(UNKNOWN_PATH);
  8000. for (const expression of expressionsToBeDeoptimized) {
  8001. expression.deoptimizeCache();
  8002. }
  8003. }
  8004. deoptimizePath(path) {
  8005. if (path.length === 0)
  8006. this.disallowNamespaceReassignment();
  8007. if (this.variable) {
  8008. this.variable.deoptimizePath(path);
  8009. }
  8010. else if (!this.replacement) {
  8011. if (path.length < MAX_PATH_DEPTH) {
  8012. const propertyKey = this.getPropertyKey();
  8013. this.object.deoptimizePath([
  8014. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  8015. ...path
  8016. ]);
  8017. }
  8018. }
  8019. }
  8020. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8021. if (this.variable) {
  8022. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8023. }
  8024. else if (!this.replacement) {
  8025. if (path.length < MAX_PATH_DEPTH) {
  8026. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  8027. }
  8028. else {
  8029. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8030. }
  8031. }
  8032. }
  8033. getLiteralValueAtPath(path, recursionTracker, origin) {
  8034. if (this.variable) {
  8035. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8036. }
  8037. if (this.replacement) {
  8038. return UnknownValue;
  8039. }
  8040. this.expressionsToBeDeoptimized.push(origin);
  8041. if (path.length < MAX_PATH_DEPTH) {
  8042. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  8043. }
  8044. return UnknownValue;
  8045. }
  8046. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8047. if (this.variable) {
  8048. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8049. }
  8050. if (this.replacement) {
  8051. return UNKNOWN_EXPRESSION;
  8052. }
  8053. this.expressionsToBeDeoptimized.push(origin);
  8054. if (path.length < MAX_PATH_DEPTH) {
  8055. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  8056. }
  8057. return UNKNOWN_EXPRESSION;
  8058. }
  8059. hasEffects(context) {
  8060. if (!this.deoptimized)
  8061. this.applyDeoptimizations();
  8062. return (this.property.hasEffects(context) ||
  8063. this.object.hasEffects(context) ||
  8064. this.hasAccessEffect(context));
  8065. }
  8066. hasEffectsAsAssignmentTarget(context, checkAccess) {
  8067. if (checkAccess && !this.deoptimized)
  8068. this.applyDeoptimizations();
  8069. if (!this.assignmentDeoptimized)
  8070. this.applyAssignmentDeoptimization();
  8071. return (this.property.hasEffects(context) ||
  8072. this.object.hasEffects(context) ||
  8073. (checkAccess && this.hasAccessEffect(context)) ||
  8074. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  8075. }
  8076. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8077. if (this.variable) {
  8078. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  8079. }
  8080. if (this.replacement) {
  8081. return true;
  8082. }
  8083. if (path.length < MAX_PATH_DEPTH) {
  8084. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  8085. }
  8086. return true;
  8087. }
  8088. include(context, includeChildrenRecursively) {
  8089. if (!this.deoptimized)
  8090. this.applyDeoptimizations();
  8091. this.includeProperties(context, includeChildrenRecursively);
  8092. }
  8093. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  8094. if (!this.assignmentDeoptimized)
  8095. this.applyAssignmentDeoptimization();
  8096. if (deoptimizeAccess) {
  8097. this.include(context, includeChildrenRecursively);
  8098. }
  8099. else {
  8100. this.includeProperties(context, includeChildrenRecursively);
  8101. }
  8102. }
  8103. includeCallArguments(context, args) {
  8104. if (this.variable) {
  8105. this.variable.includeCallArguments(context, args);
  8106. }
  8107. else {
  8108. super.includeCallArguments(context, args);
  8109. }
  8110. }
  8111. initialise() {
  8112. this.propertyKey = getResolvablePropertyKey(this);
  8113. this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
  8114. }
  8115. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  8116. if (this.variable || this.replacement) {
  8117. const { snippets: { getPropertyAccess } } = options;
  8118. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
  8119. if (renderedParentType && isCalleeOfRenderedParent)
  8120. replacement = '0, ' + replacement;
  8121. code.overwrite(this.start, this.end, replacement, {
  8122. contentOnly: true,
  8123. storeName: true
  8124. });
  8125. }
  8126. else {
  8127. if (renderedParentType && isCalleeOfRenderedParent) {
  8128. code.appendRight(this.start, '0, ');
  8129. }
  8130. this.object.render(code, options, { renderedSurroundingElement });
  8131. this.property.render(code, options);
  8132. }
  8133. }
  8134. setAssignedValue(value) {
  8135. this.assignmentInteraction = {
  8136. args: [value],
  8137. thisArg: this.object,
  8138. type: INTERACTION_ASSIGNED
  8139. };
  8140. }
  8141. applyDeoptimizations() {
  8142. this.deoptimized = true;
  8143. const { propertyReadSideEffects } = this.context.options
  8144. .treeshake;
  8145. if (
  8146. // Namespaces are not bound and should not be deoptimized
  8147. this.bound &&
  8148. propertyReadSideEffects &&
  8149. !(this.variable || this.replacement)) {
  8150. const propertyKey = this.getPropertyKey();
  8151. this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8152. this.context.requestTreeshakingPass();
  8153. }
  8154. }
  8155. applyAssignmentDeoptimization() {
  8156. this.assignmentDeoptimized = true;
  8157. const { propertyReadSideEffects } = this.context.options
  8158. .treeshake;
  8159. if (
  8160. // Namespaces are not bound and should not be deoptimized
  8161. this.bound &&
  8162. propertyReadSideEffects &&
  8163. !(this.variable || this.replacement)) {
  8164. this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8165. this.context.requestTreeshakingPass();
  8166. }
  8167. }
  8168. disallowNamespaceReassignment() {
  8169. if (this.object instanceof Identifier) {
  8170. const variable = this.scope.findVariable(this.object.name);
  8171. if (variable.isNamespace) {
  8172. if (this.variable) {
  8173. this.context.includeVariableInModule(this.variable);
  8174. }
  8175. this.context.warn({
  8176. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  8177. message: `Illegal reassignment to import '${this.object.name}'`
  8178. }, this.start);
  8179. }
  8180. }
  8181. }
  8182. getPropertyKey() {
  8183. if (this.propertyKey === null) {
  8184. this.propertyKey = UnknownKey;
  8185. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8186. return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
  8187. }
  8188. return this.propertyKey;
  8189. }
  8190. hasAccessEffect(context) {
  8191. const { propertyReadSideEffects } = this.context.options
  8192. .treeshake;
  8193. return (!(this.variable || this.replacement) &&
  8194. propertyReadSideEffects &&
  8195. (propertyReadSideEffects === 'always' ||
  8196. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8197. }
  8198. includeProperties(context, includeChildrenRecursively) {
  8199. if (!this.included) {
  8200. this.included = true;
  8201. if (this.variable) {
  8202. this.context.includeVariableInModule(this.variable);
  8203. }
  8204. }
  8205. this.object.include(context, includeChildrenRecursively);
  8206. this.property.include(context, includeChildrenRecursively);
  8207. }
  8208. }
  8209. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8210. if (path.length === 0)
  8211. return baseVariable;
  8212. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8213. return null;
  8214. const exportName = path[0].key;
  8215. const variable = baseVariable.context.traceExport(exportName);
  8216. if (!variable) {
  8217. const fileName = baseVariable.context.fileName;
  8218. astContext.warn({
  8219. code: 'MISSING_EXPORT',
  8220. exporter: relativeId(fileName),
  8221. importer: relativeId(astContext.fileName),
  8222. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  8223. missing: exportName,
  8224. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  8225. }, path[0].pos);
  8226. return 'undefined';
  8227. }
  8228. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8229. }
  8230. class CallExpressionBase extends NodeBase {
  8231. constructor() {
  8232. super(...arguments);
  8233. this.returnExpression = null;
  8234. this.deoptimizableDependentExpressions = [];
  8235. this.expressionsToBeDeoptimized = new Set();
  8236. }
  8237. deoptimizeCache() {
  8238. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  8239. this.returnExpression = UNKNOWN_EXPRESSION;
  8240. for (const expression of this.deoptimizableDependentExpressions) {
  8241. expression.deoptimizeCache();
  8242. }
  8243. for (const expression of this.expressionsToBeDeoptimized) {
  8244. expression.deoptimizePath(UNKNOWN_PATH);
  8245. }
  8246. }
  8247. }
  8248. deoptimizePath(path) {
  8249. if (path.length === 0 ||
  8250. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8251. return;
  8252. }
  8253. const returnExpression = this.getReturnExpression();
  8254. if (returnExpression !== UNKNOWN_EXPRESSION) {
  8255. returnExpression.deoptimizePath(path);
  8256. }
  8257. }
  8258. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8259. const returnExpression = this.getReturnExpression(recursionTracker);
  8260. if (returnExpression === UNKNOWN_EXPRESSION) {
  8261. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8262. }
  8263. else {
  8264. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8265. this.expressionsToBeDeoptimized.add(interaction.thisArg);
  8266. returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8267. }, undefined);
  8268. }
  8269. }
  8270. getLiteralValueAtPath(path, recursionTracker, origin) {
  8271. const returnExpression = this.getReturnExpression(recursionTracker);
  8272. if (returnExpression === UNKNOWN_EXPRESSION) {
  8273. return UnknownValue;
  8274. }
  8275. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8276. this.deoptimizableDependentExpressions.push(origin);
  8277. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  8278. }, UnknownValue);
  8279. }
  8280. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8281. const returnExpression = this.getReturnExpression(recursionTracker);
  8282. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  8283. return UNKNOWN_EXPRESSION;
  8284. }
  8285. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8286. this.deoptimizableDependentExpressions.push(origin);
  8287. return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8288. }, UNKNOWN_EXPRESSION);
  8289. }
  8290. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8291. const { type } = interaction;
  8292. if (type === INTERACTION_CALLED) {
  8293. if ((interaction.withNew
  8294. ? context.instantiated
  8295. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
  8296. return false;
  8297. }
  8298. }
  8299. else if ((type === INTERACTION_ASSIGNED
  8300. ? context.assigned
  8301. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  8302. return false;
  8303. }
  8304. return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
  8305. }
  8306. }
  8307. class CallExpression extends CallExpressionBase {
  8308. bind() {
  8309. super.bind();
  8310. if (this.callee instanceof Identifier) {
  8311. const variable = this.scope.findVariable(this.callee.name);
  8312. if (variable.isNamespace) {
  8313. this.context.warn({
  8314. code: 'CANNOT_CALL_NAMESPACE',
  8315. message: `Cannot call a namespace ('${this.callee.name}')`
  8316. }, this.start);
  8317. }
  8318. if (this.callee.name === 'eval') {
  8319. this.context.warn({
  8320. code: 'EVAL',
  8321. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8322. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  8323. }, this.start);
  8324. }
  8325. }
  8326. this.interaction = {
  8327. args: this.arguments,
  8328. thisArg: this.callee instanceof MemberExpression && !this.callee.variable
  8329. ? this.callee.object
  8330. : null,
  8331. type: INTERACTION_CALLED,
  8332. withNew: false
  8333. };
  8334. }
  8335. hasEffects(context) {
  8336. try {
  8337. for (const argument of this.arguments) {
  8338. if (argument.hasEffects(context))
  8339. return true;
  8340. }
  8341. if (this.context.options.treeshake.annotations &&
  8342. this.annotations)
  8343. return false;
  8344. return (this.callee.hasEffects(context) ||
  8345. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  8346. }
  8347. finally {
  8348. if (!this.deoptimized)
  8349. this.applyDeoptimizations();
  8350. }
  8351. }
  8352. include(context, includeChildrenRecursively) {
  8353. if (!this.deoptimized)
  8354. this.applyDeoptimizations();
  8355. if (includeChildrenRecursively) {
  8356. super.include(context, includeChildrenRecursively);
  8357. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  8358. this.callee instanceof Identifier &&
  8359. this.callee.variable) {
  8360. this.callee.variable.markCalledFromTryStatement();
  8361. }
  8362. }
  8363. else {
  8364. this.included = true;
  8365. this.callee.include(context, false);
  8366. }
  8367. this.callee.includeCallArguments(context, this.arguments);
  8368. }
  8369. render(code, options, { renderedSurroundingElement } = BLANK) {
  8370. this.callee.render(code, options, {
  8371. isCalleeOfRenderedParent: true,
  8372. renderedSurroundingElement
  8373. });
  8374. renderCallArguments(code, options, this);
  8375. }
  8376. applyDeoptimizations() {
  8377. this.deoptimized = true;
  8378. if (this.interaction.thisArg) {
  8379. this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  8380. }
  8381. for (const argument of this.arguments) {
  8382. // This will make sure all properties of parameters behave as "unknown"
  8383. argument.deoptimizePath(UNKNOWN_PATH);
  8384. }
  8385. this.context.requestTreeshakingPass();
  8386. }
  8387. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  8388. if (this.returnExpression === null) {
  8389. this.returnExpression = UNKNOWN_EXPRESSION;
  8390. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  8391. }
  8392. return this.returnExpression;
  8393. }
  8394. }
  8395. class CatchScope extends ParameterScope {
  8396. addDeclaration(identifier, context, init, isHoisted) {
  8397. const existingParameter = this.variables.get(identifier.name);
  8398. if (existingParameter) {
  8399. // While we still create a hoisted declaration, the initializer goes to
  8400. // the parameter. Note that technically, the declaration now belongs to
  8401. // two variables, which is not correct but should not cause issues.
  8402. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  8403. existingParameter.addDeclaration(identifier, init);
  8404. return existingParameter;
  8405. }
  8406. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  8407. }
  8408. }
  8409. class CatchClause extends NodeBase {
  8410. createScope(parentScope) {
  8411. this.scope = new CatchScope(parentScope, this.context);
  8412. }
  8413. parseNode(esTreeNode) {
  8414. // Parameters need to be declared first as the logic is that initializers
  8415. // of hoisted body variables are associated with parameters of the same
  8416. // name instead of the variable
  8417. const { param } = esTreeNode;
  8418. if (param) {
  8419. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  8420. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  8421. }
  8422. super.parseNode(esTreeNode);
  8423. }
  8424. }
  8425. class ChainExpression extends NodeBase {
  8426. }
  8427. class ClassBodyScope extends ChildScope {
  8428. constructor(parent, classNode, context) {
  8429. super(parent);
  8430. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  8431. this.instanceScope = new ChildScope(this);
  8432. this.instanceScope.variables.set('this', new ThisVariable(context));
  8433. }
  8434. findLexicalBoundary() {
  8435. return this;
  8436. }
  8437. }
  8438. class ClassBody extends NodeBase {
  8439. createScope(parentScope) {
  8440. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  8441. }
  8442. include(context, includeChildrenRecursively) {
  8443. this.included = true;
  8444. this.context.includeVariableInModule(this.scope.thisVariable);
  8445. for (const definition of this.body) {
  8446. definition.include(context, includeChildrenRecursively);
  8447. }
  8448. }
  8449. parseNode(esTreeNode) {
  8450. const body = (this.body = []);
  8451. for (const definition of esTreeNode.body) {
  8452. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  8453. }
  8454. super.parseNode(esTreeNode);
  8455. }
  8456. applyDeoptimizations() { }
  8457. }
  8458. class MethodBase extends NodeBase {
  8459. constructor() {
  8460. super(...arguments);
  8461. this.accessedValue = null;
  8462. }
  8463. // As getter properties directly receive their values from fixed function
  8464. // expressions, there is no known situation where a getter is deoptimized.
  8465. deoptimizeCache() { }
  8466. deoptimizePath(path) {
  8467. this.getAccessedValue().deoptimizePath(path);
  8468. }
  8469. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8470. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8471. return this.value.deoptimizeThisOnInteractionAtPath({
  8472. args: NO_ARGS,
  8473. thisArg: interaction.thisArg,
  8474. type: INTERACTION_CALLED,
  8475. withNew: false
  8476. }, EMPTY_PATH, recursionTracker);
  8477. }
  8478. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8479. return this.value.deoptimizeThisOnInteractionAtPath({
  8480. args: interaction.args,
  8481. thisArg: interaction.thisArg,
  8482. type: INTERACTION_CALLED,
  8483. withNew: false
  8484. }, EMPTY_PATH, recursionTracker);
  8485. }
  8486. this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8487. }
  8488. getLiteralValueAtPath(path, recursionTracker, origin) {
  8489. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  8490. }
  8491. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8492. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8493. }
  8494. hasEffects(context) {
  8495. return this.key.hasEffects(context);
  8496. }
  8497. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8498. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8499. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8500. args: NO_ARGS,
  8501. thisArg: interaction.thisArg,
  8502. type: INTERACTION_CALLED,
  8503. withNew: false
  8504. }, context);
  8505. }
  8506. // setters are only called for empty paths
  8507. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8508. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8509. args: interaction.args,
  8510. thisArg: interaction.thisArg,
  8511. type: INTERACTION_CALLED,
  8512. withNew: false
  8513. }, context);
  8514. }
  8515. return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
  8516. }
  8517. applyDeoptimizations() { }
  8518. getAccessedValue() {
  8519. if (this.accessedValue === null) {
  8520. if (this.kind === 'get') {
  8521. this.accessedValue = UNKNOWN_EXPRESSION;
  8522. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8523. }
  8524. else {
  8525. return (this.accessedValue = this.value);
  8526. }
  8527. }
  8528. return this.accessedValue;
  8529. }
  8530. }
  8531. class MethodDefinition extends MethodBase {
  8532. applyDeoptimizations() { }
  8533. }
  8534. class ObjectMember extends ExpressionEntity {
  8535. constructor(object, key) {
  8536. super();
  8537. this.object = object;
  8538. this.key = key;
  8539. }
  8540. deoptimizePath(path) {
  8541. this.object.deoptimizePath([this.key, ...path]);
  8542. }
  8543. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8544. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  8545. }
  8546. getLiteralValueAtPath(path, recursionTracker, origin) {
  8547. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  8548. }
  8549. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8550. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  8551. }
  8552. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8553. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  8554. }
  8555. }
  8556. class ClassNode extends NodeBase {
  8557. constructor() {
  8558. super(...arguments);
  8559. this.objectEntity = null;
  8560. }
  8561. createScope(parentScope) {
  8562. this.scope = new ChildScope(parentScope);
  8563. }
  8564. deoptimizeCache() {
  8565. this.getObjectEntity().deoptimizeAllProperties();
  8566. }
  8567. deoptimizePath(path) {
  8568. this.getObjectEntity().deoptimizePath(path);
  8569. }
  8570. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8571. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8572. }
  8573. getLiteralValueAtPath(path, recursionTracker, origin) {
  8574. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8575. }
  8576. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8577. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8578. }
  8579. hasEffects(context) {
  8580. var _a, _b;
  8581. if (!this.deoptimized)
  8582. this.applyDeoptimizations();
  8583. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  8584. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  8585. return initEffect || super.hasEffects(context);
  8586. }
  8587. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8588. var _a;
  8589. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  8590. return (!interaction.withNew ||
  8591. (this.classConstructor !== null
  8592. ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
  8593. : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8594. false);
  8595. }
  8596. else {
  8597. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8598. }
  8599. }
  8600. include(context, includeChildrenRecursively) {
  8601. var _a;
  8602. if (!this.deoptimized)
  8603. this.applyDeoptimizations();
  8604. this.included = true;
  8605. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  8606. this.body.include(context, includeChildrenRecursively);
  8607. if (this.id) {
  8608. this.id.markDeclarationReached();
  8609. this.id.include();
  8610. }
  8611. }
  8612. initialise() {
  8613. var _a;
  8614. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  8615. for (const method of this.body.body) {
  8616. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8617. this.classConstructor = method;
  8618. return;
  8619. }
  8620. }
  8621. this.classConstructor = null;
  8622. }
  8623. applyDeoptimizations() {
  8624. this.deoptimized = true;
  8625. for (const definition of this.body.body) {
  8626. if (!(definition.static ||
  8627. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8628. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8629. definition.deoptimizePath(UNKNOWN_PATH);
  8630. }
  8631. }
  8632. this.context.requestTreeshakingPass();
  8633. }
  8634. getObjectEntity() {
  8635. if (this.objectEntity !== null) {
  8636. return this.objectEntity;
  8637. }
  8638. const staticProperties = [];
  8639. const dynamicMethods = [];
  8640. for (const definition of this.body.body) {
  8641. const properties = definition.static ? staticProperties : dynamicMethods;
  8642. const definitionKind = definition.kind;
  8643. // Note that class fields do not end up on the prototype
  8644. if (properties === dynamicMethods && !definitionKind)
  8645. continue;
  8646. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8647. let key;
  8648. if (definition.computed) {
  8649. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8650. if (typeof keyValue === 'symbol') {
  8651. properties.push({ key: UnknownKey, kind, property: definition });
  8652. continue;
  8653. }
  8654. else {
  8655. key = String(keyValue);
  8656. }
  8657. }
  8658. else {
  8659. key =
  8660. definition.key instanceof Identifier
  8661. ? definition.key.name
  8662. : String(definition.key.value);
  8663. }
  8664. properties.push({ key, kind, property: definition });
  8665. }
  8666. staticProperties.unshift({
  8667. key: 'prototype',
  8668. kind: 'init',
  8669. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  8670. });
  8671. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8672. }
  8673. }
  8674. class ClassDeclaration extends ClassNode {
  8675. initialise() {
  8676. super.initialise();
  8677. if (this.id !== null) {
  8678. this.id.variable.isId = true;
  8679. }
  8680. }
  8681. parseNode(esTreeNode) {
  8682. if (esTreeNode.id !== null) {
  8683. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8684. }
  8685. super.parseNode(esTreeNode);
  8686. }
  8687. render(code, options) {
  8688. const { exportNamesByVariable, format, snippets: { _ } } = options;
  8689. if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
  8690. code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
  8691. }
  8692. super.render(code, options);
  8693. }
  8694. }
  8695. class ClassExpression extends ClassNode {
  8696. render(code, options, { renderedSurroundingElement } = BLANK) {
  8697. super.render(code, options);
  8698. if (renderedSurroundingElement === ExpressionStatement$1) {
  8699. code.appendRight(this.start, '(');
  8700. code.prependLeft(this.end, ')');
  8701. }
  8702. }
  8703. }
  8704. class MultiExpression extends ExpressionEntity {
  8705. constructor(expressions) {
  8706. super();
  8707. this.expressions = expressions;
  8708. this.included = false;
  8709. }
  8710. deoptimizePath(path) {
  8711. for (const expression of this.expressions) {
  8712. expression.deoptimizePath(path);
  8713. }
  8714. }
  8715. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8716. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
  8717. }
  8718. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8719. for (const expression of this.expressions) {
  8720. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  8721. return true;
  8722. }
  8723. return false;
  8724. }
  8725. }
  8726. class ConditionalExpression extends NodeBase {
  8727. constructor() {
  8728. super(...arguments);
  8729. this.expressionsToBeDeoptimized = [];
  8730. this.isBranchResolutionAnalysed = false;
  8731. this.usedBranch = null;
  8732. }
  8733. deoptimizeCache() {
  8734. if (this.usedBranch !== null) {
  8735. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  8736. this.usedBranch = null;
  8737. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  8738. for (const expression of this.expressionsToBeDeoptimized) {
  8739. expression.deoptimizeCache();
  8740. }
  8741. }
  8742. }
  8743. deoptimizePath(path) {
  8744. const usedBranch = this.getUsedBranch();
  8745. if (!usedBranch) {
  8746. this.consequent.deoptimizePath(path);
  8747. this.alternate.deoptimizePath(path);
  8748. }
  8749. else {
  8750. usedBranch.deoptimizePath(path);
  8751. }
  8752. }
  8753. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8754. this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8755. this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8756. }
  8757. getLiteralValueAtPath(path, recursionTracker, origin) {
  8758. const usedBranch = this.getUsedBranch();
  8759. if (!usedBranch)
  8760. return UnknownValue;
  8761. this.expressionsToBeDeoptimized.push(origin);
  8762. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  8763. }
  8764. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8765. const usedBranch = this.getUsedBranch();
  8766. if (!usedBranch)
  8767. return new MultiExpression([
  8768. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  8769. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  8770. ]);
  8771. this.expressionsToBeDeoptimized.push(origin);
  8772. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8773. }
  8774. hasEffects(context) {
  8775. if (this.test.hasEffects(context))
  8776. return true;
  8777. const usedBranch = this.getUsedBranch();
  8778. if (!usedBranch) {
  8779. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  8780. }
  8781. return usedBranch.hasEffects(context);
  8782. }
  8783. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8784. const usedBranch = this.getUsedBranch();
  8785. if (!usedBranch) {
  8786. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8787. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  8788. }
  8789. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  8790. }
  8791. include(context, includeChildrenRecursively) {
  8792. this.included = true;
  8793. const usedBranch = this.getUsedBranch();
  8794. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  8795. this.test.include(context, includeChildrenRecursively);
  8796. this.consequent.include(context, includeChildrenRecursively);
  8797. this.alternate.include(context, includeChildrenRecursively);
  8798. }
  8799. else {
  8800. usedBranch.include(context, includeChildrenRecursively);
  8801. }
  8802. }
  8803. includeCallArguments(context, args) {
  8804. const usedBranch = this.getUsedBranch();
  8805. if (!usedBranch) {
  8806. this.consequent.includeCallArguments(context, args);
  8807. this.alternate.includeCallArguments(context, args);
  8808. }
  8809. else {
  8810. usedBranch.includeCallArguments(context, args);
  8811. }
  8812. }
  8813. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8814. const usedBranch = this.getUsedBranch();
  8815. if (!this.test.included) {
  8816. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  8817. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  8818. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  8819. : colonPos) + 1);
  8820. if (preventASI) {
  8821. removeLineBreaks(code, inclusionStart, usedBranch.start);
  8822. }
  8823. code.remove(this.start, inclusionStart);
  8824. if (this.consequent.included) {
  8825. code.remove(colonPos, this.end);
  8826. }
  8827. removeAnnotations(this, code);
  8828. usedBranch.render(code, options, {
  8829. isCalleeOfRenderedParent,
  8830. preventASI: true,
  8831. renderedParentType: renderedParentType || this.parent.type,
  8832. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8833. });
  8834. }
  8835. else {
  8836. this.test.render(code, options, { renderedSurroundingElement });
  8837. this.consequent.render(code, options);
  8838. this.alternate.render(code, options);
  8839. }
  8840. }
  8841. getUsedBranch() {
  8842. if (this.isBranchResolutionAnalysed) {
  8843. return this.usedBranch;
  8844. }
  8845. this.isBranchResolutionAnalysed = true;
  8846. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8847. return typeof testValue === 'symbol'
  8848. ? null
  8849. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  8850. }
  8851. }
  8852. class ContinueStatement extends NodeBase {
  8853. hasEffects(context) {
  8854. if (this.label) {
  8855. if (!context.ignore.labels.has(this.label.name))
  8856. return true;
  8857. context.includedLabels.add(this.label.name);
  8858. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8859. }
  8860. else {
  8861. if (!context.ignore.continues)
  8862. return true;
  8863. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  8864. }
  8865. return false;
  8866. }
  8867. include(context) {
  8868. this.included = true;
  8869. if (this.label) {
  8870. this.label.include();
  8871. context.includedLabels.add(this.label.name);
  8872. }
  8873. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  8874. }
  8875. }
  8876. class DoWhileStatement extends NodeBase {
  8877. hasEffects(context) {
  8878. if (this.test.hasEffects(context))
  8879. return true;
  8880. const { brokenFlow, ignore: { breaks, continues } } = context;
  8881. context.ignore.breaks = true;
  8882. context.ignore.continues = true;
  8883. if (this.body.hasEffects(context))
  8884. return true;
  8885. context.ignore.breaks = breaks;
  8886. context.ignore.continues = continues;
  8887. context.brokenFlow = brokenFlow;
  8888. return false;
  8889. }
  8890. include(context, includeChildrenRecursively) {
  8891. this.included = true;
  8892. this.test.include(context, includeChildrenRecursively);
  8893. const { brokenFlow } = context;
  8894. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8895. context.brokenFlow = brokenFlow;
  8896. }
  8897. }
  8898. class EmptyStatement extends NodeBase {
  8899. hasEffects() {
  8900. return false;
  8901. }
  8902. }
  8903. class ExportAllDeclaration extends NodeBase {
  8904. hasEffects() {
  8905. return false;
  8906. }
  8907. initialise() {
  8908. this.context.addExport(this);
  8909. }
  8910. render(code, _options, nodeRenderOptions) {
  8911. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  8912. }
  8913. applyDeoptimizations() { }
  8914. }
  8915. ExportAllDeclaration.prototype.needsBoundaries = true;
  8916. class FunctionDeclaration extends FunctionNode {
  8917. initialise() {
  8918. super.initialise();
  8919. if (this.id !== null) {
  8920. this.id.variable.isId = true;
  8921. }
  8922. }
  8923. parseNode(esTreeNode) {
  8924. if (esTreeNode.id !== null) {
  8925. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8926. }
  8927. super.parseNode(esTreeNode);
  8928. }
  8929. }
  8930. // The header ends at the first non-white-space after "default"
  8931. function getDeclarationStart(code, start) {
  8932. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  8933. }
  8934. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  8935. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  8936. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  8937. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  8938. if (generatorStarPos === -1) {
  8939. return declarationEnd;
  8940. }
  8941. return declarationEnd + generatorStarPos + 1;
  8942. }
  8943. class ExportDefaultDeclaration extends NodeBase {
  8944. include(context, includeChildrenRecursively) {
  8945. super.include(context, includeChildrenRecursively);
  8946. if (includeChildrenRecursively) {
  8947. this.context.includeVariableInModule(this.variable);
  8948. }
  8949. }
  8950. initialise() {
  8951. const declaration = this.declaration;
  8952. this.declarationName =
  8953. (declaration.id && declaration.id.name) || this.declaration.name;
  8954. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  8955. this.context.addExport(this);
  8956. }
  8957. render(code, options, nodeRenderOptions) {
  8958. const { start, end } = nodeRenderOptions;
  8959. const declarationStart = getDeclarationStart(code.original, this.start);
  8960. if (this.declaration instanceof FunctionDeclaration) {
  8961. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  8962. }
  8963. else if (this.declaration instanceof ClassDeclaration) {
  8964. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  8965. }
  8966. else if (this.variable.getOriginalVariable() !== this.variable) {
  8967. // Remove altogether to prevent re-declaring the same variable
  8968. treeshakeNode(this, code, start, end);
  8969. return;
  8970. }
  8971. else if (this.variable.included) {
  8972. this.renderVariableDeclaration(code, declarationStart, options);
  8973. }
  8974. else {
  8975. code.remove(this.start, declarationStart);
  8976. this.declaration.render(code, options, {
  8977. renderedSurroundingElement: ExpressionStatement$1
  8978. });
  8979. if (code.original[this.end - 1] !== ';') {
  8980. code.appendLeft(this.end, ';');
  8981. }
  8982. return;
  8983. }
  8984. this.declaration.render(code, options);
  8985. }
  8986. applyDeoptimizations() { }
  8987. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  8988. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  8989. const name = this.variable.getName(getPropertyAccess);
  8990. // Remove `export default`
  8991. code.remove(this.start, declarationStart);
  8992. if (needsId) {
  8993. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  8994. }
  8995. if (format === 'system' &&
  8996. this.declaration instanceof ClassDeclaration &&
  8997. exportNamesByVariable.has(this.variable)) {
  8998. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  8999. }
  9000. }
  9001. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  9002. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  9003. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  9004. if (systemExportNames) {
  9005. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  9006. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  9007. }
  9008. else {
  9009. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  9010. if (!hasTrailingSemicolon) {
  9011. code.appendLeft(this.end, ';');
  9012. }
  9013. }
  9014. }
  9015. }
  9016. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9017. class ExportNamedDeclaration extends NodeBase {
  9018. bind() {
  9019. var _a;
  9020. // Do not bind specifiers
  9021. (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
  9022. }
  9023. hasEffects(context) {
  9024. var _a;
  9025. return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9026. }
  9027. initialise() {
  9028. this.context.addExport(this);
  9029. }
  9030. render(code, options, nodeRenderOptions) {
  9031. const { start, end } = nodeRenderOptions;
  9032. if (this.declaration === null) {
  9033. code.remove(start, end);
  9034. }
  9035. else {
  9036. code.remove(this.start, this.declaration.start);
  9037. this.declaration.render(code, options, { end, start });
  9038. }
  9039. }
  9040. applyDeoptimizations() { }
  9041. }
  9042. ExportNamedDeclaration.prototype.needsBoundaries = true;
  9043. class ExportSpecifier extends NodeBase {
  9044. applyDeoptimizations() { }
  9045. }
  9046. class ForInStatement extends NodeBase {
  9047. createScope(parentScope) {
  9048. this.scope = new BlockScope(parentScope);
  9049. }
  9050. hasEffects(context) {
  9051. const { deoptimized, left, right } = this;
  9052. if (!deoptimized)
  9053. this.applyDeoptimizations();
  9054. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  9055. return true;
  9056. const { brokenFlow, ignore: { breaks, continues } } = context;
  9057. context.ignore.breaks = true;
  9058. context.ignore.continues = true;
  9059. if (this.body.hasEffects(context))
  9060. return true;
  9061. context.ignore.breaks = breaks;
  9062. context.ignore.continues = continues;
  9063. context.brokenFlow = brokenFlow;
  9064. return false;
  9065. }
  9066. include(context, includeChildrenRecursively) {
  9067. const { body, deoptimized, left, right } = this;
  9068. if (!deoptimized)
  9069. this.applyDeoptimizations();
  9070. this.included = true;
  9071. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9072. right.include(context, includeChildrenRecursively);
  9073. const { brokenFlow } = context;
  9074. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9075. context.brokenFlow = brokenFlow;
  9076. }
  9077. initialise() {
  9078. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9079. }
  9080. render(code, options) {
  9081. this.left.render(code, options, NO_SEMICOLON);
  9082. this.right.render(code, options, NO_SEMICOLON);
  9083. // handle no space between "in" and the right side
  9084. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  9085. code.prependLeft(this.right.start, ' ');
  9086. }
  9087. this.body.render(code, options);
  9088. }
  9089. applyDeoptimizations() {
  9090. this.deoptimized = true;
  9091. this.left.deoptimizePath(EMPTY_PATH);
  9092. this.context.requestTreeshakingPass();
  9093. }
  9094. }
  9095. class ForOfStatement extends NodeBase {
  9096. createScope(parentScope) {
  9097. this.scope = new BlockScope(parentScope);
  9098. }
  9099. hasEffects() {
  9100. if (!this.deoptimized)
  9101. this.applyDeoptimizations();
  9102. // Placeholder until proper Symbol.Iterator support
  9103. return true;
  9104. }
  9105. include(context, includeChildrenRecursively) {
  9106. const { body, deoptimized, left, right } = this;
  9107. if (!deoptimized)
  9108. this.applyDeoptimizations();
  9109. this.included = true;
  9110. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9111. right.include(context, includeChildrenRecursively);
  9112. const { brokenFlow } = context;
  9113. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9114. context.brokenFlow = brokenFlow;
  9115. }
  9116. initialise() {
  9117. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9118. }
  9119. render(code, options) {
  9120. this.left.render(code, options, NO_SEMICOLON);
  9121. this.right.render(code, options, NO_SEMICOLON);
  9122. // handle no space between "of" and the right side
  9123. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  9124. code.prependLeft(this.right.start, ' ');
  9125. }
  9126. this.body.render(code, options);
  9127. }
  9128. applyDeoptimizations() {
  9129. this.deoptimized = true;
  9130. this.left.deoptimizePath(EMPTY_PATH);
  9131. this.context.requestTreeshakingPass();
  9132. }
  9133. }
  9134. class ForStatement extends NodeBase {
  9135. createScope(parentScope) {
  9136. this.scope = new BlockScope(parentScope);
  9137. }
  9138. hasEffects(context) {
  9139. var _a, _b, _c;
  9140. if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
  9141. ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
  9142. ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
  9143. return true;
  9144. const { brokenFlow, ignore: { breaks, continues } } = context;
  9145. context.ignore.breaks = true;
  9146. context.ignore.continues = true;
  9147. if (this.body.hasEffects(context))
  9148. return true;
  9149. context.ignore.breaks = breaks;
  9150. context.ignore.continues = continues;
  9151. context.brokenFlow = brokenFlow;
  9152. return false;
  9153. }
  9154. include(context, includeChildrenRecursively) {
  9155. var _a, _b, _c;
  9156. this.included = true;
  9157. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9158. (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  9159. const { brokenFlow } = context;
  9160. (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
  9161. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9162. context.brokenFlow = brokenFlow;
  9163. }
  9164. render(code, options) {
  9165. var _a, _b, _c;
  9166. (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
  9167. (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
  9168. (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
  9169. this.body.render(code, options);
  9170. }
  9171. }
  9172. class FunctionExpression extends FunctionNode {
  9173. render(code, options, { renderedSurroundingElement } = BLANK) {
  9174. super.render(code, options);
  9175. if (renderedSurroundingElement === ExpressionStatement$1) {
  9176. code.appendRight(this.start, '(');
  9177. code.prependLeft(this.end, ')');
  9178. }
  9179. }
  9180. }
  9181. class TrackingScope extends BlockScope {
  9182. constructor() {
  9183. super(...arguments);
  9184. this.hoistedDeclarations = [];
  9185. }
  9186. addDeclaration(identifier, context, init, isHoisted) {
  9187. this.hoistedDeclarations.push(identifier);
  9188. return super.addDeclaration(identifier, context, init, isHoisted);
  9189. }
  9190. }
  9191. const unset = Symbol('unset');
  9192. class IfStatement extends NodeBase {
  9193. constructor() {
  9194. super(...arguments);
  9195. this.testValue = unset;
  9196. }
  9197. deoptimizeCache() {
  9198. this.testValue = UnknownValue;
  9199. }
  9200. hasEffects(context) {
  9201. var _a;
  9202. if (this.test.hasEffects(context)) {
  9203. return true;
  9204. }
  9205. const testValue = this.getTestValue();
  9206. if (typeof testValue === 'symbol') {
  9207. const { brokenFlow } = context;
  9208. if (this.consequent.hasEffects(context))
  9209. return true;
  9210. const consequentBrokenFlow = context.brokenFlow;
  9211. context.brokenFlow = brokenFlow;
  9212. if (this.alternate === null)
  9213. return false;
  9214. if (this.alternate.hasEffects(context))
  9215. return true;
  9216. context.brokenFlow =
  9217. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9218. return false;
  9219. }
  9220. return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9221. }
  9222. include(context, includeChildrenRecursively) {
  9223. this.included = true;
  9224. if (includeChildrenRecursively) {
  9225. this.includeRecursively(includeChildrenRecursively, context);
  9226. }
  9227. else {
  9228. const testValue = this.getTestValue();
  9229. if (typeof testValue === 'symbol') {
  9230. this.includeUnknownTest(context);
  9231. }
  9232. else {
  9233. this.includeKnownTest(context, testValue);
  9234. }
  9235. }
  9236. }
  9237. parseNode(esTreeNode) {
  9238. this.consequentScope = new TrackingScope(this.scope);
  9239. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  9240. if (esTreeNode.alternate) {
  9241. this.alternateScope = new TrackingScope(this.scope);
  9242. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  9243. }
  9244. super.parseNode(esTreeNode);
  9245. }
  9246. render(code, options) {
  9247. const { snippets: { getPropertyAccess } } = options;
  9248. // Note that unknown test values are always included
  9249. const testValue = this.getTestValue();
  9250. const hoistedDeclarations = [];
  9251. const includesIfElse = this.test.included;
  9252. const noTreeshake = !this.context.options.treeshake;
  9253. if (includesIfElse) {
  9254. this.test.render(code, options);
  9255. }
  9256. else {
  9257. code.remove(this.start, this.consequent.start);
  9258. }
  9259. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  9260. this.consequent.render(code, options);
  9261. }
  9262. else {
  9263. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  9264. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  9265. }
  9266. if (this.alternate) {
  9267. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  9268. if (includesIfElse) {
  9269. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  9270. code.prependLeft(this.alternate.start, ' ');
  9271. }
  9272. }
  9273. else {
  9274. code.remove(this.consequent.end, this.alternate.start);
  9275. }
  9276. this.alternate.render(code, options);
  9277. }
  9278. else {
  9279. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  9280. code.overwrite(this.alternate.start, this.end, ';');
  9281. }
  9282. else {
  9283. code.remove(this.consequent.end, this.end);
  9284. }
  9285. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  9286. }
  9287. }
  9288. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  9289. }
  9290. applyDeoptimizations() { }
  9291. getTestValue() {
  9292. if (this.testValue === unset) {
  9293. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  9294. }
  9295. return this.testValue;
  9296. }
  9297. includeKnownTest(context, testValue) {
  9298. var _a;
  9299. if (this.test.shouldBeIncluded(context)) {
  9300. this.test.include(context, false);
  9301. }
  9302. if (testValue && this.consequent.shouldBeIncluded(context)) {
  9303. this.consequent.include(context, false, { asSingleStatement: true });
  9304. }
  9305. if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
  9306. this.alternate.include(context, false, { asSingleStatement: true });
  9307. }
  9308. }
  9309. includeRecursively(includeChildrenRecursively, context) {
  9310. var _a;
  9311. this.test.include(context, includeChildrenRecursively);
  9312. this.consequent.include(context, includeChildrenRecursively);
  9313. (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  9314. }
  9315. includeUnknownTest(context) {
  9316. var _a;
  9317. this.test.include(context, false);
  9318. const { brokenFlow } = context;
  9319. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  9320. if (this.consequent.shouldBeIncluded(context)) {
  9321. this.consequent.include(context, false, { asSingleStatement: true });
  9322. consequentBrokenFlow = context.brokenFlow;
  9323. context.brokenFlow = brokenFlow;
  9324. }
  9325. if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
  9326. this.alternate.include(context, false, { asSingleStatement: true });
  9327. context.brokenFlow =
  9328. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9329. }
  9330. }
  9331. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  9332. const hoistedVars = [
  9333. ...new Set(hoistedDeclarations.map(identifier => {
  9334. const variable = identifier.variable;
  9335. return variable.included ? variable.getName(getPropertyAccess) : '';
  9336. }))
  9337. ]
  9338. .filter(Boolean)
  9339. .join(', ');
  9340. if (hoistedVars) {
  9341. const parentType = this.parent.type;
  9342. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  9343. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  9344. if (needsBraces) {
  9345. code.appendLeft(this.end, ` }`);
  9346. }
  9347. }
  9348. }
  9349. shouldKeepAlternateBranch() {
  9350. let currentParent = this.parent;
  9351. do {
  9352. if (currentParent instanceof IfStatement && currentParent.alternate) {
  9353. return true;
  9354. }
  9355. if (currentParent instanceof BlockStatement) {
  9356. return false;
  9357. }
  9358. currentParent = currentParent.parent;
  9359. } while (currentParent);
  9360. return false;
  9361. }
  9362. }
  9363. class ImportDeclaration extends NodeBase {
  9364. // Do not bind specifiers
  9365. bind() { }
  9366. hasEffects() {
  9367. return false;
  9368. }
  9369. initialise() {
  9370. this.context.addImport(this);
  9371. }
  9372. render(code, _options, nodeRenderOptions) {
  9373. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9374. }
  9375. applyDeoptimizations() { }
  9376. }
  9377. ImportDeclaration.prototype.needsBoundaries = true;
  9378. class ImportDefaultSpecifier extends NodeBase {
  9379. applyDeoptimizations() { }
  9380. }
  9381. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9382. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  9383. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9384. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9385. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9386. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9387. const defaultInteropHelpersByInteropType = {
  9388. auto: INTEROP_DEFAULT_VARIABLE,
  9389. default: null,
  9390. defaultOnly: null,
  9391. esModule: null,
  9392. false: null,
  9393. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  9394. };
  9395. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9396. (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
  9397. const namespaceInteropHelpersByInteropType = {
  9398. auto: INTEROP_NAMESPACE_VARIABLE,
  9399. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9400. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9401. esModule: null,
  9402. false: null,
  9403. true: INTEROP_NAMESPACE_VARIABLE
  9404. };
  9405. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
  9406. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
  9407. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9408. const usedHelpers = new Set(additionalHelpers);
  9409. for (const variable of HELPER_NAMES) {
  9410. if (accessedGlobals.has(variable)) {
  9411. usedHelpers.add(variable);
  9412. }
  9413. }
  9414. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9415. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  9416. : '').join('');
  9417. };
  9418. const HELPER_GENERATORS = {
  9419. [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
  9420. const { _, getDirectReturnFunction, n } = snippets;
  9421. const [left, right] = getDirectReturnFunction(['e'], {
  9422. functionReturn: true,
  9423. lineBreakIndent: null,
  9424. name: INTEROP_DEFAULT_LEGACY_VARIABLE
  9425. });
  9426. return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  9427. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9428. },
  9429. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9430. const { _, getDirectReturnFunction, n } = snippets;
  9431. const [left, right] = getDirectReturnFunction(['e'], {
  9432. functionReturn: true,
  9433. lineBreakIndent: null,
  9434. name: INTEROP_DEFAULT_VARIABLE
  9435. });
  9436. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9437. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9438. },
  9439. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  9440. const { getDirectReturnFunction, getObject, n } = snippets;
  9441. const [left, right] = getDirectReturnFunction(['e'], {
  9442. functionReturn: true,
  9443. lineBreakIndent: null,
  9444. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9445. });
  9446. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  9447. ['__proto__', 'null'],
  9448. ['default', 'e']
  9449. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  9450. },
  9451. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9452. const { _, n } = snippets;
  9453. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  9454. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9455. `}${n}${n}`);
  9456. },
  9457. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  9458. const { _, getDirectReturnFunction, n } = snippets;
  9459. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9460. const [left, right] = getDirectReturnFunction(['e'], {
  9461. functionReturn: true,
  9462. lineBreakIndent: null,
  9463. name: INTEROP_NAMESPACE_VARIABLE
  9464. });
  9465. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9466. }
  9467. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  9468. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  9469. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9470. `}${n}${n}`);
  9471. },
  9472. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9473. const { _, cnst, n } = snippets;
  9474. const useForEach = cnst === 'var' && liveBindings;
  9475. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  9476. `${t}${loopOverNamespaces(`{${n}` +
  9477. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  9478. (liveBindings
  9479. ? useForEach
  9480. ? copyOwnPropertyLiveBinding
  9481. : copyPropertyLiveBinding
  9482. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  9483. `${t}${t}${t}}${n}` +
  9484. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  9485. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  9486. `}${n}${n}`);
  9487. }
  9488. };
  9489. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  9490. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  9491. const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9492. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  9493. const copyProperty = `{${n}` +
  9494. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
  9495. `${i}${t}}`;
  9496. return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  9497. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  9498. : ''});${n}` +
  9499. `${i}if${_}(e)${_}{${n}` +
  9500. `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  9501. `${i}}${n}` +
  9502. `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  9503. `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
  9504. };
  9505. const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
  9506. ? `for${_}(${cnst} k in e)${_}${body}`
  9507. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9508. isAsync: false,
  9509. name: null
  9510. })}${body})${s}`;
  9511. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  9512. if (useForEach) {
  9513. const [left, right] = getDirectReturnFunction(['e'], {
  9514. functionReturn: false,
  9515. lineBreakIndent: { base: t, t },
  9516. name: null
  9517. });
  9518. return (`m.forEach(${left}` +
  9519. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9520. isAsync: false,
  9521. name: null
  9522. })}${body})${right});`);
  9523. }
  9524. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  9525. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  9526. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  9527. };
  9528. const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
  9529. const { _, n } = snippets;
  9530. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  9531. copyOwnPropertyLiveBinding(t, i + t, snippets) +
  9532. `${i}}${n}`);
  9533. };
  9534. const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9535. const [left, right] = getDirectReturnFunction([], {
  9536. functionReturn: true,
  9537. lineBreakIndent: null,
  9538. name: null
  9539. });
  9540. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9541. `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9542. `${i}${t}enumerable:${_}true,${n}` +
  9543. `${i}${t}get:${_}${left}e[k]${right}${n}` +
  9544. `${i}});${n}`);
  9545. };
  9546. const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9547. const [left, right] = getDirectReturnFunction([], {
  9548. functionReturn: true,
  9549. lineBreakIndent: null,
  9550. name: null
  9551. });
  9552. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9553. `${i}if${_}(d)${_}{${n}` +
  9554. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9555. `${i}${t}${t}enumerable:${_}true,${n}` +
  9556. `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
  9557. `${i}${t}});${n}` +
  9558. `${i}}${n}`);
  9559. };
  9560. const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
  9561. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  9562. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  9563. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  9564. : fragment;
  9565. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  9566. function getToStringTagValue(getObject) {
  9567. return getObject([['value', "'Module'"]], {
  9568. lineBreakIndent: null
  9569. });
  9570. }
  9571. class ImportExpression extends NodeBase {
  9572. constructor() {
  9573. super(...arguments);
  9574. this.inlineNamespace = null;
  9575. this.mechanism = null;
  9576. this.resolution = null;
  9577. }
  9578. hasEffects() {
  9579. return true;
  9580. }
  9581. include(context, includeChildrenRecursively) {
  9582. if (!this.included) {
  9583. this.included = true;
  9584. this.context.includeDynamicImport(this);
  9585. this.scope.addAccessedDynamicImport(this);
  9586. }
  9587. this.source.include(context, includeChildrenRecursively);
  9588. }
  9589. initialise() {
  9590. this.context.addDynamicImport(this);
  9591. }
  9592. render(code, options) {
  9593. if (this.inlineNamespace) {
  9594. const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
  9595. const [left, right] = getDirectReturnFunction([], {
  9596. functionReturn: true,
  9597. lineBreakIndent: null,
  9598. name: null
  9599. });
  9600. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
  9601. return;
  9602. }
  9603. if (this.mechanism) {
  9604. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  9605. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  9606. }
  9607. this.source.render(code, options);
  9608. }
  9609. renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
  9610. code.overwrite(this.source.start, this.source.end, resolution);
  9611. if (namespaceExportName) {
  9612. const [left, right] = getDirectReturnFunction(['n'], {
  9613. functionReturn: true,
  9614. lineBreakIndent: null,
  9615. name: null
  9616. });
  9617. code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
  9618. }
  9619. }
  9620. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
  9621. const { format } = options;
  9622. this.inlineNamespace = null;
  9623. this.resolution = resolution;
  9624. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  9625. let helper;
  9626. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  9627. if (helper) {
  9628. accessedGlobals.push(helper);
  9629. }
  9630. if (accessedGlobals.length > 0) {
  9631. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9632. }
  9633. }
  9634. setInternalResolution(inlineNamespace) {
  9635. this.inlineNamespace = inlineNamespace;
  9636. }
  9637. applyDeoptimizations() { }
  9638. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  9639. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  9640. {
  9641. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  9642. format,
  9643. moduleId: this.context.module.id,
  9644. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  9645. }
  9646. ]);
  9647. if (mechanism) {
  9648. return { helper: null, mechanism };
  9649. }
  9650. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  9651. switch (format) {
  9652. case 'cjs': {
  9653. const helper = getInteropHelper(resolution, exportMode, interop);
  9654. let left = `require(`;
  9655. let right = `)`;
  9656. if (helper) {
  9657. left = `/*#__PURE__*/${helper}(${left}`;
  9658. right += ')';
  9659. }
  9660. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  9661. functionReturn: true,
  9662. lineBreakIndent: null,
  9663. name: null
  9664. });
  9665. left = `Promise.resolve().then(${functionLeft}${left}`;
  9666. right += `${functionRight})`;
  9667. if (!arrowFunctions && hasDynamicTarget) {
  9668. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9669. needsArrowReturnParens: false,
  9670. needsWrappedFunction: true
  9671. });
  9672. right = ')';
  9673. }
  9674. return {
  9675. helper,
  9676. mechanism: { left, right }
  9677. };
  9678. }
  9679. case 'amd': {
  9680. const resolve = compact ? 'c' : 'resolve';
  9681. const reject = compact ? 'e' : 'reject';
  9682. const helper = getInteropHelper(resolution, exportMode, interop);
  9683. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  9684. functionReturn: false,
  9685. lineBreakIndent: null,
  9686. name: null
  9687. });
  9688. const resolveNamespace = helper
  9689. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  9690. : resolve;
  9691. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  9692. functionReturn: false,
  9693. lineBreakIndent: null,
  9694. name: null
  9695. });
  9696. let left = `new Promise(${handlerLeft}require([`;
  9697. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  9698. if (!arrowFunctions && hasDynamicTarget) {
  9699. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9700. needsArrowReturnParens: false,
  9701. needsWrappedFunction: true
  9702. });
  9703. right = ')';
  9704. }
  9705. return {
  9706. helper,
  9707. mechanism: { left, right }
  9708. };
  9709. }
  9710. case 'system':
  9711. return {
  9712. helper: null,
  9713. mechanism: {
  9714. left: 'module.import(',
  9715. right: ')'
  9716. }
  9717. };
  9718. case 'es':
  9719. if (dynamicImportFunction) {
  9720. return {
  9721. helper: null,
  9722. mechanism: {
  9723. left: `${dynamicImportFunction}(`,
  9724. right: ')'
  9725. }
  9726. };
  9727. }
  9728. }
  9729. return { helper: null, mechanism: null };
  9730. }
  9731. }
  9732. function getInteropHelper(resolution, exportMode, interop) {
  9733. return exportMode === 'external'
  9734. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  9735. : exportMode === 'default'
  9736. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9737. : null;
  9738. }
  9739. const accessedImportGlobals = {
  9740. amd: ['require'],
  9741. cjs: ['require'],
  9742. system: ['module']
  9743. };
  9744. class ImportNamespaceSpecifier extends NodeBase {
  9745. applyDeoptimizations() { }
  9746. }
  9747. class ImportSpecifier extends NodeBase {
  9748. applyDeoptimizations() { }
  9749. }
  9750. class LabeledStatement extends NodeBase {
  9751. hasEffects(context) {
  9752. const brokenFlow = context.brokenFlow;
  9753. context.ignore.labels.add(this.label.name);
  9754. if (this.body.hasEffects(context))
  9755. return true;
  9756. context.ignore.labels.delete(this.label.name);
  9757. if (context.includedLabels.has(this.label.name)) {
  9758. context.includedLabels.delete(this.label.name);
  9759. context.brokenFlow = brokenFlow;
  9760. }
  9761. return false;
  9762. }
  9763. include(context, includeChildrenRecursively) {
  9764. this.included = true;
  9765. const brokenFlow = context.brokenFlow;
  9766. this.body.include(context, includeChildrenRecursively);
  9767. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  9768. this.label.include();
  9769. context.includedLabels.delete(this.label.name);
  9770. context.brokenFlow = brokenFlow;
  9771. }
  9772. }
  9773. render(code, options) {
  9774. if (this.label.included) {
  9775. this.label.render(code, options);
  9776. }
  9777. else {
  9778. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  9779. }
  9780. this.body.render(code, options);
  9781. }
  9782. }
  9783. class LogicalExpression extends NodeBase {
  9784. constructor() {
  9785. super(...arguments);
  9786. // We collect deoptimization information if usedBranch !== null
  9787. this.expressionsToBeDeoptimized = [];
  9788. this.isBranchResolutionAnalysed = false;
  9789. this.usedBranch = null;
  9790. }
  9791. deoptimizeCache() {
  9792. if (this.usedBranch) {
  9793. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  9794. this.usedBranch = null;
  9795. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9796. for (const expression of this.expressionsToBeDeoptimized) {
  9797. expression.deoptimizeCache();
  9798. }
  9799. // Request another pass because we need to ensure "include" runs again if
  9800. // it is rendered
  9801. this.context.requestTreeshakingPass();
  9802. }
  9803. }
  9804. deoptimizePath(path) {
  9805. const usedBranch = this.getUsedBranch();
  9806. if (!usedBranch) {
  9807. this.left.deoptimizePath(path);
  9808. this.right.deoptimizePath(path);
  9809. }
  9810. else {
  9811. usedBranch.deoptimizePath(path);
  9812. }
  9813. }
  9814. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9815. this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9816. this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9817. }
  9818. getLiteralValueAtPath(path, recursionTracker, origin) {
  9819. const usedBranch = this.getUsedBranch();
  9820. if (!usedBranch)
  9821. return UnknownValue;
  9822. this.expressionsToBeDeoptimized.push(origin);
  9823. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9824. }
  9825. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9826. const usedBranch = this.getUsedBranch();
  9827. if (!usedBranch)
  9828. return new MultiExpression([
  9829. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  9830. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  9831. ]);
  9832. this.expressionsToBeDeoptimized.push(origin);
  9833. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9834. }
  9835. hasEffects(context) {
  9836. if (this.left.hasEffects(context)) {
  9837. return true;
  9838. }
  9839. if (this.getUsedBranch() !== this.left) {
  9840. return this.right.hasEffects(context);
  9841. }
  9842. return false;
  9843. }
  9844. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9845. const usedBranch = this.getUsedBranch();
  9846. if (!usedBranch) {
  9847. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9848. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  9849. }
  9850. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9851. }
  9852. include(context, includeChildrenRecursively) {
  9853. this.included = true;
  9854. const usedBranch = this.getUsedBranch();
  9855. if (includeChildrenRecursively ||
  9856. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  9857. !usedBranch) {
  9858. this.left.include(context, includeChildrenRecursively);
  9859. this.right.include(context, includeChildrenRecursively);
  9860. }
  9861. else {
  9862. usedBranch.include(context, includeChildrenRecursively);
  9863. }
  9864. }
  9865. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9866. if (!this.left.included || !this.right.included) {
  9867. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  9868. if (this.right.included) {
  9869. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  9870. code.remove(this.start, removePos);
  9871. if (preventASI) {
  9872. removeLineBreaks(code, removePos, this.right.start);
  9873. }
  9874. }
  9875. else {
  9876. code.remove(operatorPos, this.end);
  9877. }
  9878. removeAnnotations(this, code);
  9879. this.getUsedBranch().render(code, options, {
  9880. isCalleeOfRenderedParent,
  9881. preventASI,
  9882. renderedParentType: renderedParentType || this.parent.type,
  9883. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9884. });
  9885. }
  9886. else {
  9887. this.left.render(code, options, {
  9888. preventASI,
  9889. renderedSurroundingElement
  9890. });
  9891. this.right.render(code, options);
  9892. }
  9893. }
  9894. getUsedBranch() {
  9895. if (!this.isBranchResolutionAnalysed) {
  9896. this.isBranchResolutionAnalysed = true;
  9897. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9898. if (typeof leftValue === 'symbol') {
  9899. return null;
  9900. }
  9901. else {
  9902. this.usedBranch =
  9903. (this.operator === '||' && leftValue) ||
  9904. (this.operator === '&&' && !leftValue) ||
  9905. (this.operator === '??' && leftValue != null)
  9906. ? this.left
  9907. : this.right;
  9908. }
  9909. }
  9910. return this.usedBranch;
  9911. }
  9912. }
  9913. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  9914. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  9915. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  9916. class MetaProperty extends NodeBase {
  9917. addAccessedGlobals(format, accessedGlobalsByScope) {
  9918. const metaProperty = this.metaProperty;
  9919. const accessedGlobals = (metaProperty &&
  9920. (metaProperty.startsWith(FILE_PREFIX) ||
  9921. metaProperty.startsWith(ASSET_PREFIX) ||
  9922. metaProperty.startsWith(CHUNK_PREFIX))
  9923. ? accessedFileUrlGlobals
  9924. : accessedMetaUrlGlobals)[format];
  9925. if (accessedGlobals.length > 0) {
  9926. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9927. }
  9928. }
  9929. getReferencedFileName(outputPluginDriver) {
  9930. const metaProperty = this.metaProperty;
  9931. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  9932. return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
  9933. }
  9934. return null;
  9935. }
  9936. hasEffects() {
  9937. return false;
  9938. }
  9939. hasEffectsOnInteractionAtPath(path, { type }) {
  9940. return path.length > 1 || type !== INTERACTION_ACCESSED;
  9941. }
  9942. include() {
  9943. if (!this.included) {
  9944. this.included = true;
  9945. if (this.meta.name === 'import') {
  9946. this.context.addImportMeta(this);
  9947. const parent = this.parent;
  9948. this.metaProperty =
  9949. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  9950. ? parent.propertyKey
  9951. : null;
  9952. }
  9953. }
  9954. }
  9955. renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
  9956. var _a;
  9957. const parent = this.parent;
  9958. const metaProperty = this.metaProperty;
  9959. if (metaProperty &&
  9960. (metaProperty.startsWith(FILE_PREFIX) ||
  9961. metaProperty.startsWith(ASSET_PREFIX) ||
  9962. metaProperty.startsWith(CHUNK_PREFIX))) {
  9963. let referenceId = null;
  9964. let assetReferenceId = null;
  9965. let chunkReferenceId = null;
  9966. let fileName;
  9967. if (metaProperty.startsWith(FILE_PREFIX)) {
  9968. referenceId = metaProperty.substring(FILE_PREFIX.length);
  9969. fileName = outputPluginDriver.getFileName(referenceId);
  9970. }
  9971. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  9972. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9973. assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
  9974. fileName = outputPluginDriver.getFileName(assetReferenceId);
  9975. }
  9976. else {
  9977. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9978. chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
  9979. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  9980. }
  9981. const relativePath = normalize(require$$0.relative(require$$0.dirname(chunkId), fileName));
  9982. let replacement;
  9983. if (assetReferenceId !== null) {
  9984. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  9985. {
  9986. assetFileName: fileName,
  9987. chunkId,
  9988. format,
  9989. moduleId: this.context.module.id,
  9990. relativeAssetPath: relativePath
  9991. }
  9992. ]);
  9993. }
  9994. if (!replacement) {
  9995. replacement =
  9996. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  9997. {
  9998. assetReferenceId,
  9999. chunkId,
  10000. chunkReferenceId,
  10001. fileName,
  10002. format,
  10003. moduleId: this.context.module.id,
  10004. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  10005. relativePath
  10006. }
  10007. ]) || relativeUrlMechanisms[format](relativePath);
  10008. }
  10009. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10010. return;
  10011. }
  10012. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  10013. metaProperty,
  10014. {
  10015. chunkId,
  10016. format,
  10017. moduleId: this.context.module.id
  10018. }
  10019. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
  10020. if (typeof replacement === 'string') {
  10021. if (parent instanceof MemberExpression) {
  10022. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10023. }
  10024. else {
  10025. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  10026. }
  10027. }
  10028. }
  10029. }
  10030. const accessedMetaUrlGlobals = {
  10031. amd: ['document', 'module', 'URL'],
  10032. cjs: ['document', 'require', 'URL'],
  10033. es: [],
  10034. iife: ['document', 'URL'],
  10035. system: ['module'],
  10036. umd: ['document', 'require', 'URL']
  10037. };
  10038. const accessedFileUrlGlobals = {
  10039. amd: ['document', 'require', 'URL'],
  10040. cjs: ['document', 'require', 'URL'],
  10041. es: [],
  10042. iife: ['document', 'URL'],
  10043. system: ['module', 'URL'],
  10044. umd: ['document', 'require', 'URL']
  10045. };
  10046. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  10047. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  10048. const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
  10049. const urlMechanism = getUrl(chunkId);
  10050. return prop === null
  10051. ? `({ url: ${urlMechanism} })`
  10052. : prop === 'url'
  10053. ? urlMechanism
  10054. : 'undefined';
  10055. };
  10056. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  10057. const relativeUrlMechanisms = {
  10058. amd: relativePath => {
  10059. if (relativePath[0] !== '.')
  10060. relativePath = './' + relativePath;
  10061. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  10062. },
  10063. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  10064. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  10065. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  10066. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  10067. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  10068. };
  10069. const importMetaMechanisms = {
  10070. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  10071. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  10072. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  10073. system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
  10074. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  10075. };
  10076. class NewExpression extends NodeBase {
  10077. hasEffects(context) {
  10078. try {
  10079. for (const argument of this.arguments) {
  10080. if (argument.hasEffects(context))
  10081. return true;
  10082. }
  10083. if (this.context.options.treeshake.annotations &&
  10084. this.annotations) {
  10085. return false;
  10086. }
  10087. return (this.callee.hasEffects(context) ||
  10088. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10089. }
  10090. finally {
  10091. if (!this.deoptimized)
  10092. this.applyDeoptimizations();
  10093. }
  10094. }
  10095. hasEffectsOnInteractionAtPath(path, { type }) {
  10096. return path.length > 0 || type !== INTERACTION_ACCESSED;
  10097. }
  10098. include(context, includeChildrenRecursively) {
  10099. if (!this.deoptimized)
  10100. this.applyDeoptimizations();
  10101. if (includeChildrenRecursively) {
  10102. super.include(context, includeChildrenRecursively);
  10103. }
  10104. else {
  10105. this.included = true;
  10106. this.callee.include(context, false);
  10107. }
  10108. this.callee.includeCallArguments(context, this.arguments);
  10109. }
  10110. initialise() {
  10111. this.interaction = {
  10112. args: this.arguments,
  10113. thisArg: null,
  10114. type: INTERACTION_CALLED,
  10115. withNew: true
  10116. };
  10117. }
  10118. render(code, options) {
  10119. this.callee.render(code, options);
  10120. renderCallArguments(code, options, this);
  10121. }
  10122. applyDeoptimizations() {
  10123. this.deoptimized = true;
  10124. for (const argument of this.arguments) {
  10125. // This will make sure all properties of parameters behave as "unknown"
  10126. argument.deoptimizePath(UNKNOWN_PATH);
  10127. }
  10128. this.context.requestTreeshakingPass();
  10129. }
  10130. }
  10131. class ObjectExpression extends NodeBase {
  10132. constructor() {
  10133. super(...arguments);
  10134. this.objectEntity = null;
  10135. }
  10136. deoptimizeCache() {
  10137. this.getObjectEntity().deoptimizeAllProperties();
  10138. }
  10139. deoptimizePath(path) {
  10140. this.getObjectEntity().deoptimizePath(path);
  10141. }
  10142. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10143. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10144. }
  10145. getLiteralValueAtPath(path, recursionTracker, origin) {
  10146. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10147. }
  10148. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10149. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10150. }
  10151. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10152. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10153. }
  10154. render(code, options, { renderedSurroundingElement } = BLANK) {
  10155. super.render(code, options);
  10156. if (renderedSurroundingElement === ExpressionStatement$1 ||
  10157. renderedSurroundingElement === ArrowFunctionExpression$1) {
  10158. code.appendRight(this.start, '(');
  10159. code.prependLeft(this.end, ')');
  10160. }
  10161. }
  10162. applyDeoptimizations() { }
  10163. getObjectEntity() {
  10164. if (this.objectEntity !== null) {
  10165. return this.objectEntity;
  10166. }
  10167. let prototype = OBJECT_PROTOTYPE;
  10168. const properties = [];
  10169. for (const property of this.properties) {
  10170. if (property instanceof SpreadElement) {
  10171. properties.push({ key: UnknownKey, kind: 'init', property });
  10172. continue;
  10173. }
  10174. let key;
  10175. if (property.computed) {
  10176. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10177. if (typeof keyValue === 'symbol') {
  10178. properties.push({ key: UnknownKey, kind: property.kind, property });
  10179. continue;
  10180. }
  10181. else {
  10182. key = String(keyValue);
  10183. }
  10184. }
  10185. else {
  10186. key =
  10187. property.key instanceof Identifier
  10188. ? property.key.name
  10189. : String(property.key.value);
  10190. if (key === '__proto__' && property.kind === 'init') {
  10191. prototype =
  10192. property.value instanceof Literal && property.value.value === null
  10193. ? null
  10194. : property.value;
  10195. continue;
  10196. }
  10197. }
  10198. properties.push({ key, kind: property.kind, property });
  10199. }
  10200. return (this.objectEntity = new ObjectEntity(properties, prototype));
  10201. }
  10202. }
  10203. class PrivateIdentifier extends NodeBase {
  10204. }
  10205. class Program extends NodeBase {
  10206. constructor() {
  10207. super(...arguments);
  10208. this.hasCachedEffect = false;
  10209. }
  10210. hasEffects(context) {
  10211. // We are caching here to later more efficiently identify side-effect-free modules
  10212. if (this.hasCachedEffect)
  10213. return true;
  10214. for (const node of this.body) {
  10215. if (node.hasEffects(context)) {
  10216. return (this.hasCachedEffect = true);
  10217. }
  10218. }
  10219. return false;
  10220. }
  10221. include(context, includeChildrenRecursively) {
  10222. this.included = true;
  10223. for (const node of this.body) {
  10224. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  10225. node.include(context, includeChildrenRecursively);
  10226. }
  10227. }
  10228. }
  10229. render(code, options) {
  10230. if (this.body.length) {
  10231. renderStatementList(this.body, code, this.start, this.end, options);
  10232. }
  10233. else {
  10234. super.render(code, options);
  10235. }
  10236. }
  10237. applyDeoptimizations() { }
  10238. }
  10239. class Property extends MethodBase {
  10240. constructor() {
  10241. super(...arguments);
  10242. this.declarationInit = null;
  10243. }
  10244. declare(kind, init) {
  10245. this.declarationInit = init;
  10246. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  10247. }
  10248. hasEffects(context) {
  10249. if (!this.deoptimized)
  10250. this.applyDeoptimizations();
  10251. const propertyReadSideEffects = this.context.options.treeshake
  10252. .propertyReadSideEffects;
  10253. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  10254. this.key.hasEffects(context) ||
  10255. this.value.hasEffects(context));
  10256. }
  10257. markDeclarationReached() {
  10258. this.value.markDeclarationReached();
  10259. }
  10260. render(code, options) {
  10261. if (!this.shorthand) {
  10262. this.key.render(code, options);
  10263. }
  10264. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  10265. }
  10266. applyDeoptimizations() {
  10267. this.deoptimized = true;
  10268. if (this.declarationInit !== null) {
  10269. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  10270. this.context.requestTreeshakingPass();
  10271. }
  10272. }
  10273. }
  10274. class PropertyDefinition extends NodeBase {
  10275. deoptimizePath(path) {
  10276. var _a;
  10277. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  10278. }
  10279. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10280. var _a;
  10281. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10282. }
  10283. getLiteralValueAtPath(path, recursionTracker, origin) {
  10284. return this.value
  10285. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  10286. : UnknownValue;
  10287. }
  10288. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10289. return this.value
  10290. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  10291. : UNKNOWN_EXPRESSION;
  10292. }
  10293. hasEffects(context) {
  10294. var _a;
  10295. return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10296. }
  10297. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10298. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  10299. }
  10300. applyDeoptimizations() { }
  10301. }
  10302. class ReturnStatement extends NodeBase {
  10303. hasEffects(context) {
  10304. var _a;
  10305. if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
  10306. return true;
  10307. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10308. return false;
  10309. }
  10310. include(context, includeChildrenRecursively) {
  10311. var _a;
  10312. this.included = true;
  10313. (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10314. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10315. }
  10316. initialise() {
  10317. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  10318. }
  10319. render(code, options) {
  10320. if (this.argument) {
  10321. this.argument.render(code, options, { preventASI: true });
  10322. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  10323. code.prependLeft(this.start + 6, ' ');
  10324. }
  10325. }
  10326. }
  10327. }
  10328. class SequenceExpression extends NodeBase {
  10329. deoptimizePath(path) {
  10330. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  10331. }
  10332. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10333. this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10334. }
  10335. getLiteralValueAtPath(path, recursionTracker, origin) {
  10336. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  10337. }
  10338. hasEffects(context) {
  10339. for (const expression of this.expressions) {
  10340. if (expression.hasEffects(context))
  10341. return true;
  10342. }
  10343. return false;
  10344. }
  10345. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10346. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  10347. }
  10348. include(context, includeChildrenRecursively) {
  10349. this.included = true;
  10350. const lastExpression = this.expressions[this.expressions.length - 1];
  10351. for (const expression of this.expressions) {
  10352. if (includeChildrenRecursively ||
  10353. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  10354. expression.shouldBeIncluded(context))
  10355. expression.include(context, includeChildrenRecursively);
  10356. }
  10357. }
  10358. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  10359. let includedNodes = 0;
  10360. let lastSeparatorPos = null;
  10361. const lastNode = this.expressions[this.expressions.length - 1];
  10362. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  10363. if (!node.included) {
  10364. treeshakeNode(node, code, start, end);
  10365. continue;
  10366. }
  10367. includedNodes++;
  10368. lastSeparatorPos = separator;
  10369. if (includedNodes === 1 && preventASI) {
  10370. removeLineBreaks(code, start, node.start);
  10371. }
  10372. if (includedNodes === 1) {
  10373. const parentType = renderedParentType || this.parent.type;
  10374. node.render(code, options, {
  10375. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  10376. renderedParentType: parentType,
  10377. renderedSurroundingElement: parentType
  10378. });
  10379. }
  10380. else {
  10381. node.render(code, options);
  10382. }
  10383. }
  10384. if (lastSeparatorPos) {
  10385. code.remove(lastSeparatorPos, this.end);
  10386. }
  10387. }
  10388. }
  10389. class StaticBlock extends NodeBase {
  10390. createScope(parentScope) {
  10391. this.scope = new BlockScope(parentScope);
  10392. }
  10393. hasEffects(context) {
  10394. for (const node of this.body) {
  10395. if (node.hasEffects(context))
  10396. return true;
  10397. }
  10398. return false;
  10399. }
  10400. include(context, includeChildrenRecursively) {
  10401. this.included = true;
  10402. for (const node of this.body) {
  10403. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10404. node.include(context, includeChildrenRecursively);
  10405. }
  10406. }
  10407. render(code, options) {
  10408. if (this.body.length) {
  10409. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  10410. }
  10411. else {
  10412. super.render(code, options);
  10413. }
  10414. }
  10415. }
  10416. class Super extends NodeBase {
  10417. bind() {
  10418. this.variable = this.scope.findVariable('this');
  10419. }
  10420. deoptimizePath(path) {
  10421. this.variable.deoptimizePath(path);
  10422. }
  10423. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10424. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10425. }
  10426. include() {
  10427. if (!this.included) {
  10428. this.included = true;
  10429. this.context.includeVariableInModule(this.variable);
  10430. }
  10431. }
  10432. }
  10433. class SwitchCase extends NodeBase {
  10434. hasEffects(context) {
  10435. var _a;
  10436. if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
  10437. return true;
  10438. for (const node of this.consequent) {
  10439. if (context.brokenFlow)
  10440. break;
  10441. if (node.hasEffects(context))
  10442. return true;
  10443. }
  10444. return false;
  10445. }
  10446. include(context, includeChildrenRecursively) {
  10447. var _a;
  10448. this.included = true;
  10449. (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10450. for (const node of this.consequent) {
  10451. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10452. node.include(context, includeChildrenRecursively);
  10453. }
  10454. }
  10455. render(code, options, nodeRenderOptions) {
  10456. if (this.consequent.length) {
  10457. this.test && this.test.render(code, options);
  10458. const testEnd = this.test
  10459. ? this.test.end
  10460. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  10461. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  10462. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  10463. }
  10464. else {
  10465. super.render(code, options);
  10466. }
  10467. }
  10468. }
  10469. SwitchCase.prototype.needsBoundaries = true;
  10470. class SwitchStatement extends NodeBase {
  10471. createScope(parentScope) {
  10472. this.scope = new BlockScope(parentScope);
  10473. }
  10474. hasEffects(context) {
  10475. if (this.discriminant.hasEffects(context))
  10476. return true;
  10477. const { brokenFlow, ignore: { breaks } } = context;
  10478. let minBrokenFlow = Infinity;
  10479. context.ignore.breaks = true;
  10480. for (const switchCase of this.cases) {
  10481. if (switchCase.hasEffects(context))
  10482. return true;
  10483. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  10484. context.brokenFlow = brokenFlow;
  10485. }
  10486. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10487. context.brokenFlow = minBrokenFlow;
  10488. }
  10489. context.ignore.breaks = breaks;
  10490. return false;
  10491. }
  10492. include(context, includeChildrenRecursively) {
  10493. this.included = true;
  10494. this.discriminant.include(context, includeChildrenRecursively);
  10495. const { brokenFlow } = context;
  10496. let minBrokenFlow = Infinity;
  10497. let isCaseIncluded = includeChildrenRecursively ||
  10498. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  10499. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  10500. const switchCase = this.cases[caseIndex];
  10501. if (switchCase.included) {
  10502. isCaseIncluded = true;
  10503. }
  10504. if (!isCaseIncluded) {
  10505. const hasEffectsContext = createHasEffectsContext();
  10506. hasEffectsContext.ignore.breaks = true;
  10507. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  10508. }
  10509. if (isCaseIncluded) {
  10510. switchCase.include(context, includeChildrenRecursively);
  10511. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  10512. context.brokenFlow = brokenFlow;
  10513. }
  10514. else {
  10515. minBrokenFlow = brokenFlow;
  10516. }
  10517. }
  10518. if (isCaseIncluded &&
  10519. this.defaultCase !== null &&
  10520. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10521. context.brokenFlow = minBrokenFlow;
  10522. }
  10523. }
  10524. initialise() {
  10525. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  10526. if (this.cases[caseIndex].test === null) {
  10527. this.defaultCase = caseIndex;
  10528. return;
  10529. }
  10530. }
  10531. this.defaultCase = null;
  10532. }
  10533. render(code, options) {
  10534. this.discriminant.render(code, options);
  10535. if (this.cases.length > 0) {
  10536. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  10537. }
  10538. }
  10539. }
  10540. class TaggedTemplateExpression extends CallExpressionBase {
  10541. bind() {
  10542. super.bind();
  10543. if (this.tag.type === Identifier$1) {
  10544. const name = this.tag.name;
  10545. const variable = this.scope.findVariable(name);
  10546. if (variable.isNamespace) {
  10547. this.context.warn({
  10548. code: 'CANNOT_CALL_NAMESPACE',
  10549. message: `Cannot call a namespace ('${name}')`
  10550. }, this.start);
  10551. }
  10552. }
  10553. }
  10554. hasEffects(context) {
  10555. try {
  10556. for (const argument of this.quasi.expressions) {
  10557. if (argument.hasEffects(context))
  10558. return true;
  10559. }
  10560. return (this.tag.hasEffects(context) ||
  10561. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10562. }
  10563. finally {
  10564. if (!this.deoptimized)
  10565. this.applyDeoptimizations();
  10566. }
  10567. }
  10568. include(context, includeChildrenRecursively) {
  10569. if (!this.deoptimized)
  10570. this.applyDeoptimizations();
  10571. if (includeChildrenRecursively) {
  10572. super.include(context, includeChildrenRecursively);
  10573. }
  10574. else {
  10575. this.included = true;
  10576. this.tag.include(context, includeChildrenRecursively);
  10577. this.quasi.include(context, includeChildrenRecursively);
  10578. }
  10579. this.tag.includeCallArguments(context, this.interaction.args);
  10580. const returnExpression = this.getReturnExpression();
  10581. if (!returnExpression.included) {
  10582. returnExpression.include(context, false);
  10583. }
  10584. }
  10585. initialise() {
  10586. this.interaction = {
  10587. args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
  10588. thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  10589. type: INTERACTION_CALLED,
  10590. withNew: false
  10591. };
  10592. }
  10593. render(code, options) {
  10594. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  10595. this.quasi.render(code, options);
  10596. }
  10597. applyDeoptimizations() {
  10598. this.deoptimized = true;
  10599. if (this.interaction.thisArg) {
  10600. this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10601. }
  10602. for (const argument of this.quasi.expressions) {
  10603. // This will make sure all properties of parameters behave as "unknown"
  10604. argument.deoptimizePath(UNKNOWN_PATH);
  10605. }
  10606. this.context.requestTreeshakingPass();
  10607. }
  10608. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10609. if (this.returnExpression === null) {
  10610. this.returnExpression = UNKNOWN_EXPRESSION;
  10611. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10612. }
  10613. return this.returnExpression;
  10614. }
  10615. }
  10616. class TemplateElement extends NodeBase {
  10617. // Do not try to bind value
  10618. bind() { }
  10619. hasEffects() {
  10620. return false;
  10621. }
  10622. include() {
  10623. this.included = true;
  10624. }
  10625. parseNode(esTreeNode) {
  10626. this.value = esTreeNode.value;
  10627. super.parseNode(esTreeNode);
  10628. }
  10629. render() { }
  10630. }
  10631. class TemplateLiteral extends NodeBase {
  10632. deoptimizeThisOnInteractionAtPath() { }
  10633. getLiteralValueAtPath(path) {
  10634. if (path.length > 0 || this.quasis.length !== 1) {
  10635. return UnknownValue;
  10636. }
  10637. return this.quasis[0].value.cooked;
  10638. }
  10639. getReturnExpressionWhenCalledAtPath(path) {
  10640. if (path.length !== 1) {
  10641. return UNKNOWN_EXPRESSION;
  10642. }
  10643. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  10644. }
  10645. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10646. if (interaction.type === INTERACTION_ACCESSED) {
  10647. return path.length > 1;
  10648. }
  10649. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  10650. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  10651. }
  10652. return true;
  10653. }
  10654. render(code, options) {
  10655. code.indentExclusionRanges.push([this.start, this.end]);
  10656. super.render(code, options);
  10657. }
  10658. }
  10659. class UndefinedVariable extends Variable {
  10660. constructor() {
  10661. super('undefined');
  10662. }
  10663. getLiteralValueAtPath() {
  10664. return undefined;
  10665. }
  10666. }
  10667. class ExportDefaultVariable extends LocalVariable {
  10668. constructor(name, exportDefaultDeclaration, context) {
  10669. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  10670. this.hasId = false;
  10671. this.originalId = null;
  10672. this.originalVariable = null;
  10673. const declaration = exportDefaultDeclaration.declaration;
  10674. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10675. declaration.id) {
  10676. this.hasId = true;
  10677. this.originalId = declaration.id;
  10678. }
  10679. else if (declaration instanceof Identifier) {
  10680. this.originalId = declaration;
  10681. }
  10682. }
  10683. addReference(identifier) {
  10684. if (!this.hasId) {
  10685. this.name = identifier.name;
  10686. }
  10687. }
  10688. getAssignedVariableName() {
  10689. return (this.originalId && this.originalId.name) || null;
  10690. }
  10691. getBaseVariableName() {
  10692. const original = this.getOriginalVariable();
  10693. if (original === this) {
  10694. return super.getBaseVariableName();
  10695. }
  10696. else {
  10697. return original.getBaseVariableName();
  10698. }
  10699. }
  10700. getDirectOriginalVariable() {
  10701. return this.originalId &&
  10702. (this.hasId ||
  10703. !(this.originalId.isPossibleTDZ() ||
  10704. this.originalId.variable.isReassigned ||
  10705. this.originalId.variable instanceof UndefinedVariable ||
  10706. // this avoids a circular dependency
  10707. 'syntheticNamespace' in this.originalId.variable))
  10708. ? this.originalId.variable
  10709. : null;
  10710. }
  10711. getName(getPropertyAccess) {
  10712. const original = this.getOriginalVariable();
  10713. if (original === this) {
  10714. return super.getName(getPropertyAccess);
  10715. }
  10716. else {
  10717. return original.getName(getPropertyAccess);
  10718. }
  10719. }
  10720. getOriginalVariable() {
  10721. if (this.originalVariable)
  10722. return this.originalVariable;
  10723. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10724. let original = this;
  10725. let currentVariable;
  10726. const checkedVariables = new Set();
  10727. do {
  10728. checkedVariables.add(original);
  10729. currentVariable = original;
  10730. original = currentVariable.getDirectOriginalVariable();
  10731. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10732. return (this.originalVariable = original || currentVariable);
  10733. }
  10734. }
  10735. class ModuleScope extends ChildScope {
  10736. constructor(parent, context) {
  10737. super(parent);
  10738. this.context = context;
  10739. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  10740. }
  10741. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  10742. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  10743. this.variables.set('default', variable);
  10744. return variable;
  10745. }
  10746. addNamespaceMemberAccess() { }
  10747. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  10748. // all module level variables are already deconflicted when deconflicting the chunk
  10749. for (const scope of this.children)
  10750. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10751. }
  10752. findLexicalBoundary() {
  10753. return this;
  10754. }
  10755. findVariable(name) {
  10756. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  10757. if (knownVariable) {
  10758. return knownVariable;
  10759. }
  10760. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  10761. if (variable instanceof GlobalVariable) {
  10762. this.accessedOutsideVariables.set(name, variable);
  10763. }
  10764. return variable;
  10765. }
  10766. }
  10767. class ThisExpression extends NodeBase {
  10768. bind() {
  10769. this.variable = this.scope.findVariable('this');
  10770. }
  10771. deoptimizePath(path) {
  10772. this.variable.deoptimizePath(path);
  10773. }
  10774. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10775. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  10776. this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
  10777. }
  10778. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10779. if (path.length === 0) {
  10780. return interaction.type !== INTERACTION_ACCESSED;
  10781. }
  10782. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10783. }
  10784. include() {
  10785. if (!this.included) {
  10786. this.included = true;
  10787. this.context.includeVariableInModule(this.variable);
  10788. }
  10789. }
  10790. initialise() {
  10791. this.alias =
  10792. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  10793. if (this.alias === 'undefined') {
  10794. this.context.warn({
  10795. code: 'THIS_IS_UNDEFINED',
  10796. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  10797. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  10798. }, this.start);
  10799. }
  10800. }
  10801. render(code) {
  10802. if (this.alias !== null) {
  10803. code.overwrite(this.start, this.end, this.alias, {
  10804. contentOnly: false,
  10805. storeName: true
  10806. });
  10807. }
  10808. }
  10809. }
  10810. class ThrowStatement extends NodeBase {
  10811. hasEffects() {
  10812. return true;
  10813. }
  10814. include(context, includeChildrenRecursively) {
  10815. this.included = true;
  10816. this.argument.include(context, includeChildrenRecursively);
  10817. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10818. }
  10819. render(code, options) {
  10820. this.argument.render(code, options, { preventASI: true });
  10821. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  10822. code.prependLeft(this.start + 5, ' ');
  10823. }
  10824. }
  10825. }
  10826. class TryStatement extends NodeBase {
  10827. constructor() {
  10828. super(...arguments);
  10829. this.directlyIncluded = false;
  10830. this.includedLabelsAfterBlock = null;
  10831. }
  10832. hasEffects(context) {
  10833. var _a;
  10834. return ((this.context.options.treeshake.tryCatchDeoptimization
  10835. ? this.block.body.length > 0
  10836. : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10837. }
  10838. include(context, includeChildrenRecursively) {
  10839. var _a, _b;
  10840. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  10841. const { brokenFlow } = context;
  10842. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  10843. this.included = true;
  10844. this.directlyIncluded = true;
  10845. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  10846. if (context.includedLabels.size > 0) {
  10847. this.includedLabelsAfterBlock = [...context.includedLabels];
  10848. }
  10849. context.brokenFlow = brokenFlow;
  10850. }
  10851. else if (this.includedLabelsAfterBlock) {
  10852. for (const label of this.includedLabelsAfterBlock) {
  10853. context.includedLabels.add(label);
  10854. }
  10855. }
  10856. if (this.handler !== null) {
  10857. this.handler.include(context, includeChildrenRecursively);
  10858. context.brokenFlow = brokenFlow;
  10859. }
  10860. (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  10861. }
  10862. }
  10863. const unaryOperators = {
  10864. '!': value => !value,
  10865. '+': value => +value,
  10866. '-': value => -value,
  10867. delete: () => UnknownValue,
  10868. typeof: value => typeof value,
  10869. void: () => undefined,
  10870. '~': value => ~value
  10871. };
  10872. class UnaryExpression extends NodeBase {
  10873. getLiteralValueAtPath(path, recursionTracker, origin) {
  10874. if (path.length > 0)
  10875. return UnknownValue;
  10876. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10877. if (typeof argumentValue === 'symbol')
  10878. return UnknownValue;
  10879. return unaryOperators[this.operator](argumentValue);
  10880. }
  10881. hasEffects(context) {
  10882. if (!this.deoptimized)
  10883. this.applyDeoptimizations();
  10884. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  10885. return false;
  10886. return (this.argument.hasEffects(context) ||
  10887. (this.operator === 'delete' &&
  10888. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  10889. }
  10890. hasEffectsOnInteractionAtPath(path, { type }) {
  10891. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  10892. }
  10893. applyDeoptimizations() {
  10894. this.deoptimized = true;
  10895. if (this.operator === 'delete') {
  10896. this.argument.deoptimizePath(EMPTY_PATH);
  10897. this.context.requestTreeshakingPass();
  10898. }
  10899. }
  10900. }
  10901. class UnknownNode extends NodeBase {
  10902. hasEffects() {
  10903. return true;
  10904. }
  10905. include(context) {
  10906. super.include(context, true);
  10907. }
  10908. }
  10909. class UpdateExpression extends NodeBase {
  10910. hasEffects(context) {
  10911. if (!this.deoptimized)
  10912. this.applyDeoptimizations();
  10913. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  10914. }
  10915. hasEffectsOnInteractionAtPath(path, { type }) {
  10916. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10917. }
  10918. include(context, includeChildrenRecursively) {
  10919. if (!this.deoptimized)
  10920. this.applyDeoptimizations();
  10921. this.included = true;
  10922. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  10923. }
  10924. initialise() {
  10925. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  10926. }
  10927. render(code, options) {
  10928. const { exportNamesByVariable, format, snippets: { _ } } = options;
  10929. this.argument.render(code, options);
  10930. if (format === 'system') {
  10931. const variable = this.argument.variable;
  10932. const exportNames = exportNamesByVariable.get(variable);
  10933. if (exportNames) {
  10934. if (this.prefix) {
  10935. if (exportNames.length === 1) {
  10936. renderSystemExportExpression(variable, this.start, this.end, code, options);
  10937. }
  10938. else {
  10939. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  10940. }
  10941. }
  10942. else {
  10943. const operator = this.operator[0];
  10944. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  10945. }
  10946. }
  10947. }
  10948. }
  10949. applyDeoptimizations() {
  10950. this.deoptimized = true;
  10951. this.argument.deoptimizePath(EMPTY_PATH);
  10952. if (this.argument instanceof Identifier) {
  10953. const variable = this.scope.findVariable(this.argument.name);
  10954. variable.isReassigned = true;
  10955. }
  10956. this.context.requestTreeshakingPass();
  10957. }
  10958. }
  10959. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10960. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10961. }
  10962. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  10963. for (const declarator of declarations) {
  10964. if (!declarator.id.included)
  10965. return false;
  10966. if (declarator.id.type === Identifier$1) {
  10967. if (exportNamesByVariable.has(declarator.id.variable))
  10968. return false;
  10969. }
  10970. else {
  10971. const exportedVariables = [];
  10972. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  10973. if (exportedVariables.length > 0)
  10974. return false;
  10975. }
  10976. }
  10977. return true;
  10978. }
  10979. class VariableDeclaration extends NodeBase {
  10980. deoptimizePath() {
  10981. for (const declarator of this.declarations) {
  10982. declarator.deoptimizePath(EMPTY_PATH);
  10983. }
  10984. }
  10985. hasEffectsOnInteractionAtPath() {
  10986. return false;
  10987. }
  10988. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  10989. this.included = true;
  10990. for (const declarator of this.declarations) {
  10991. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  10992. declarator.include(context, includeChildrenRecursively);
  10993. if (asSingleStatement) {
  10994. declarator.id.include(context, includeChildrenRecursively);
  10995. }
  10996. }
  10997. }
  10998. initialise() {
  10999. for (const declarator of this.declarations) {
  11000. declarator.declareDeclarator(this.kind);
  11001. }
  11002. }
  11003. render(code, options, nodeRenderOptions = BLANK) {
  11004. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  11005. for (const declarator of this.declarations) {
  11006. declarator.render(code, options);
  11007. }
  11008. if (!nodeRenderOptions.isNoStatement &&
  11009. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  11010. code.appendLeft(this.end, ';');
  11011. }
  11012. }
  11013. else {
  11014. this.renderReplacedDeclarations(code, options);
  11015. }
  11016. }
  11017. applyDeoptimizations() { }
  11018. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  11019. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  11020. code.remove(this.end - 1, this.end);
  11021. }
  11022. separatorString += ';';
  11023. if (lastSeparatorPos !== null) {
  11024. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  11025. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  11026. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  11027. actualContentEnd--;
  11028. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  11029. actualContentEnd--;
  11030. }
  11031. }
  11032. if (actualContentEnd === lastSeparatorPos + 1) {
  11033. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  11034. }
  11035. else {
  11036. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11037. code.remove(actualContentEnd, renderedContentEnd);
  11038. }
  11039. }
  11040. else {
  11041. code.appendLeft(renderedContentEnd, separatorString);
  11042. }
  11043. if (systemPatternExports.length > 0) {
  11044. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  11045. }
  11046. }
  11047. renderReplacedDeclarations(code, options) {
  11048. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  11049. let actualContentEnd, renderedContentEnd;
  11050. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  11051. let lastSeparatorPos = renderedContentEnd - 1;
  11052. code.remove(this.start, lastSeparatorPos);
  11053. let isInDeclaration = false;
  11054. let hasRenderedContent = false;
  11055. let separatorString = '', leadingString, nextSeparatorString;
  11056. const aggregatedSystemExports = [];
  11057. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  11058. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  11059. if (!node.included) {
  11060. code.remove(start, end);
  11061. continue;
  11062. }
  11063. node.render(code, options);
  11064. leadingString = '';
  11065. nextSeparatorString = '';
  11066. if (!node.id.included ||
  11067. (node.id instanceof Identifier &&
  11068. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  11069. if (hasRenderedContent) {
  11070. separatorString += ';';
  11071. }
  11072. isInDeclaration = false;
  11073. }
  11074. else {
  11075. if (singleSystemExport && singleSystemExport === node.id.variable) {
  11076. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  11077. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  11078. }
  11079. if (isInDeclaration) {
  11080. separatorString += ',';
  11081. }
  11082. else {
  11083. if (hasRenderedContent) {
  11084. separatorString += ';';
  11085. }
  11086. leadingString += `${this.kind} `;
  11087. isInDeclaration = true;
  11088. }
  11089. }
  11090. if (renderedContentEnd === lastSeparatorPos + 1) {
  11091. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  11092. }
  11093. else {
  11094. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11095. code.appendLeft(renderedContentEnd, leadingString);
  11096. }
  11097. actualContentEnd = contentEnd;
  11098. renderedContentEnd = end;
  11099. hasRenderedContent = true;
  11100. lastSeparatorPos = separator;
  11101. separatorString = nextSeparatorString;
  11102. }
  11103. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  11104. }
  11105. }
  11106. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  11107. var _a;
  11108. let singleSystemExport = null;
  11109. if (options.format === 'system') {
  11110. for (const { node } of separatedNodes) {
  11111. if (node.id instanceof Identifier &&
  11112. node.init &&
  11113. aggregatedSystemExports.length === 0 &&
  11114. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  11115. singleSystemExport = node.id.variable;
  11116. aggregatedSystemExports.push(singleSystemExport);
  11117. }
  11118. else {
  11119. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  11120. }
  11121. }
  11122. if (aggregatedSystemExports.length > 1) {
  11123. singleSystemExport = null;
  11124. }
  11125. else if (singleSystemExport) {
  11126. aggregatedSystemExports.length = 0;
  11127. }
  11128. }
  11129. return singleSystemExport;
  11130. }
  11131. class VariableDeclarator extends NodeBase {
  11132. declareDeclarator(kind) {
  11133. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11134. }
  11135. deoptimizePath(path) {
  11136. this.id.deoptimizePath(path);
  11137. }
  11138. hasEffects(context) {
  11139. var _a;
  11140. const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
  11141. this.id.markDeclarationReached();
  11142. return initEffect || this.id.hasEffects(context);
  11143. }
  11144. include(context, includeChildrenRecursively) {
  11145. var _a;
  11146. this.included = true;
  11147. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  11148. this.id.markDeclarationReached();
  11149. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  11150. this.id.include(context, includeChildrenRecursively);
  11151. }
  11152. }
  11153. render(code, options) {
  11154. const { exportNamesByVariable, snippets: { _ } } = options;
  11155. const renderId = this.id.included;
  11156. if (renderId) {
  11157. this.id.render(code, options);
  11158. }
  11159. else {
  11160. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  11161. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  11162. }
  11163. if (this.init) {
  11164. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11165. }
  11166. else if (this.id instanceof Identifier &&
  11167. isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
  11168. code.appendLeft(this.end, `${_}=${_}void 0`);
  11169. }
  11170. }
  11171. applyDeoptimizations() { }
  11172. }
  11173. class WhileStatement extends NodeBase {
  11174. hasEffects(context) {
  11175. if (this.test.hasEffects(context))
  11176. return true;
  11177. const { brokenFlow, ignore: { breaks, continues } } = context;
  11178. context.ignore.breaks = true;
  11179. context.ignore.continues = true;
  11180. if (this.body.hasEffects(context))
  11181. return true;
  11182. context.ignore.breaks = breaks;
  11183. context.ignore.continues = continues;
  11184. context.brokenFlow = brokenFlow;
  11185. return false;
  11186. }
  11187. include(context, includeChildrenRecursively) {
  11188. this.included = true;
  11189. this.test.include(context, includeChildrenRecursively);
  11190. const { brokenFlow } = context;
  11191. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11192. context.brokenFlow = brokenFlow;
  11193. }
  11194. }
  11195. class YieldExpression extends NodeBase {
  11196. hasEffects(context) {
  11197. var _a;
  11198. if (!this.deoptimized)
  11199. this.applyDeoptimizations();
  11200. return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  11201. }
  11202. render(code, options) {
  11203. if (this.argument) {
  11204. this.argument.render(code, options, { preventASI: true });
  11205. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  11206. code.prependLeft(this.start + 5, ' ');
  11207. }
  11208. }
  11209. }
  11210. }
  11211. const nodeConstructors = {
  11212. ArrayExpression,
  11213. ArrayPattern,
  11214. ArrowFunctionExpression,
  11215. AssignmentExpression,
  11216. AssignmentPattern,
  11217. AwaitExpression,
  11218. BinaryExpression,
  11219. BlockStatement,
  11220. BreakStatement,
  11221. CallExpression,
  11222. CatchClause,
  11223. ChainExpression,
  11224. ClassBody,
  11225. ClassDeclaration,
  11226. ClassExpression,
  11227. ConditionalExpression,
  11228. ContinueStatement,
  11229. DoWhileStatement,
  11230. EmptyStatement,
  11231. ExportAllDeclaration,
  11232. ExportDefaultDeclaration,
  11233. ExportNamedDeclaration,
  11234. ExportSpecifier,
  11235. ExpressionStatement,
  11236. ForInStatement,
  11237. ForOfStatement,
  11238. ForStatement,
  11239. FunctionDeclaration,
  11240. FunctionExpression,
  11241. Identifier,
  11242. IfStatement,
  11243. ImportDeclaration,
  11244. ImportDefaultSpecifier,
  11245. ImportExpression,
  11246. ImportNamespaceSpecifier,
  11247. ImportSpecifier,
  11248. LabeledStatement,
  11249. Literal,
  11250. LogicalExpression,
  11251. MemberExpression,
  11252. MetaProperty,
  11253. MethodDefinition,
  11254. NewExpression,
  11255. ObjectExpression,
  11256. ObjectPattern,
  11257. PrivateIdentifier,
  11258. Program,
  11259. Property,
  11260. PropertyDefinition,
  11261. RestElement,
  11262. ReturnStatement,
  11263. SequenceExpression,
  11264. SpreadElement,
  11265. StaticBlock,
  11266. Super,
  11267. SwitchCase,
  11268. SwitchStatement,
  11269. TaggedTemplateExpression,
  11270. TemplateElement,
  11271. TemplateLiteral,
  11272. ThisExpression,
  11273. ThrowStatement,
  11274. TryStatement,
  11275. UnaryExpression,
  11276. UnknownNode,
  11277. UpdateExpression,
  11278. VariableDeclaration,
  11279. VariableDeclarator,
  11280. WhileStatement,
  11281. YieldExpression
  11282. };
  11283. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11284. class ExportShimVariable extends Variable {
  11285. constructor(module) {
  11286. super(MISSING_EXPORT_SHIM_VARIABLE);
  11287. this.module = module;
  11288. }
  11289. include() {
  11290. super.include();
  11291. this.module.needsExportShim = true;
  11292. }
  11293. }
  11294. class NamespaceVariable extends Variable {
  11295. constructor(context) {
  11296. super(context.getModuleName());
  11297. this.memberVariables = null;
  11298. this.mergedNamespaces = [];
  11299. this.referencedEarly = false;
  11300. this.references = [];
  11301. this.context = context;
  11302. this.module = context.module;
  11303. }
  11304. addReference(identifier) {
  11305. this.references.push(identifier);
  11306. this.name = identifier.name;
  11307. }
  11308. getMemberVariables() {
  11309. if (this.memberVariables) {
  11310. return this.memberVariables;
  11311. }
  11312. const memberVariables = Object.create(null);
  11313. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  11314. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  11315. const exportedVariable = this.context.traceExport(name);
  11316. if (exportedVariable) {
  11317. memberVariables[name] = exportedVariable;
  11318. }
  11319. }
  11320. }
  11321. return (this.memberVariables = memberVariables);
  11322. }
  11323. include() {
  11324. this.included = true;
  11325. this.context.includeAllExports();
  11326. }
  11327. prepare(accessedGlobalsByScope) {
  11328. if (this.mergedNamespaces.length > 0) {
  11329. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  11330. }
  11331. }
  11332. renderBlock(options) {
  11333. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  11334. const memberVariables = this.getMemberVariables();
  11335. const members = Object.entries(memberVariables).map(([name, original]) => {
  11336. if (this.referencedEarly || original.isReassigned) {
  11337. return [
  11338. null,
  11339. `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
  11340. ];
  11341. }
  11342. return [name, original.getName(getPropertyAccess)];
  11343. });
  11344. members.unshift([null, `__proto__:${_}null`]);
  11345. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  11346. if (this.mergedNamespaces.length > 0) {
  11347. const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  11348. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
  11349. }
  11350. else {
  11351. // The helper to merge namespaces will also take care of freezing and toStringTag
  11352. if (namespaceToStringTag) {
  11353. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  11354. }
  11355. if (freeze) {
  11356. output = `/*#__PURE__*/Object.freeze(${output})`;
  11357. }
  11358. }
  11359. const name = this.getName(getPropertyAccess);
  11360. output = `${cnst} ${name}${_}=${_}${output};`;
  11361. if (format === 'system' && exportNamesByVariable.has(this)) {
  11362. output += `${n}${getSystemExportStatement([this], options)};`;
  11363. }
  11364. return output;
  11365. }
  11366. renderFirst() {
  11367. return this.referencedEarly;
  11368. }
  11369. setMergedNamespaces(mergedNamespaces) {
  11370. this.mergedNamespaces = mergedNamespaces;
  11371. const moduleExecIndex = this.context.getModuleExecIndex();
  11372. for (const identifier of this.references) {
  11373. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  11374. this.referencedEarly = true;
  11375. break;
  11376. }
  11377. }
  11378. }
  11379. }
  11380. NamespaceVariable.prototype.isNamespace = true;
  11381. class SyntheticNamedExportVariable extends Variable {
  11382. constructor(context, name, syntheticNamespace) {
  11383. super(name);
  11384. this.baseVariable = null;
  11385. this.context = context;
  11386. this.module = context.module;
  11387. this.syntheticNamespace = syntheticNamespace;
  11388. }
  11389. getBaseVariable() {
  11390. if (this.baseVariable)
  11391. return this.baseVariable;
  11392. let baseVariable = this.syntheticNamespace;
  11393. while (baseVariable instanceof ExportDefaultVariable ||
  11394. baseVariable instanceof SyntheticNamedExportVariable) {
  11395. if (baseVariable instanceof ExportDefaultVariable) {
  11396. const original = baseVariable.getOriginalVariable();
  11397. if (original === baseVariable)
  11398. break;
  11399. baseVariable = original;
  11400. }
  11401. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11402. baseVariable = baseVariable.syntheticNamespace;
  11403. }
  11404. }
  11405. return (this.baseVariable = baseVariable);
  11406. }
  11407. getBaseVariableName() {
  11408. return this.syntheticNamespace.getBaseVariableName();
  11409. }
  11410. getName(getPropertyAccess) {
  11411. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11412. }
  11413. include() {
  11414. this.included = true;
  11415. this.context.includeVariableInModule(this.syntheticNamespace);
  11416. }
  11417. setRenderNames(baseName, name) {
  11418. super.setRenderNames(baseName, name);
  11419. }
  11420. }
  11421. var BuildPhase;
  11422. (function (BuildPhase) {
  11423. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11424. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11425. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11426. })(BuildPhase || (BuildPhase = {}));
  11427. function getId(m) {
  11428. return m.id;
  11429. }
  11430. function getOriginalLocation(sourcemapChain, location) {
  11431. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11432. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11433. const sourcemap = filteredSourcemapChain.pop();
  11434. const line = sourcemap.mappings[location.line - 1];
  11435. if (line) {
  11436. const filteredLine = line.filter((segment) => segment.length > 1);
  11437. const lastSegment = filteredLine[filteredLine.length - 1];
  11438. for (const segment of filteredLine) {
  11439. if (segment[0] >= location.column || segment === lastSegment) {
  11440. location = {
  11441. column: segment[3],
  11442. line: segment[2] + 1
  11443. };
  11444. continue traceSourcemap;
  11445. }
  11446. }
  11447. }
  11448. throw new Error("Can't resolve original location of error.");
  11449. }
  11450. return location;
  11451. }
  11452. const NOOP = () => { };
  11453. let timers = new Map();
  11454. function getPersistedLabel(label, level) {
  11455. switch (level) {
  11456. case 1:
  11457. return `# ${label}`;
  11458. case 2:
  11459. return `## ${label}`;
  11460. case 3:
  11461. return label;
  11462. default:
  11463. return `${' '.repeat(level - 4)}- ${label}`;
  11464. }
  11465. }
  11466. function timeStartImpl(label, level = 3) {
  11467. label = getPersistedLabel(label, level);
  11468. const startMemory = process$1.memoryUsage().heapUsed;
  11469. const startTime = perf_hooks.performance.now();
  11470. const timer = timers.get(label);
  11471. if (timer === undefined) {
  11472. timers.set(label, {
  11473. memory: 0,
  11474. startMemory,
  11475. startTime,
  11476. time: 0,
  11477. totalMemory: 0
  11478. });
  11479. }
  11480. else {
  11481. timer.startMemory = startMemory;
  11482. timer.startTime = startTime;
  11483. }
  11484. }
  11485. function timeEndImpl(label, level = 3) {
  11486. label = getPersistedLabel(label, level);
  11487. const timer = timers.get(label);
  11488. if (timer !== undefined) {
  11489. const currentMemory = process$1.memoryUsage().heapUsed;
  11490. timer.memory += currentMemory - timer.startMemory;
  11491. timer.time += perf_hooks.performance.now() - timer.startTime;
  11492. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  11493. }
  11494. }
  11495. function getTimings() {
  11496. const newTimings = {};
  11497. for (const [label, { memory, time, totalMemory }] of timers) {
  11498. newTimings[label] = [time, memory, totalMemory];
  11499. }
  11500. return newTimings;
  11501. }
  11502. let timeStart = NOOP;
  11503. let timeEnd = NOOP;
  11504. const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
  11505. function getPluginWithTimers(plugin, index) {
  11506. for (const hook of TIMED_PLUGIN_HOOKS) {
  11507. if (hook in plugin) {
  11508. let timerLabel = `plugin ${index}`;
  11509. if (plugin.name) {
  11510. timerLabel += ` (${plugin.name})`;
  11511. }
  11512. timerLabel += ` - ${hook}`;
  11513. const func = plugin[hook];
  11514. plugin[hook] = function (...args) {
  11515. timeStart(timerLabel, 4);
  11516. const result = func.apply(this, args);
  11517. timeEnd(timerLabel, 4);
  11518. if (result && typeof result.then === 'function') {
  11519. timeStart(`${timerLabel} (async)`, 4);
  11520. return result.then((hookResult) => {
  11521. timeEnd(`${timerLabel} (async)`, 4);
  11522. return hookResult;
  11523. });
  11524. }
  11525. return result;
  11526. };
  11527. }
  11528. }
  11529. return plugin;
  11530. }
  11531. function initialiseTimers(inputOptions) {
  11532. if (inputOptions.perf) {
  11533. timers = new Map();
  11534. timeStart = timeStartImpl;
  11535. timeEnd = timeEndImpl;
  11536. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  11537. }
  11538. else {
  11539. timeStart = NOOP;
  11540. timeEnd = NOOP;
  11541. }
  11542. }
  11543. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  11544. baseModule.isExecuted = true;
  11545. const modules = [baseModule];
  11546. const visitedModules = new Set();
  11547. for (const module of modules) {
  11548. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  11549. if (!(dependency instanceof ExternalModule) &&
  11550. !dependency.isExecuted &&
  11551. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  11552. !visitedModules.has(dependency.id)) {
  11553. dependency.isExecuted = true;
  11554. visitedModules.add(dependency.id);
  11555. modules.push(dependency);
  11556. }
  11557. }
  11558. }
  11559. }
  11560. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  11561. identifier: null,
  11562. localName: MISSING_EXPORT_SHIM_VARIABLE
  11563. };
  11564. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  11565. const searchedModules = searchedNamesAndModules.get(name);
  11566. if (searchedModules) {
  11567. if (searchedModules.has(target)) {
  11568. return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
  11569. }
  11570. searchedModules.add(target);
  11571. }
  11572. else {
  11573. searchedNamesAndModules.set(name, new Set([target]));
  11574. }
  11575. return target.getVariableForExportName(name, {
  11576. importerForSideEffects,
  11577. isExportAllSearch,
  11578. searchedNamesAndModules
  11579. });
  11580. }
  11581. function getAndExtendSideEffectModules(variable, module) {
  11582. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  11583. let currentVariable = variable;
  11584. const referencedVariables = new Set([currentVariable]);
  11585. while (true) {
  11586. const importingModule = currentVariable.module;
  11587. currentVariable =
  11588. currentVariable instanceof ExportDefaultVariable
  11589. ? currentVariable.getDirectOriginalVariable()
  11590. : currentVariable instanceof SyntheticNamedExportVariable
  11591. ? currentVariable.syntheticNamespace
  11592. : null;
  11593. if (!currentVariable || referencedVariables.has(currentVariable)) {
  11594. break;
  11595. }
  11596. referencedVariables.add(currentVariable);
  11597. sideEffectModules.add(importingModule);
  11598. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  11599. if (originalSideEffects) {
  11600. for (const module of originalSideEffects) {
  11601. sideEffectModules.add(module);
  11602. }
  11603. }
  11604. }
  11605. return sideEffectModules;
  11606. }
  11607. class Module {
  11608. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
  11609. this.graph = graph;
  11610. this.id = id;
  11611. this.options = options;
  11612. this.alternativeReexportModules = new Map();
  11613. this.chunkFileNames = new Set();
  11614. this.chunkNames = [];
  11615. this.cycles = new Set();
  11616. this.dependencies = new Set();
  11617. this.dynamicDependencies = new Set();
  11618. this.dynamicImporters = [];
  11619. this.dynamicImports = [];
  11620. this.execIndex = Infinity;
  11621. this.implicitlyLoadedAfter = new Set();
  11622. this.implicitlyLoadedBefore = new Set();
  11623. this.importDescriptions = new Map();
  11624. this.importMetas = [];
  11625. this.importedFromNotTreeshaken = false;
  11626. this.importers = [];
  11627. this.includedDynamicImporters = [];
  11628. this.includedImports = new Set();
  11629. this.isExecuted = false;
  11630. this.isUserDefinedEntryPoint = false;
  11631. this.needsExportShim = false;
  11632. this.sideEffectDependenciesByVariable = new Map();
  11633. this.sources = new Set();
  11634. this.usesTopLevelAwait = false;
  11635. this.allExportNames = null;
  11636. this.ast = null;
  11637. this.exportAllModules = [];
  11638. this.exportAllSources = new Set();
  11639. this.exportNamesByVariable = null;
  11640. this.exportShimVariable = new ExportShimVariable(this);
  11641. this.exports = new Map();
  11642. this.namespaceReexportsByName = new Map();
  11643. this.reexportDescriptions = new Map();
  11644. this.relevantDependencies = null;
  11645. this.syntheticExports = new Map();
  11646. this.syntheticNamespace = null;
  11647. this.transformDependencies = [];
  11648. this.transitiveReexports = null;
  11649. this.excludeFromSourcemap = /\0/.test(id);
  11650. this.context = options.moduleContext(id);
  11651. this.preserveSignature = this.options.preserveEntrySignatures;
  11652. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11653. const module = this;
  11654. const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
  11655. this.info = {
  11656. ast: null,
  11657. code: null,
  11658. get dynamicallyImportedIdResolutions() {
  11659. return dynamicImports
  11660. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  11661. .filter(Boolean);
  11662. },
  11663. get dynamicallyImportedIds() {
  11664. // We cannot use this.dynamicDependencies because this is needed before
  11665. // dynamicDependencies are populated
  11666. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  11667. },
  11668. get dynamicImporters() {
  11669. return dynamicImporters.sort();
  11670. },
  11671. get hasDefaultExport() {
  11672. // This information is only valid after parsing
  11673. if (!module.ast) {
  11674. return null;
  11675. }
  11676. return module.exports.has('default') || reexportDescriptions.has('default');
  11677. },
  11678. get hasModuleSideEffects() {
  11679. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  11680. return this.moduleSideEffects;
  11681. },
  11682. id,
  11683. get implicitlyLoadedAfterOneOf() {
  11684. return Array.from(implicitlyLoadedAfter, getId).sort();
  11685. },
  11686. get implicitlyLoadedBefore() {
  11687. return Array.from(implicitlyLoadedBefore, getId).sort();
  11688. },
  11689. get importedIdResolutions() {
  11690. return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
  11691. },
  11692. get importedIds() {
  11693. // We cannot use this.dependencies because this is needed before
  11694. // dependencies are populated
  11695. return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
  11696. },
  11697. get importers() {
  11698. return importers.sort();
  11699. },
  11700. isEntry,
  11701. isExternal: false,
  11702. get isIncluded() {
  11703. if (graph.phase !== BuildPhase.GENERATE) {
  11704. return null;
  11705. }
  11706. return module.isIncluded();
  11707. },
  11708. meta: { ...meta },
  11709. moduleSideEffects,
  11710. syntheticNamedExports
  11711. };
  11712. // Hide the deprecated key so that it only warns when accessed explicitly
  11713. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  11714. enumerable: false
  11715. });
  11716. }
  11717. basename() {
  11718. const base = require$$0.basename(this.id);
  11719. const ext = require$$0.extname(this.id);
  11720. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  11721. }
  11722. bindReferences() {
  11723. this.ast.bind();
  11724. }
  11725. error(props, pos) {
  11726. this.addLocationToLogProps(props, pos);
  11727. return error(props);
  11728. }
  11729. getAllExportNames() {
  11730. if (this.allExportNames) {
  11731. return this.allExportNames;
  11732. }
  11733. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  11734. for (const module of this.exportAllModules) {
  11735. if (module instanceof ExternalModule) {
  11736. this.allExportNames.add(`*${module.id}`);
  11737. continue;
  11738. }
  11739. for (const name of module.getAllExportNames()) {
  11740. if (name !== 'default')
  11741. this.allExportNames.add(name);
  11742. }
  11743. }
  11744. // We do not count the synthetic namespace as a regular export to hide it
  11745. // from entry signatures and namespace objects
  11746. if (typeof this.info.syntheticNamedExports === 'string') {
  11747. this.allExportNames.delete(this.info.syntheticNamedExports);
  11748. }
  11749. return this.allExportNames;
  11750. }
  11751. getDependenciesToBeIncluded() {
  11752. if (this.relevantDependencies)
  11753. return this.relevantDependencies;
  11754. this.relevantDependencies = new Set();
  11755. const necessaryDependencies = new Set();
  11756. const alwaysCheckedDependencies = new Set();
  11757. const dependencyVariables = new Set(this.includedImports);
  11758. if (this.info.isEntry ||
  11759. this.includedDynamicImporters.length > 0 ||
  11760. this.namespace.included ||
  11761. this.implicitlyLoadedAfter.size > 0) {
  11762. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  11763. const [exportedVariable] = this.getVariableForExportName(exportName);
  11764. if (exportedVariable) {
  11765. dependencyVariables.add(exportedVariable);
  11766. }
  11767. }
  11768. }
  11769. for (let variable of dependencyVariables) {
  11770. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  11771. if (sideEffectDependencies) {
  11772. for (const module of sideEffectDependencies) {
  11773. alwaysCheckedDependencies.add(module);
  11774. }
  11775. }
  11776. if (variable instanceof SyntheticNamedExportVariable) {
  11777. variable = variable.getBaseVariable();
  11778. }
  11779. else if (variable instanceof ExportDefaultVariable) {
  11780. variable = variable.getOriginalVariable();
  11781. }
  11782. necessaryDependencies.add(variable.module);
  11783. }
  11784. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  11785. for (const dependency of this.dependencies) {
  11786. this.relevantDependencies.add(dependency);
  11787. }
  11788. }
  11789. else {
  11790. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  11791. }
  11792. for (const dependency of necessaryDependencies) {
  11793. this.relevantDependencies.add(dependency);
  11794. }
  11795. return this.relevantDependencies;
  11796. }
  11797. getExportNamesByVariable() {
  11798. if (this.exportNamesByVariable) {
  11799. return this.exportNamesByVariable;
  11800. }
  11801. const exportNamesByVariable = new Map();
  11802. for (const exportName of this.getAllExportNames()) {
  11803. let [tracedVariable] = this.getVariableForExportName(exportName);
  11804. if (tracedVariable instanceof ExportDefaultVariable) {
  11805. tracedVariable = tracedVariable.getOriginalVariable();
  11806. }
  11807. if (!tracedVariable ||
  11808. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  11809. continue;
  11810. }
  11811. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  11812. if (existingExportNames) {
  11813. existingExportNames.push(exportName);
  11814. }
  11815. else {
  11816. exportNamesByVariable.set(tracedVariable, [exportName]);
  11817. }
  11818. }
  11819. return (this.exportNamesByVariable = exportNamesByVariable);
  11820. }
  11821. getExports() {
  11822. return Array.from(this.exports.keys());
  11823. }
  11824. getReexports() {
  11825. if (this.transitiveReexports) {
  11826. return this.transitiveReexports;
  11827. }
  11828. // to avoid infinite recursion when using circular `export * from X`
  11829. this.transitiveReexports = [];
  11830. const reexports = new Set(this.reexportDescriptions.keys());
  11831. for (const module of this.exportAllModules) {
  11832. if (module instanceof ExternalModule) {
  11833. reexports.add(`*${module.id}`);
  11834. }
  11835. else {
  11836. for (const name of [...module.getReexports(), ...module.getExports()]) {
  11837. if (name !== 'default')
  11838. reexports.add(name);
  11839. }
  11840. }
  11841. }
  11842. return (this.transitiveReexports = [...reexports]);
  11843. }
  11844. getRenderedExports() {
  11845. // only direct exports are counted here, not reexports at all
  11846. const renderedExports = [];
  11847. const removedExports = [];
  11848. for (const exportName of this.exports.keys()) {
  11849. const [variable] = this.getVariableForExportName(exportName);
  11850. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  11851. }
  11852. return { removedExports, renderedExports };
  11853. }
  11854. getSyntheticNamespace() {
  11855. if (this.syntheticNamespace === null) {
  11856. this.syntheticNamespace = undefined;
  11857. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  11858. ? this.info.syntheticNamedExports
  11859. : 'default', { onlyExplicit: true });
  11860. }
  11861. if (!this.syntheticNamespace) {
  11862. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  11863. }
  11864. return this.syntheticNamespace;
  11865. }
  11866. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  11867. var _a;
  11868. if (name[0] === '*') {
  11869. if (name.length === 1) {
  11870. // export * from './other'
  11871. return [this.namespace];
  11872. }
  11873. // export * from 'external'
  11874. const module = this.graph.modulesById.get(name.slice(1));
  11875. return module.getVariableForExportName('*');
  11876. }
  11877. // export { foo } from './other'
  11878. const reexportDeclaration = this.reexportDescriptions.get(name);
  11879. if (reexportDeclaration) {
  11880. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  11881. if (!variable) {
  11882. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  11883. }
  11884. if (importerForSideEffects) {
  11885. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11886. }
  11887. return [variable];
  11888. }
  11889. const exportDeclaration = this.exports.get(name);
  11890. if (exportDeclaration) {
  11891. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  11892. return [this.exportShimVariable];
  11893. }
  11894. const name = exportDeclaration.localName;
  11895. const variable = this.traceVariable(name, {
  11896. importerForSideEffects,
  11897. searchedNamesAndModules
  11898. });
  11899. if (importerForSideEffects) {
  11900. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  11901. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11902. }
  11903. return [variable];
  11904. }
  11905. if (onlyExplicit) {
  11906. return [null];
  11907. }
  11908. if (name !== 'default') {
  11909. const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  11910. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  11911. if (foundNamespaceReexport[0]) {
  11912. return foundNamespaceReexport;
  11913. }
  11914. }
  11915. if (this.info.syntheticNamedExports) {
  11916. return [
  11917. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  11918. ];
  11919. }
  11920. // we don't want to create shims when we are just
  11921. // probing export * modules for exports
  11922. if (!isExportAllSearch) {
  11923. if (this.options.shimMissingExports) {
  11924. this.shimMissingExport(name);
  11925. return [this.exportShimVariable];
  11926. }
  11927. }
  11928. return [null];
  11929. }
  11930. hasEffects() {
  11931. return (this.info.moduleSideEffects === 'no-treeshake' ||
  11932. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  11933. }
  11934. include() {
  11935. const context = createInclusionContext();
  11936. if (this.ast.shouldBeIncluded(context))
  11937. this.ast.include(context, false);
  11938. }
  11939. includeAllExports(includeNamespaceMembers) {
  11940. if (!this.isExecuted) {
  11941. markModuleAndImpureDependenciesAsExecuted(this);
  11942. this.graph.needsTreeshakingPass = true;
  11943. }
  11944. for (const exportName of this.exports.keys()) {
  11945. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  11946. const variable = this.getVariableForExportName(exportName)[0];
  11947. variable.deoptimizePath(UNKNOWN_PATH);
  11948. if (!variable.included) {
  11949. this.includeVariable(variable);
  11950. }
  11951. }
  11952. }
  11953. for (const name of this.getReexports()) {
  11954. const [variable] = this.getVariableForExportName(name);
  11955. if (variable) {
  11956. variable.deoptimizePath(UNKNOWN_PATH);
  11957. if (!variable.included) {
  11958. this.includeVariable(variable);
  11959. }
  11960. if (variable instanceof ExternalVariable) {
  11961. variable.module.reexported = true;
  11962. }
  11963. }
  11964. }
  11965. if (includeNamespaceMembers) {
  11966. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  11967. }
  11968. }
  11969. includeAllInBundle() {
  11970. this.ast.include(createInclusionContext(), true);
  11971. this.includeAllExports(false);
  11972. }
  11973. isIncluded() {
  11974. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  11975. }
  11976. linkImports() {
  11977. this.addModulesToImportDescriptions(this.importDescriptions);
  11978. this.addModulesToImportDescriptions(this.reexportDescriptions);
  11979. const externalExportAllModules = [];
  11980. for (const source of this.exportAllSources) {
  11981. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  11982. if (module instanceof ExternalModule) {
  11983. externalExportAllModules.push(module);
  11984. continue;
  11985. }
  11986. this.exportAllModules.push(module);
  11987. }
  11988. this.exportAllModules.push(...externalExportAllModules);
  11989. }
  11990. render(options) {
  11991. const magicString = this.magicString.clone();
  11992. this.ast.render(magicString, options);
  11993. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  11994. return magicString;
  11995. }
  11996. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  11997. this.info.code = code;
  11998. this.originalCode = originalCode;
  11999. this.originalSourcemap = originalSourcemap;
  12000. this.sourcemapChain = sourcemapChain;
  12001. if (transformFiles) {
  12002. this.transformFiles = transformFiles;
  12003. }
  12004. this.transformDependencies = transformDependencies;
  12005. this.customTransformCache = customTransformCache;
  12006. this.updateOptions(moduleOptions);
  12007. timeStart('generate ast', 3);
  12008. if (!ast) {
  12009. ast = this.tryParse();
  12010. }
  12011. timeEnd('generate ast', 3);
  12012. this.resolvedIds = resolvedIds || Object.create(null);
  12013. // By default, `id` is the file name. Custom resolvers and loaders
  12014. // can change that, but it makes sense to use it for the source file name
  12015. const fileName = this.id;
  12016. this.magicString = new MagicString(code, {
  12017. filename: (this.excludeFromSourcemap ? null : fileName),
  12018. indentExclusionRanges: []
  12019. });
  12020. timeStart('analyse ast', 3);
  12021. this.astContext = {
  12022. addDynamicImport: this.addDynamicImport.bind(this),
  12023. addExport: this.addExport.bind(this),
  12024. addImport: this.addImport.bind(this),
  12025. addImportMeta: this.addImportMeta.bind(this),
  12026. code,
  12027. deoptimizationTracker: this.graph.deoptimizationTracker,
  12028. error: this.error.bind(this),
  12029. fileName,
  12030. getExports: this.getExports.bind(this),
  12031. getModuleExecIndex: () => this.execIndex,
  12032. getModuleName: this.basename.bind(this),
  12033. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  12034. getReexports: this.getReexports.bind(this),
  12035. importDescriptions: this.importDescriptions,
  12036. includeAllExports: () => this.includeAllExports(true),
  12037. includeDynamicImport: this.includeDynamicImport.bind(this),
  12038. includeVariableInModule: this.includeVariableInModule.bind(this),
  12039. magicString: this.magicString,
  12040. module: this,
  12041. moduleContext: this.context,
  12042. options: this.options,
  12043. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  12044. traceExport: (name) => this.getVariableForExportName(name)[0],
  12045. traceVariable: this.traceVariable.bind(this),
  12046. usesTopLevelAwait: false,
  12047. warn: this.warn.bind(this)
  12048. };
  12049. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  12050. this.namespace = new NamespaceVariable(this.astContext);
  12051. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  12052. this.info.ast = ast;
  12053. timeEnd('analyse ast', 3);
  12054. }
  12055. toJSON() {
  12056. return {
  12057. ast: this.ast.esTreeNode,
  12058. code: this.info.code,
  12059. customTransformCache: this.customTransformCache,
  12060. dependencies: Array.from(this.dependencies, getId),
  12061. id: this.id,
  12062. meta: this.info.meta,
  12063. moduleSideEffects: this.info.moduleSideEffects,
  12064. originalCode: this.originalCode,
  12065. originalSourcemap: this.originalSourcemap,
  12066. resolvedIds: this.resolvedIds,
  12067. sourcemapChain: this.sourcemapChain,
  12068. syntheticNamedExports: this.info.syntheticNamedExports,
  12069. transformDependencies: this.transformDependencies,
  12070. transformFiles: this.transformFiles
  12071. };
  12072. }
  12073. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  12074. const localVariable = this.scope.variables.get(name);
  12075. if (localVariable) {
  12076. return localVariable;
  12077. }
  12078. const importDeclaration = this.importDescriptions.get(name);
  12079. if (importDeclaration) {
  12080. const otherModule = importDeclaration.module;
  12081. if (otherModule instanceof Module && importDeclaration.name === '*') {
  12082. return otherModule.namespace;
  12083. }
  12084. const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  12085. if (!declaration) {
  12086. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  12087. }
  12088. return declaration;
  12089. }
  12090. return null;
  12091. }
  12092. tryParse() {
  12093. try {
  12094. return this.graph.contextParse(this.info.code);
  12095. }
  12096. catch (err) {
  12097. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  12098. if (this.id.endsWith('.json')) {
  12099. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  12100. }
  12101. else if (!this.id.endsWith('.js')) {
  12102. message += ' (Note that you need plugins to import files that are not JavaScript)';
  12103. }
  12104. return this.error({
  12105. code: 'PARSE_ERROR',
  12106. message,
  12107. parserError: err
  12108. }, err.pos);
  12109. }
  12110. }
  12111. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  12112. if (moduleSideEffects != null) {
  12113. this.info.moduleSideEffects = moduleSideEffects;
  12114. }
  12115. if (syntheticNamedExports != null) {
  12116. this.info.syntheticNamedExports = syntheticNamedExports;
  12117. }
  12118. if (meta != null) {
  12119. Object.assign(this.info.meta, meta);
  12120. }
  12121. }
  12122. warn(props, pos) {
  12123. this.addLocationToLogProps(props, pos);
  12124. this.options.onwarn(props);
  12125. }
  12126. addDynamicImport(node) {
  12127. let argument = node.source;
  12128. if (argument instanceof TemplateLiteral) {
  12129. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  12130. argument = argument.quasis[0].value.cooked;
  12131. }
  12132. }
  12133. else if (argument instanceof Literal && typeof argument.value === 'string') {
  12134. argument = argument.value;
  12135. }
  12136. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  12137. }
  12138. addExport(node) {
  12139. if (node instanceof ExportDefaultDeclaration) {
  12140. // export default foo;
  12141. this.exports.set('default', {
  12142. identifier: node.variable.getAssignedVariableName(),
  12143. localName: 'default'
  12144. });
  12145. }
  12146. else if (node instanceof ExportAllDeclaration) {
  12147. const source = node.source.value;
  12148. this.sources.add(source);
  12149. if (node.exported) {
  12150. // export * as name from './other'
  12151. const name = node.exported.name;
  12152. this.reexportDescriptions.set(name, {
  12153. localName: '*',
  12154. module: null,
  12155. source,
  12156. start: node.start
  12157. });
  12158. }
  12159. else {
  12160. // export * from './other'
  12161. this.exportAllSources.add(source);
  12162. }
  12163. }
  12164. else if (node.source instanceof Literal) {
  12165. // export { name } from './other'
  12166. const source = node.source.value;
  12167. this.sources.add(source);
  12168. for (const specifier of node.specifiers) {
  12169. const name = specifier.exported.name;
  12170. this.reexportDescriptions.set(name, {
  12171. localName: specifier.local.name,
  12172. module: null,
  12173. source,
  12174. start: specifier.start
  12175. });
  12176. }
  12177. }
  12178. else if (node.declaration) {
  12179. const declaration = node.declaration;
  12180. if (declaration instanceof VariableDeclaration) {
  12181. // export var { foo, bar } = ...
  12182. // export var foo = 1, bar = 2;
  12183. for (const declarator of declaration.declarations) {
  12184. for (const localName of extractAssignedNames(declarator.id)) {
  12185. this.exports.set(localName, { identifier: null, localName });
  12186. }
  12187. }
  12188. }
  12189. else {
  12190. // export function foo () {}
  12191. const localName = declaration.id.name;
  12192. this.exports.set(localName, { identifier: null, localName });
  12193. }
  12194. }
  12195. else {
  12196. // export { foo, bar, baz }
  12197. for (const specifier of node.specifiers) {
  12198. const localName = specifier.local.name;
  12199. const exportedName = specifier.exported.name;
  12200. this.exports.set(exportedName, { identifier: null, localName });
  12201. }
  12202. }
  12203. }
  12204. addImport(node) {
  12205. const source = node.source.value;
  12206. this.sources.add(source);
  12207. for (const specifier of node.specifiers) {
  12208. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  12209. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  12210. const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
  12211. this.importDescriptions.set(specifier.local.name, {
  12212. module: null,
  12213. name,
  12214. source,
  12215. start: specifier.start
  12216. });
  12217. }
  12218. }
  12219. addImportMeta(node) {
  12220. this.importMetas.push(node);
  12221. }
  12222. addLocationToLogProps(props, pos) {
  12223. props.id = this.id;
  12224. props.pos = pos;
  12225. let code = this.info.code;
  12226. const location = locate(code, pos, { offsetLine: 1 });
  12227. if (location) {
  12228. let { column, line } = location;
  12229. try {
  12230. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  12231. code = this.originalCode;
  12232. }
  12233. catch (err) {
  12234. this.options.onwarn({
  12235. code: 'SOURCEMAP_ERROR',
  12236. id: this.id,
  12237. loc: {
  12238. column,
  12239. file: this.id,
  12240. line
  12241. },
  12242. message: `Error when using sourcemap for reporting an error: ${err.message}`,
  12243. pos
  12244. });
  12245. }
  12246. augmentCodeLocation(props, { column, line }, code, this.id);
  12247. }
  12248. }
  12249. addModulesToImportDescriptions(importDescription) {
  12250. for (const specifier of importDescription.values()) {
  12251. const { id } = this.resolvedIds[specifier.source];
  12252. specifier.module = this.graph.modulesById.get(id);
  12253. }
  12254. }
  12255. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  12256. const handledDependencies = new Set();
  12257. const addSideEffectDependencies = (possibleDependencies) => {
  12258. for (const dependency of possibleDependencies) {
  12259. if (handledDependencies.has(dependency)) {
  12260. continue;
  12261. }
  12262. handledDependencies.add(dependency);
  12263. if (necessaryDependencies.has(dependency)) {
  12264. relevantDependencies.add(dependency);
  12265. continue;
  12266. }
  12267. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  12268. continue;
  12269. }
  12270. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  12271. relevantDependencies.add(dependency);
  12272. continue;
  12273. }
  12274. addSideEffectDependencies(dependency.dependencies);
  12275. }
  12276. };
  12277. addSideEffectDependencies(this.dependencies);
  12278. addSideEffectDependencies(alwaysCheckedDependencies);
  12279. }
  12280. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  12281. let foundSyntheticDeclaration = null;
  12282. const foundInternalDeclarations = new Map();
  12283. const foundExternalDeclarations = new Set();
  12284. for (const module of this.exportAllModules) {
  12285. // Synthetic namespaces should not hide "regular" exports of the same name
  12286. if (module.info.syntheticNamedExports === name) {
  12287. continue;
  12288. }
  12289. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  12290. // We are creating a copy to handle the case where the same binding is
  12291. // imported through different namespace reexports gracefully
  12292. copyNameToModulesMap(searchedNamesAndModules));
  12293. if (module instanceof ExternalModule || indirectExternal) {
  12294. foundExternalDeclarations.add(variable);
  12295. }
  12296. else if (variable instanceof SyntheticNamedExportVariable) {
  12297. if (!foundSyntheticDeclaration) {
  12298. foundSyntheticDeclaration = variable;
  12299. }
  12300. }
  12301. else if (variable) {
  12302. foundInternalDeclarations.set(variable, module);
  12303. }
  12304. }
  12305. if (foundInternalDeclarations.size > 0) {
  12306. const foundDeclarationList = [...foundInternalDeclarations];
  12307. const usedDeclaration = foundDeclarationList[0][0];
  12308. if (foundDeclarationList.length === 1) {
  12309. return [usedDeclaration];
  12310. }
  12311. this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  12312. // TODO we are pretending it was not found while it should behave like "undefined"
  12313. return [null];
  12314. }
  12315. if (foundExternalDeclarations.size > 0) {
  12316. const foundDeclarationList = [...foundExternalDeclarations];
  12317. const usedDeclaration = foundDeclarationList[0];
  12318. if (foundDeclarationList.length > 1) {
  12319. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  12320. }
  12321. return [usedDeclaration, true];
  12322. }
  12323. if (foundSyntheticDeclaration) {
  12324. return [foundSyntheticDeclaration];
  12325. }
  12326. return [null];
  12327. }
  12328. includeAndGetAdditionalMergedNamespaces() {
  12329. const externalNamespaces = new Set();
  12330. const syntheticNamespaces = new Set();
  12331. for (const module of [this, ...this.exportAllModules]) {
  12332. if (module instanceof ExternalModule) {
  12333. const [externalVariable] = module.getVariableForExportName('*');
  12334. externalVariable.include();
  12335. this.includedImports.add(externalVariable);
  12336. externalNamespaces.add(externalVariable);
  12337. }
  12338. else if (module.info.syntheticNamedExports) {
  12339. const syntheticNamespace = module.getSyntheticNamespace();
  12340. syntheticNamespace.include();
  12341. this.includedImports.add(syntheticNamespace);
  12342. syntheticNamespaces.add(syntheticNamespace);
  12343. }
  12344. }
  12345. return [...syntheticNamespaces, ...externalNamespaces];
  12346. }
  12347. includeDynamicImport(node) {
  12348. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  12349. if (resolution instanceof Module) {
  12350. resolution.includedDynamicImporters.push(this);
  12351. resolution.includeAllExports(true);
  12352. }
  12353. }
  12354. includeVariable(variable) {
  12355. if (!variable.included) {
  12356. variable.include();
  12357. this.graph.needsTreeshakingPass = true;
  12358. const variableModule = variable.module;
  12359. if (variableModule instanceof Module) {
  12360. if (!variableModule.isExecuted) {
  12361. markModuleAndImpureDependenciesAsExecuted(variableModule);
  12362. }
  12363. if (variableModule !== this) {
  12364. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  12365. for (const module of sideEffectModules) {
  12366. if (!module.isExecuted) {
  12367. markModuleAndImpureDependenciesAsExecuted(module);
  12368. }
  12369. }
  12370. }
  12371. }
  12372. }
  12373. }
  12374. includeVariableInModule(variable) {
  12375. this.includeVariable(variable);
  12376. const variableModule = variable.module;
  12377. if (variableModule && variableModule !== this) {
  12378. this.includedImports.add(variable);
  12379. }
  12380. }
  12381. shimMissingExport(name) {
  12382. this.options.onwarn({
  12383. code: 'SHIMMED_EXPORT',
  12384. exporter: relativeId(this.id),
  12385. exportName: name,
  12386. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  12387. });
  12388. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  12389. }
  12390. }
  12391. // if there is a cyclic import in the reexport chain, we should not
  12392. // import from the original module but from the cyclic module to not
  12393. // mess up execution order.
  12394. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  12395. if (variable.module instanceof Module && variable.module !== reexporter) {
  12396. const exporterCycles = variable.module.cycles;
  12397. if (exporterCycles.size > 0) {
  12398. const importerCycles = reexporter.cycles;
  12399. for (const cycleSymbol of importerCycles) {
  12400. if (exporterCycles.has(cycleSymbol)) {
  12401. importer.alternativeReexportModules.set(variable, reexporter);
  12402. break;
  12403. }
  12404. }
  12405. }
  12406. }
  12407. }
  12408. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  12409. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  12410. function removeJsExtension(name) {
  12411. return name.endsWith('.js') ? name.slice(0, -3) : name;
  12412. }
  12413. function getCompleteAmdId(options, chunkId) {
  12414. if (options.autoId) {
  12415. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  12416. }
  12417. return options.id || '';
  12418. }
  12419. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  12420. const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  12421. if (!namedExportsMode) {
  12422. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  12423. }
  12424. let exportBlock = '';
  12425. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12426. if (reexports && namedExportsMode) {
  12427. for (const specifier of reexports) {
  12428. if (specifier.reexported !== '*') {
  12429. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12430. if (exportBlock)
  12431. exportBlock += n;
  12432. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  12433. const [left, right] = getDirectReturnFunction([], {
  12434. functionReturn: true,
  12435. lineBreakIndent: null,
  12436. name: null
  12437. });
  12438. exportBlock +=
  12439. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  12440. `${t}enumerable:${_}true,${n}` +
  12441. `${t}get:${_}${left}${importName}${right}${n}});`;
  12442. }
  12443. else {
  12444. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  12445. }
  12446. }
  12447. }
  12448. }
  12449. }
  12450. for (const { exported, local } of exports) {
  12451. const lhs = `exports${getPropertyAccess(exported)}`;
  12452. const rhs = local;
  12453. if (lhs !== rhs) {
  12454. if (exportBlock)
  12455. exportBlock += n;
  12456. exportBlock += `${lhs}${_}=${_}${rhs};`;
  12457. }
  12458. }
  12459. for (const { name, reexports } of dependencies) {
  12460. if (reexports && namedExportsMode) {
  12461. for (const specifier of reexports) {
  12462. if (specifier.reexported === '*') {
  12463. if (exportBlock)
  12464. exportBlock += n;
  12465. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  12466. exportBlock +=
  12467. cnst === 'var' && specifier.needsLiveBinding
  12468. ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  12469. isAsync: false,
  12470. name: null
  12471. })}${copyPropertyIfNecessary});`
  12472. : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
  12473. }
  12474. }
  12475. }
  12476. }
  12477. if (exportBlock) {
  12478. return `${n}${n}${exportBlock}`;
  12479. }
  12480. return '';
  12481. }
  12482. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  12483. if (exports.length > 0) {
  12484. return exports[0].local;
  12485. }
  12486. else {
  12487. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12488. if (reexports) {
  12489. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12490. }
  12491. }
  12492. }
  12493. }
  12494. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  12495. if (imported === 'default') {
  12496. if (!isChunk) {
  12497. const moduleInterop = String(interop(moduleId));
  12498. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  12499. ? defaultVariableName
  12500. : moduleVariableName;
  12501. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  12502. ? `${variableName}${getPropertyAccess('default')}`
  12503. : variableName;
  12504. }
  12505. return depNamedExportsMode
  12506. ? `${moduleVariableName}${getPropertyAccess('default')}`
  12507. : moduleVariableName;
  12508. }
  12509. if (imported === '*') {
  12510. return (isChunk
  12511. ? !depNamedExportsMode
  12512. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  12513. ? namespaceVariableName
  12514. : moduleVariableName;
  12515. }
  12516. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  12517. }
  12518. function getEsModuleValue(getObject) {
  12519. return getObject([['value', 'true']], {
  12520. lineBreakIndent: null
  12521. });
  12522. }
  12523. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  12524. if (hasNamedExports) {
  12525. if (addEsModule) {
  12526. if (addNamespaceToStringTag) {
  12527. return `Object.defineProperties(exports,${_}${getObject([
  12528. ['__esModule', getEsModuleValue(getObject)],
  12529. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  12530. ], {
  12531. lineBreakIndent: null
  12532. })});`;
  12533. }
  12534. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  12535. }
  12536. if (addNamespaceToStringTag) {
  12537. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  12538. }
  12539. }
  12540. return '';
  12541. }
  12542. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  12543. if (needsLiveBinding) {
  12544. const [left, right] = getDirectReturnFunction([], {
  12545. functionReturn: true,
  12546. lineBreakIndent: null,
  12547. name: null
  12548. });
  12549. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  12550. `${t}${t}enumerable:${_}true,${n}` +
  12551. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  12552. }
  12553. return `exports[k]${_}=${_}${name}[k]`;
  12554. };
  12555. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  12556. const { _, cnst, n } = snippets;
  12557. const neededInteropHelpers = new Set();
  12558. const interopStatements = [];
  12559. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  12560. neededInteropHelpers.add(helper);
  12561. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  12562. };
  12563. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12564. if (isChunk) {
  12565. for (const { imported, reexported } of [
  12566. ...(imports || []),
  12567. ...(reexports || [])
  12568. ]) {
  12569. if (imported === '*' && reexported !== '*') {
  12570. if (!namedExportsMode) {
  12571. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  12572. }
  12573. break;
  12574. }
  12575. }
  12576. }
  12577. else {
  12578. const moduleInterop = String(interop(id));
  12579. let hasDefault = false;
  12580. let hasNamespace = false;
  12581. for (const { imported, reexported } of [
  12582. ...(imports || []),
  12583. ...(reexports || [])
  12584. ]) {
  12585. let helper;
  12586. let variableName;
  12587. if (imported === 'default') {
  12588. if (!hasDefault) {
  12589. hasDefault = true;
  12590. if (defaultVariableName !== namespaceVariableName) {
  12591. variableName = defaultVariableName;
  12592. helper = defaultInteropHelpersByInteropType[moduleInterop];
  12593. }
  12594. }
  12595. }
  12596. else if (imported === '*' && reexported !== '*') {
  12597. if (!hasNamespace) {
  12598. hasNamespace = true;
  12599. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  12600. variableName = namespaceVariableName;
  12601. }
  12602. }
  12603. if (helper) {
  12604. addInteropStatement(variableName, helper, name);
  12605. }
  12606. }
  12607. }
  12608. }
  12609. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  12610. }
  12611. function addJsExtension(name) {
  12612. return name.endsWith('.js') ? name : name + '.js';
  12613. }
  12614. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  12615. // The assumption is that this makes sense for all relative ids:
  12616. // https://requirejs.org/docs/api.html#jsfiles
  12617. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  12618. if (id[0] !== '.') {
  12619. return id;
  12620. }
  12621. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  12622. }
  12623. const builtins = {
  12624. assert: true,
  12625. buffer: true,
  12626. console: true,
  12627. constants: true,
  12628. domain: true,
  12629. events: true,
  12630. http: true,
  12631. https: true,
  12632. os: true,
  12633. path: true,
  12634. process: true,
  12635. punycode: true,
  12636. querystring: true,
  12637. stream: true,
  12638. string_decoder: true,
  12639. timers: true,
  12640. tty: true,
  12641. url: true,
  12642. util: true,
  12643. vm: true,
  12644. zlib: true
  12645. };
  12646. function warnOnBuiltins(warn, dependencies) {
  12647. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  12648. if (!externalBuiltins.length)
  12649. return;
  12650. warn({
  12651. code: 'MISSING_NODE_BUILTINS',
  12652. 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`,
  12653. modules: externalBuiltins
  12654. });
  12655. }
  12656. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12657. warnOnBuiltins(warn, dependencies);
  12658. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
  12659. const args = dependencies.map(m => m.name);
  12660. const { n, getNonArrowFunctionIntro, _ } = snippets;
  12661. if (namedExportsMode && hasExports) {
  12662. args.unshift(`exports`);
  12663. deps.unshift(`'exports'`);
  12664. }
  12665. if (accessedGlobals.has('require')) {
  12666. args.unshift('require');
  12667. deps.unshift(`'require'`);
  12668. }
  12669. if (accessedGlobals.has('module')) {
  12670. args.unshift('module');
  12671. deps.unshift(`'module'`);
  12672. }
  12673. const completeAmdId = getCompleteAmdId(amd, id);
  12674. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12675. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  12676. const useStrict = strict ? `${_}'use strict';` : '';
  12677. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  12678. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12679. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12680. if (namespaceMarkers) {
  12681. namespaceMarkers = n + n + namespaceMarkers;
  12682. }
  12683. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12684. return (magicString
  12685. .indent(t)
  12686. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12687. // cf. https://v8.dev/blog/preparser#pife
  12688. .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
  12689. isAsync: false,
  12690. name: null
  12691. })}{${useStrict}${n}${n}`)
  12692. .append(`${n}${n}}));`));
  12693. }
  12694. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12695. const { _, n } = snippets;
  12696. const useStrict = strict ? `'use strict';${n}${n}` : '';
  12697. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12698. if (namespaceMarkers) {
  12699. namespaceMarkers += n + n;
  12700. }
  12701. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  12702. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12703. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  12704. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  12705. return magicString.append(`${exportBlock}${outro}`);
  12706. }
  12707. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  12708. let importBlock = '';
  12709. let definingVariable = false;
  12710. for (const { id, name, reexports, imports } of dependencies) {
  12711. if (!reexports && !imports) {
  12712. if (importBlock) {
  12713. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  12714. }
  12715. definingVariable = false;
  12716. importBlock += `require('${id}')`;
  12717. }
  12718. else {
  12719. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  12720. definingVariable = true;
  12721. importBlock += `${name}${_}=${_}require('${id}')`;
  12722. }
  12723. }
  12724. if (importBlock) {
  12725. return `${importBlock};${n}${n}`;
  12726. }
  12727. return '';
  12728. }
  12729. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  12730. const { _, n } = snippets;
  12731. const importBlock = getImportBlock(dependencies, _);
  12732. if (importBlock.length > 0)
  12733. intro += importBlock.join(n) + n + n;
  12734. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  12735. if (intro)
  12736. magicString.prepend(intro);
  12737. const exportBlock = getExportBlock(exports, snippets);
  12738. if (exportBlock.length)
  12739. magicString.append(n + n + exportBlock.join(n).trim());
  12740. if (outro)
  12741. magicString.append(outro);
  12742. return magicString.trim();
  12743. }
  12744. function getImportBlock(dependencies, _) {
  12745. const importBlock = [];
  12746. for (const { id, reexports, imports, name } of dependencies) {
  12747. if (!reexports && !imports) {
  12748. importBlock.push(`import${_}'${id}';`);
  12749. continue;
  12750. }
  12751. if (imports) {
  12752. let defaultImport = null;
  12753. let starImport = null;
  12754. const importedNames = [];
  12755. for (const specifier of imports) {
  12756. if (specifier.imported === 'default') {
  12757. defaultImport = specifier;
  12758. }
  12759. else if (specifier.imported === '*') {
  12760. starImport = specifier;
  12761. }
  12762. else {
  12763. importedNames.push(specifier);
  12764. }
  12765. }
  12766. if (starImport) {
  12767. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  12768. }
  12769. if (defaultImport && importedNames.length === 0) {
  12770. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  12771. }
  12772. else if (importedNames.length > 0) {
  12773. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  12774. .map(specifier => {
  12775. if (specifier.imported === specifier.local) {
  12776. return specifier.imported;
  12777. }
  12778. else {
  12779. return `${specifier.imported} as ${specifier.local}`;
  12780. }
  12781. })
  12782. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12783. }
  12784. }
  12785. if (reexports) {
  12786. let starExport = null;
  12787. const namespaceReexports = [];
  12788. const namedReexports = [];
  12789. for (const specifier of reexports) {
  12790. if (specifier.reexported === '*') {
  12791. starExport = specifier;
  12792. }
  12793. else if (specifier.imported === '*') {
  12794. namespaceReexports.push(specifier);
  12795. }
  12796. else {
  12797. namedReexports.push(specifier);
  12798. }
  12799. }
  12800. if (starExport) {
  12801. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  12802. }
  12803. if (namespaceReexports.length > 0) {
  12804. if (!imports ||
  12805. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  12806. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  12807. }
  12808. for (const specifier of namespaceReexports) {
  12809. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  12810. }
  12811. }
  12812. if (namedReexports.length > 0) {
  12813. importBlock.push(`export${_}{${_}${namedReexports
  12814. .map(specifier => {
  12815. if (specifier.imported === specifier.reexported) {
  12816. return specifier.imported;
  12817. }
  12818. else {
  12819. return `${specifier.imported} as ${specifier.reexported}`;
  12820. }
  12821. })
  12822. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12823. }
  12824. }
  12825. }
  12826. return importBlock;
  12827. }
  12828. function getExportBlock(exports, { _, cnst }) {
  12829. const exportBlock = [];
  12830. const exportDeclaration = [];
  12831. for (const specifier of exports) {
  12832. if (specifier.expression) {
  12833. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  12834. }
  12835. exportDeclaration.push(specifier.exported === specifier.local
  12836. ? specifier.local
  12837. : `${specifier.local} as ${specifier.exported}`);
  12838. }
  12839. if (exportDeclaration.length) {
  12840. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  12841. }
  12842. return exportBlock;
  12843. }
  12844. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  12845. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  12846. const parts = name.split('.');
  12847. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12848. parts.pop();
  12849. let propertyPath = root;
  12850. return (parts
  12851. .map(part => {
  12852. propertyPath += getPropertyAccess(part);
  12853. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  12854. })
  12855. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  12856. }
  12857. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  12858. const parts = deepName.split('.');
  12859. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12860. const last = parts.pop();
  12861. let propertyPath = root;
  12862. let deepAssignment = parts
  12863. .map(part => {
  12864. propertyPath += getPropertyAccess(part);
  12865. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  12866. })
  12867. .concat(`${propertyPath}${getPropertyAccess(last)}`)
  12868. .join(`,${_}`) + `${_}=${_}${assignment}`;
  12869. if (parts.length > 0) {
  12870. deepAssignment = `(${deepAssignment})`;
  12871. }
  12872. return deepAssignment;
  12873. }
  12874. function trimEmptyImports(dependencies) {
  12875. let i = dependencies.length;
  12876. while (i--) {
  12877. const { imports, reexports } = dependencies[i];
  12878. if (imports || reexports) {
  12879. return dependencies.slice(0, i + 1);
  12880. }
  12881. }
  12882. return [];
  12883. }
  12884. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  12885. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  12886. const isNamespaced = name && name.includes('.');
  12887. const useVariableAssignment = !extend && !isNamespaced;
  12888. if (name && useVariableAssignment && !isLegal(name)) {
  12889. return error({
  12890. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  12891. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  12892. });
  12893. }
  12894. warnOnBuiltins(warn, dependencies);
  12895. const external = trimEmptyImports(dependencies);
  12896. const deps = external.map(dep => dep.globalName || 'null');
  12897. const args = external.map(m => m.name);
  12898. if (hasExports && !name) {
  12899. warn({
  12900. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12901. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  12902. });
  12903. }
  12904. if (namedExportsMode && hasExports) {
  12905. if (extend) {
  12906. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  12907. args.unshift('exports');
  12908. }
  12909. else {
  12910. deps.unshift('{}');
  12911. args.unshift('exports');
  12912. }
  12913. }
  12914. const useStrict = strict ? `${t}'use strict';${n}` : '';
  12915. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12916. magicString.prepend(`${intro}${interopBlock}`);
  12917. let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
  12918. isAsync: false,
  12919. name: null
  12920. })}{${n}${useStrict}${n}`;
  12921. if (hasExports) {
  12922. if (name && !(extend && namedExportsMode)) {
  12923. wrapperIntro =
  12924. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  12925. `${_}=${_}${wrapperIntro}`;
  12926. }
  12927. if (isNamespaced) {
  12928. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  12929. }
  12930. }
  12931. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  12932. if (hasExports && !extend && namedExportsMode) {
  12933. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  12934. }
  12935. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12936. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  12937. if (namespaceMarkers) {
  12938. namespaceMarkers = n + n + namespaceMarkers;
  12939. }
  12940. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12941. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  12942. }
  12943. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  12944. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  12945. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  12946. const registeredName = name ? `'${name}',${_}` : '';
  12947. const wrapperParams = accessedGlobals.has('module')
  12948. ? ['exports', 'module']
  12949. : hasExports
  12950. ? ['exports']
  12951. : [];
  12952. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12953. // cf. https://v8.dev/blog/preparser#pife
  12954. let wrapperStart = `System.register(${registeredName}[` +
  12955. dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
  12956. `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
  12957. getStarExcludesBlock(starExcludes, t, snippets) +
  12958. getImportBindingsBlock(importBindings, t, snippets) +
  12959. `${n}${t}return${_}{${setters.length
  12960. ? `${n}${t}${t}setters:${_}[${setters
  12961. .map(setter => setter
  12962. ? `${getFunctionIntro(['module'], {
  12963. isAsync: false,
  12964. name: null
  12965. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  12966. : systemNullSetters
  12967. ? `null`
  12968. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  12969. .join(`,${_}`)}],`
  12970. : ''}${n}`;
  12971. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  12972. isAsync: usesTopLevelAwait,
  12973. name: null
  12974. })}{${n}${n}`;
  12975. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  12976. magicString.prepend(intro +
  12977. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  12978. getHoistedExportsBlock(exports, t, snippets));
  12979. magicString.append(`${outro}${n}${n}` +
  12980. getSyntheticExportsBlock(exports, t, snippets) +
  12981. getMissingExportsBlock(exports, t, snippets));
  12982. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  12983. }
  12984. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  12985. const importBindings = [];
  12986. const setters = [];
  12987. let starExcludes = null;
  12988. for (const { imports, reexports } of dependencies) {
  12989. const setter = [];
  12990. if (imports) {
  12991. for (const specifier of imports) {
  12992. importBindings.push(specifier.local);
  12993. if (specifier.imported === '*') {
  12994. setter.push(`${specifier.local}${_}=${_}module;`);
  12995. }
  12996. else {
  12997. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  12998. }
  12999. }
  13000. }
  13001. if (reexports) {
  13002. const reexportedNames = [];
  13003. let hasStarReexport = false;
  13004. for (const { imported, reexported } of reexports) {
  13005. if (reexported === '*') {
  13006. hasStarReexport = true;
  13007. }
  13008. else {
  13009. reexportedNames.push([
  13010. reexported,
  13011. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  13012. ]);
  13013. }
  13014. }
  13015. if (reexportedNames.length > 1 || hasStarReexport) {
  13016. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  13017. if (hasStarReexport) {
  13018. if (!starExcludes) {
  13019. starExcludes = getStarExcludes({ dependencies, exports });
  13020. }
  13021. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  13022. }
  13023. else {
  13024. setter.push(`exports(${exportMapping});`);
  13025. }
  13026. }
  13027. else {
  13028. const [key, value] = reexportedNames[0];
  13029. setter.push(`exports('${key}',${_}${value});`);
  13030. }
  13031. }
  13032. setters.push(setter.join(`${n}${t}${t}${t}`));
  13033. }
  13034. return { importBindings, setters, starExcludes };
  13035. }
  13036. const getStarExcludes = ({ dependencies, exports }) => {
  13037. const starExcludes = new Set(exports.map(expt => expt.exported));
  13038. starExcludes.add('default');
  13039. for (const { reexports } of dependencies) {
  13040. if (reexports) {
  13041. for (const reexport of reexports) {
  13042. if (reexport.reexported !== '*')
  13043. starExcludes.add(reexport.reexported);
  13044. }
  13045. }
  13046. }
  13047. return starExcludes;
  13048. };
  13049. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  13050. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
  13051. : '';
  13052. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  13053. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  13054. function getExportsBlock(exports, t, { _, n }) {
  13055. if (exports.length === 0) {
  13056. return '';
  13057. }
  13058. if (exports.length === 1) {
  13059. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  13060. }
  13061. return (`exports({${n}` +
  13062. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  13063. `${n}});${n}${n}`);
  13064. }
  13065. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  13066. .filter(expt => expt.expression)
  13067. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  13068. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  13069. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  13070. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  13071. function globalProp(name, globalVar, getPropertyAccess) {
  13072. if (!name)
  13073. return 'null';
  13074. return `${globalVar}${keypath(name, getPropertyAccess)}`;
  13075. }
  13076. function safeAccess(name, globalVar, { _, getPropertyAccess }) {
  13077. let propertyPath = globalVar;
  13078. return name
  13079. .split('.')
  13080. .map(part => (propertyPath += getPropertyAccess(part)))
  13081. .join(`${_}&&${_}`);
  13082. }
  13083. 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 }) {
  13084. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  13085. const factoryVar = compact ? 'f' : 'factory';
  13086. const globalVar = compact ? 'g' : 'global';
  13087. if (hasExports && !name) {
  13088. return error({
  13089. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  13090. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  13091. });
  13092. }
  13093. warnOnBuiltins(warn, dependencies);
  13094. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
  13095. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  13096. const trimmedImports = trimEmptyImports(dependencies);
  13097. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
  13098. const factoryParams = trimmedImports.map(m => m.name);
  13099. if (namedExportsMode && (hasExports || noConflict)) {
  13100. amdDeps.unshift(`'exports'`);
  13101. cjsDeps.unshift(`exports`);
  13102. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  13103. factoryParams.unshift('exports');
  13104. }
  13105. const completeAmdId = getCompleteAmdId(amd, id);
  13106. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  13107. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  13108. const define = amd.define;
  13109. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  13110. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  13111. let iifeExport;
  13112. if (noConflict) {
  13113. const noConflictExportsVar = compact ? 'e' : 'exports';
  13114. let factory;
  13115. if (!namedExportsMode && hasExports) {
  13116. factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  13117. }
  13118. else {
  13119. const module = globalDeps.shift();
  13120. factory =
  13121. `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
  13122. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  13123. }
  13124. iifeExport =
  13125. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  13126. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
  13127. `${t}${t}${factory}${n}` +
  13128. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
  13129. isAsync: false,
  13130. name: null
  13131. })}{${_}` +
  13132. `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
  13133. `${t}})()`;
  13134. }
  13135. else {
  13136. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  13137. if (!namedExportsMode && hasExports) {
  13138. iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
  13139. }
  13140. }
  13141. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  13142. const wrapperParams = [factoryVar];
  13143. if (iifeNeedsGlobal) {
  13144. wrapperParams.unshift(globalVar);
  13145. }
  13146. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  13147. const iifeStart = iifeNeedsGlobal
  13148. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  13149. : '';
  13150. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  13151. const cjsIntro = iifeNeedsGlobal
  13152. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  13153. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  13154. : '';
  13155. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
  13156. cjsIntro +
  13157. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  13158. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  13159. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13160. // cf. https://v8.dev/blog/preparser#pife
  13161. `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
  13162. isAsync: false,
  13163. name: null
  13164. })}{${useStrict}${n}`;
  13165. const wrapperOutro = n + n + '}));';
  13166. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13167. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13168. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  13169. if (namespaceMarkers) {
  13170. namespaceMarkers = n + n + namespaceMarkers;
  13171. }
  13172. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  13173. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  13174. }
  13175. const finalisers = { amd, cjs, es, iife, system, umd };
  13176. class Source {
  13177. constructor(filename, content) {
  13178. this.isOriginal = true;
  13179. this.filename = filename;
  13180. this.content = content;
  13181. }
  13182. traceSegment(line, column, name) {
  13183. return { column, line, name, source: this };
  13184. }
  13185. }
  13186. class Link {
  13187. constructor(map, sources) {
  13188. this.sources = sources;
  13189. this.names = map.names;
  13190. this.mappings = map.mappings;
  13191. }
  13192. traceMappings() {
  13193. const sources = [];
  13194. const sourceIndexMap = new Map();
  13195. const sourcesContent = [];
  13196. const names = [];
  13197. const nameIndexMap = new Map();
  13198. const mappings = [];
  13199. for (const line of this.mappings) {
  13200. const tracedLine = [];
  13201. for (const segment of line) {
  13202. if (segment.length === 1)
  13203. continue;
  13204. const source = this.sources[segment[1]];
  13205. if (!source)
  13206. continue;
  13207. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  13208. if (traced) {
  13209. const { column, line, name, source: { content, filename } } = traced;
  13210. let sourceIndex = sourceIndexMap.get(filename);
  13211. if (sourceIndex === undefined) {
  13212. sourceIndex = sources.length;
  13213. sources.push(filename);
  13214. sourceIndexMap.set(filename, sourceIndex);
  13215. sourcesContent[sourceIndex] = content;
  13216. }
  13217. else if (sourcesContent[sourceIndex] == null) {
  13218. sourcesContent[sourceIndex] = content;
  13219. }
  13220. else if (content != null && sourcesContent[sourceIndex] !== content) {
  13221. return error({
  13222. message: `Multiple conflicting contents for sourcemap source ${filename}`
  13223. });
  13224. }
  13225. const tracedSegment = [segment[0], sourceIndex, line, column];
  13226. if (name) {
  13227. let nameIndex = nameIndexMap.get(name);
  13228. if (nameIndex === undefined) {
  13229. nameIndex = names.length;
  13230. names.push(name);
  13231. nameIndexMap.set(name, nameIndex);
  13232. }
  13233. tracedSegment[4] = nameIndex;
  13234. }
  13235. tracedLine.push(tracedSegment);
  13236. }
  13237. }
  13238. mappings.push(tracedLine);
  13239. }
  13240. return { mappings, names, sources, sourcesContent };
  13241. }
  13242. traceSegment(line, column, name) {
  13243. const segments = this.mappings[line];
  13244. if (!segments)
  13245. return null;
  13246. // binary search through segments for the given column
  13247. let searchStart = 0;
  13248. let searchEnd = segments.length - 1;
  13249. while (searchStart <= searchEnd) {
  13250. const m = (searchStart + searchEnd) >> 1;
  13251. const segment = segments[m];
  13252. // If a sourcemap does not have sufficient resolution to contain a
  13253. // necessary mapping, e.g. because it only contains line information, we
  13254. // use the best approximation we could find
  13255. if (segment[0] === column || searchStart === searchEnd) {
  13256. if (segment.length == 1)
  13257. return null;
  13258. const source = this.sources[segment[1]];
  13259. if (!source)
  13260. return null;
  13261. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  13262. }
  13263. if (segment[0] > column) {
  13264. searchEnd = m - 1;
  13265. }
  13266. else {
  13267. searchStart = m + 1;
  13268. }
  13269. }
  13270. return null;
  13271. }
  13272. }
  13273. function getLinkMap(warn) {
  13274. return function linkMap(source, map) {
  13275. if (map.mappings) {
  13276. return new Link(map, [source]);
  13277. }
  13278. warn({
  13279. code: 'SOURCEMAP_BROKEN',
  13280. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  13281. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  13282. 'documentation for help',
  13283. plugin: map.plugin,
  13284. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  13285. });
  13286. return new Link({
  13287. mappings: [],
  13288. names: []
  13289. }, [source]);
  13290. };
  13291. }
  13292. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  13293. let source;
  13294. if (!originalSourcemap) {
  13295. source = new Source(id, originalCode);
  13296. }
  13297. else {
  13298. const sources = originalSourcemap.sources;
  13299. const sourcesContent = originalSourcemap.sourcesContent || [];
  13300. const directory = require$$0.dirname(id) || '.';
  13301. const sourceRoot = originalSourcemap.sourceRoot || '.';
  13302. const baseSources = sources.map((source, i) => new Source(require$$0.resolve(directory, sourceRoot, source), sourcesContent[i]));
  13303. source = new Link(originalSourcemap, baseSources);
  13304. }
  13305. return sourcemapChain.reduce(linkMap, source);
  13306. }
  13307. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  13308. const linkMap = getLinkMap(warn);
  13309. const moduleSources = modules
  13310. .filter(module => !module.excludeFromSourcemap)
  13311. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  13312. const link = new Link(map, moduleSources);
  13313. const source = bundleSourcemapChain.reduce(linkMap, link);
  13314. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  13315. if (file) {
  13316. const directory = require$$0.dirname(file);
  13317. sources = sources.map((source) => require$$0.relative(directory, source));
  13318. file = require$$0.basename(file);
  13319. }
  13320. sourcesContent = (excludeContent ? null : sourcesContent);
  13321. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  13322. }
  13323. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  13324. if (!sourcemapChain.length) {
  13325. return originalSourcemap;
  13326. }
  13327. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  13328. const map = source.traceMappings();
  13329. return { version: 3, ...map };
  13330. }
  13331. const createHash = () => crypto.createHash('sha256');
  13332. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  13333. amd: deconflictImportsOther,
  13334. cjs: deconflictImportsOther,
  13335. es: deconflictImportsEsmOrSystem,
  13336. iife: deconflictImportsOther,
  13337. system: deconflictImportsEsmOrSystem,
  13338. umd: deconflictImportsOther
  13339. };
  13340. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  13341. const reversedModules = modules.slice().reverse();
  13342. for (const module of reversedModules) {
  13343. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  13344. }
  13345. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  13346. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  13347. for (const module of reversedModules) {
  13348. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13349. }
  13350. }
  13351. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  13352. // This is needed for namespace reexports
  13353. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  13354. if (preserveModules || dependency instanceof ExternalModule) {
  13355. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  13356. }
  13357. }
  13358. for (const variable of imports) {
  13359. const module = variable.module;
  13360. const name = variable.name;
  13361. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  13362. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  13363. }
  13364. else if (module instanceof ExternalModule && name === 'default') {
  13365. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  13366. ? module.suggestedVariableName + '__default'
  13367. : module.suggestedVariableName, usedNames));
  13368. }
  13369. else {
  13370. variable.setRenderNames(null, getSafeName(name, usedNames));
  13371. }
  13372. }
  13373. for (const variable of syntheticExports) {
  13374. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13375. }
  13376. }
  13377. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  13378. for (const chunkOrExternalModule of dependencies) {
  13379. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  13380. }
  13381. for (const externalModuleOrChunk of deconflictedNamespace) {
  13382. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  13383. }
  13384. for (const externalModule of deconflictedDefault) {
  13385. if (deconflictedNamespace.has(externalModule) &&
  13386. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  13387. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  13388. }
  13389. else {
  13390. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  13391. }
  13392. }
  13393. for (const variable of imports) {
  13394. const module = variable.module;
  13395. if (module instanceof ExternalModule) {
  13396. const name = variable.name;
  13397. if (name === 'default') {
  13398. const moduleInterop = String(interop(module.id));
  13399. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13400. ? module.defaultVariableName
  13401. : module.variableName;
  13402. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  13403. variable.setRenderNames(variableName, 'default');
  13404. }
  13405. else {
  13406. variable.setRenderNames(null, variableName);
  13407. }
  13408. }
  13409. else if (name === '*') {
  13410. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  13411. ? module.namespaceVariableName
  13412. : module.variableName);
  13413. }
  13414. else {
  13415. // if the second parameter is `null`, it uses its "name" for the property name
  13416. variable.setRenderNames(module.variableName, null);
  13417. }
  13418. }
  13419. else {
  13420. const chunk = chunkByModule.get(module);
  13421. if (preserveModules && variable.isNamespace) {
  13422. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  13423. }
  13424. else if (chunk.exportMode === 'default') {
  13425. variable.setRenderNames(null, chunk.variableName);
  13426. }
  13427. else {
  13428. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  13429. }
  13430. }
  13431. }
  13432. }
  13433. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  13434. for (const module of modules) {
  13435. for (const variable of module.scope.variables.values()) {
  13436. if (variable.included &&
  13437. // this will only happen for exports in some formats
  13438. !(variable.renderBaseName ||
  13439. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  13440. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13441. }
  13442. }
  13443. if (includedNamespaces.has(module)) {
  13444. const namespace = module.namespace;
  13445. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  13446. }
  13447. }
  13448. }
  13449. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  13450. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  13451. const backSlashRegEx = /\\/g;
  13452. function escapeId(id) {
  13453. if (!id.match(needsEscapeRegEx))
  13454. return id;
  13455. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  13456. }
  13457. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  13458. let nameIndex = 0;
  13459. for (const variable of exports) {
  13460. let [exportName] = variable.name;
  13461. if (exportsByName.has(exportName)) {
  13462. do {
  13463. exportName = toBase64(++nameIndex);
  13464. // skip past leading number identifiers
  13465. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  13466. nameIndex += 9 * 64 ** (exportName.length - 1);
  13467. exportName = toBase64(nameIndex);
  13468. }
  13469. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  13470. }
  13471. exportsByName.set(exportName, variable);
  13472. exportNamesByVariable.set(variable, [exportName]);
  13473. }
  13474. }
  13475. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  13476. for (const variable of exports) {
  13477. let nameIndex = 0;
  13478. let exportName = variable.name;
  13479. while (exportsByName.has(exportName)) {
  13480. exportName = variable.name + '$' + ++nameIndex;
  13481. }
  13482. exportsByName.set(exportName, variable);
  13483. exportNamesByVariable.set(variable, [exportName]);
  13484. }
  13485. }
  13486. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  13487. const exportKeys = chunk.getExportNames();
  13488. if (exportMode === 'default') {
  13489. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  13490. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  13491. }
  13492. }
  13493. else if (exportMode === 'none' && exportKeys.length) {
  13494. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  13495. }
  13496. if (exportMode === 'auto') {
  13497. if (exportKeys.length === 0) {
  13498. exportMode = 'none';
  13499. }
  13500. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  13501. if (format === 'cjs' && unsetOptions.has('exports')) {
  13502. warn(errPreferNamedExports(facadeModuleId));
  13503. }
  13504. exportMode = 'default';
  13505. }
  13506. else {
  13507. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  13508. warn(errMixedExport(facadeModuleId, name));
  13509. }
  13510. exportMode = 'named';
  13511. }
  13512. }
  13513. return exportMode;
  13514. }
  13515. function guessIndentString(code) {
  13516. const lines = code.split('\n');
  13517. const tabbed = lines.filter(line => /^\t+/.test(line));
  13518. const spaced = lines.filter(line => /^ {2,}/.test(line));
  13519. if (tabbed.length === 0 && spaced.length === 0) {
  13520. return null;
  13521. }
  13522. // More lines tabbed than spaced? Assume tabs, and
  13523. // default to tabs in the case of a tie (or nothing
  13524. // to go on)
  13525. if (tabbed.length >= spaced.length) {
  13526. return '\t';
  13527. }
  13528. // Otherwise, we need to guess the multiple
  13529. const min = spaced.reduce((previous, current) => {
  13530. const numSpaces = /^ +/.exec(current)[0].length;
  13531. return Math.min(numSpaces, previous);
  13532. }, Infinity);
  13533. return new Array(min + 1).join(' ');
  13534. }
  13535. function getIndentString(modules, options) {
  13536. if (options.indent !== true)
  13537. return options.indent;
  13538. for (const module of modules) {
  13539. const indent = guessIndentString(module.originalCode);
  13540. if (indent !== null)
  13541. return indent;
  13542. }
  13543. return '\t';
  13544. }
  13545. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  13546. const staticDependencyBlocks = [];
  13547. const handledDependencies = new Set();
  13548. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  13549. const module = orderedModules[modulePos];
  13550. if (!handledDependencies.has(module)) {
  13551. const staticDependencies = [];
  13552. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  13553. staticDependencyBlocks.unshift(staticDependencies);
  13554. }
  13555. }
  13556. const dependencies = new Set();
  13557. for (const block of staticDependencyBlocks) {
  13558. for (const dependency of block) {
  13559. dependencies.add(dependency);
  13560. }
  13561. }
  13562. return dependencies;
  13563. }
  13564. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  13565. const dependencies = module.getDependenciesToBeIncluded();
  13566. for (const dependency of dependencies) {
  13567. if (dependency instanceof ExternalModule) {
  13568. staticDependencies.push(dependency);
  13569. continue;
  13570. }
  13571. const dependencyChunk = chunkByModule.get(dependency);
  13572. if (dependencyChunk !== chunk) {
  13573. staticDependencies.push(dependencyChunk);
  13574. continue;
  13575. }
  13576. if (!handledModules.has(dependency)) {
  13577. handledModules.add(dependency);
  13578. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  13579. }
  13580. }
  13581. }
  13582. function decodedSourcemap(map) {
  13583. if (!map)
  13584. return null;
  13585. if (typeof map === 'string') {
  13586. map = JSON.parse(map);
  13587. }
  13588. if (map.mappings === '') {
  13589. return {
  13590. mappings: [],
  13591. names: [],
  13592. sources: [],
  13593. version: 3
  13594. };
  13595. }
  13596. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  13597. return { ...map, mappings };
  13598. }
  13599. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  13600. const renderChunkReducer = (code, result, plugin) => {
  13601. if (result == null)
  13602. return code;
  13603. if (typeof result === 'string')
  13604. result = {
  13605. code: result,
  13606. map: undefined
  13607. };
  13608. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  13609. if (result.map !== null) {
  13610. const map = decodedSourcemap(result.map);
  13611. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  13612. }
  13613. return result.code;
  13614. };
  13615. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  13616. }
  13617. const lowercaseBundleKeys = Symbol('bundleKeys');
  13618. const FILE_PLACEHOLDER = {
  13619. type: 'placeholder'
  13620. };
  13621. const getOutputBundle = (outputBundleBase) => {
  13622. const reservedLowercaseBundleKeys = new Set();
  13623. return new Proxy(outputBundleBase, {
  13624. deleteProperty(target, key) {
  13625. if (typeof key === 'string') {
  13626. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  13627. }
  13628. return Reflect.deleteProperty(target, key);
  13629. },
  13630. get(target, key) {
  13631. if (key === lowercaseBundleKeys) {
  13632. return reservedLowercaseBundleKeys;
  13633. }
  13634. return Reflect.get(target, key);
  13635. },
  13636. set(target, key, value) {
  13637. if (typeof key === 'string') {
  13638. reservedLowercaseBundleKeys.add(key.toLowerCase());
  13639. }
  13640. return Reflect.set(target, key, value);
  13641. }
  13642. });
  13643. };
  13644. function renderNamePattern(pattern, patternName, replacements) {
  13645. if (isPathFragment(pattern))
  13646. 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.`));
  13647. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  13648. if (!replacements.hasOwnProperty(type)) {
  13649. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  13650. }
  13651. const replacement = replacements[type]();
  13652. if (isPathFragment(replacement))
  13653. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  13654. return replacement;
  13655. });
  13656. }
  13657. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  13658. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  13659. return name;
  13660. const ext = require$$0.extname(name);
  13661. name = name.substring(0, name.length - ext.length);
  13662. let uniqueName, uniqueIndex = 1;
  13663. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  13664. ;
  13665. return uniqueName;
  13666. }
  13667. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  13668. function getGlobalName(module, globals, hasExports, warn) {
  13669. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  13670. if (globalName) {
  13671. return globalName;
  13672. }
  13673. if (hasExports) {
  13674. warn({
  13675. code: 'MISSING_GLOBAL_NAME',
  13676. guess: module.variableName,
  13677. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  13678. source: module.id
  13679. });
  13680. return module.variableName;
  13681. }
  13682. }
  13683. class Chunk {
  13684. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  13685. this.orderedModules = orderedModules;
  13686. this.inputOptions = inputOptions;
  13687. this.outputOptions = outputOptions;
  13688. this.unsetOptions = unsetOptions;
  13689. this.pluginDriver = pluginDriver;
  13690. this.modulesById = modulesById;
  13691. this.chunkByModule = chunkByModule;
  13692. this.facadeChunkByModule = facadeChunkByModule;
  13693. this.includedNamespaces = includedNamespaces;
  13694. this.manualChunkAlias = manualChunkAlias;
  13695. this.entryModules = [];
  13696. this.exportMode = 'named';
  13697. this.facadeModule = null;
  13698. this.id = null;
  13699. this.namespaceVariableName = '';
  13700. this.needsExportsShim = false;
  13701. this.variableName = '';
  13702. this.accessedGlobalsByScope = new Map();
  13703. this.dependencies = new Set();
  13704. this.dynamicDependencies = new Set();
  13705. this.dynamicEntryModules = [];
  13706. this.dynamicName = null;
  13707. this.exportNamesByVariable = new Map();
  13708. this.exports = new Set();
  13709. this.exportsByName = new Map();
  13710. this.fileName = null;
  13711. this.implicitEntryModules = [];
  13712. this.implicitlyLoadedBefore = new Set();
  13713. this.imports = new Set();
  13714. this.includedReexportsByModule = new Map();
  13715. this.indentString = undefined;
  13716. // This may only be updated in the constructor
  13717. this.isEmpty = true;
  13718. this.name = null;
  13719. this.renderedDependencies = null;
  13720. this.renderedExports = null;
  13721. this.renderedHash = undefined;
  13722. this.renderedModuleSources = new Map();
  13723. this.renderedModules = Object.create(null);
  13724. this.renderedSource = null;
  13725. this.sortedExportNames = null;
  13726. this.strictFacade = false;
  13727. this.usedModules = undefined;
  13728. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  13729. const chunkModules = new Set(orderedModules);
  13730. for (const module of orderedModules) {
  13731. if (module.namespace.included) {
  13732. includedNamespaces.add(module);
  13733. }
  13734. if (this.isEmpty && module.isIncluded()) {
  13735. this.isEmpty = false;
  13736. }
  13737. if (module.info.isEntry || outputOptions.preserveModules) {
  13738. this.entryModules.push(module);
  13739. }
  13740. for (const importer of module.includedDynamicImporters) {
  13741. if (!chunkModules.has(importer)) {
  13742. this.dynamicEntryModules.push(module);
  13743. // Modules with synthetic exports need an artificial namespace for dynamic imports
  13744. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  13745. includedNamespaces.add(module);
  13746. this.exports.add(module.namespace);
  13747. }
  13748. }
  13749. }
  13750. if (module.implicitlyLoadedAfter.size > 0) {
  13751. this.implicitEntryModules.push(module);
  13752. }
  13753. }
  13754. this.suggestedVariableName = makeLegal(this.generateVariableName());
  13755. }
  13756. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  13757. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  13758. chunk.assignFacadeName(facadeName, facadedModule);
  13759. if (!facadeChunkByModule.has(facadedModule)) {
  13760. facadeChunkByModule.set(facadedModule, chunk);
  13761. }
  13762. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  13763. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  13764. }
  13765. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  13766. facadedModule.info.moduleSideEffects &&
  13767. facadedModule.hasEffects()) {
  13768. chunk.dependencies.add(chunkByModule.get(facadedModule));
  13769. }
  13770. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  13771. chunk.facadeModule = facadedModule;
  13772. chunk.strictFacade = true;
  13773. return chunk;
  13774. }
  13775. canModuleBeFacade(module, exposedVariables) {
  13776. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  13777. for (const exposedVariable of this.exports) {
  13778. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  13779. if (moduleExportNamesByVariable.size === 0 &&
  13780. module.isUserDefinedEntryPoint &&
  13781. module.preserveSignature === 'strict' &&
  13782. this.unsetOptions.has('preserveEntrySignatures')) {
  13783. this.inputOptions.onwarn({
  13784. code: 'EMPTY_FACADE',
  13785. id: module.id,
  13786. 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.`,
  13787. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  13788. });
  13789. }
  13790. return false;
  13791. }
  13792. }
  13793. for (const exposedVariable of exposedVariables) {
  13794. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  13795. return false;
  13796. }
  13797. }
  13798. return true;
  13799. }
  13800. generateExports() {
  13801. this.sortedExportNames = null;
  13802. const remainingExports = new Set(this.exports);
  13803. if (this.facadeModule !== null &&
  13804. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  13805. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  13806. for (const [variable, exportNames] of exportNamesByVariable) {
  13807. this.exportNamesByVariable.set(variable, [...exportNames]);
  13808. for (const exportName of exportNames) {
  13809. this.exportsByName.set(exportName, variable);
  13810. }
  13811. remainingExports.delete(variable);
  13812. }
  13813. }
  13814. if (this.outputOptions.minifyInternalExports) {
  13815. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13816. }
  13817. else {
  13818. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13819. }
  13820. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  13821. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  13822. }
  13823. generateFacades() {
  13824. var _a;
  13825. const facades = [];
  13826. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  13827. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  13828. for (const module of entryModules) {
  13829. if (module.preserveSignature) {
  13830. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  13831. exposedVariables.add(exportedVariable);
  13832. }
  13833. }
  13834. }
  13835. for (const module of entryModules) {
  13836. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  13837. // mapping must run after Set 'name' dedupe
  13838. name => ({
  13839. name
  13840. }));
  13841. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  13842. requiredFacades.push({});
  13843. }
  13844. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  13845. if (requiredFacades.length === 0) {
  13846. requiredFacades.push({});
  13847. }
  13848. if (!this.facadeModule) {
  13849. const needsStrictFacade = module.preserveSignature === 'strict' ||
  13850. (module.preserveSignature === 'exports-only' &&
  13851. module.getExportNamesByVariable().size !== 0);
  13852. if (!needsStrictFacade ||
  13853. this.outputOptions.preserveModules ||
  13854. this.canModuleBeFacade(module, exposedVariables)) {
  13855. this.facadeModule = module;
  13856. this.facadeChunkByModule.set(module, this);
  13857. if (module.preserveSignature) {
  13858. this.strictFacade = needsStrictFacade;
  13859. }
  13860. this.assignFacadeName(requiredFacades.shift(), module);
  13861. }
  13862. }
  13863. for (const facadeName of requiredFacades) {
  13864. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  13865. }
  13866. }
  13867. for (const module of this.dynamicEntryModules) {
  13868. if (module.info.syntheticNamedExports)
  13869. continue;
  13870. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  13871. this.facadeModule = module;
  13872. this.facadeChunkByModule.set(module, this);
  13873. this.strictFacade = true;
  13874. this.dynamicName = getChunkNameFromModule(module);
  13875. }
  13876. else if (this.facadeModule === module &&
  13877. !this.strictFacade &&
  13878. this.canModuleBeFacade(module, exposedVariables)) {
  13879. this.strictFacade = true;
  13880. }
  13881. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  13882. this.includedNamespaces.add(module);
  13883. this.exports.add(module.namespace);
  13884. }
  13885. }
  13886. if (!this.outputOptions.preserveModules) {
  13887. this.addNecessaryImportsForFacades();
  13888. }
  13889. return facades;
  13890. }
  13891. generateId(addons, options, bundle, includeHash) {
  13892. if (this.fileName !== null) {
  13893. return this.fileName;
  13894. }
  13895. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  13896. ? [options.entryFileNames, 'output.entryFileNames']
  13897. : [options.chunkFileNames, 'output.chunkFileNames'];
  13898. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  13899. format: () => options.format,
  13900. hash: () => includeHash
  13901. ? this.computeContentHashWithDependencies(addons, options, bundle)
  13902. : '[hash]',
  13903. name: () => this.getChunkName()
  13904. }), bundle);
  13905. }
  13906. generateIdPreserveModules(preserveModulesRelativeDir, options, bundle, unsetOptions) {
  13907. const [{ id }] = this.orderedModules;
  13908. const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
  13909. let path;
  13910. const patternOpt = unsetOptions.has('entryFileNames')
  13911. ? '[name][assetExtname].js'
  13912. : options.entryFileNames;
  13913. const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
  13914. if (isAbsolute(sanitizedId)) {
  13915. const currentDir = require$$0.dirname(sanitizedId);
  13916. const extension = require$$0.extname(sanitizedId);
  13917. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13918. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13919. ext: () => extension.substring(1),
  13920. extname: () => extension,
  13921. format: () => options.format,
  13922. name: () => this.getChunkName()
  13923. });
  13924. const currentPath = `${currentDir}/${fileName}`;
  13925. const { preserveModulesRoot } = options;
  13926. if (preserveModulesRoot && require$$0.resolve(currentPath).startsWith(preserveModulesRoot)) {
  13927. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  13928. }
  13929. else {
  13930. path = relative(preserveModulesRelativeDir, currentPath);
  13931. }
  13932. }
  13933. else {
  13934. const extension = require$$0.extname(sanitizedId);
  13935. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13936. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13937. ext: () => extension.substring(1),
  13938. extname: () => extension,
  13939. format: () => options.format,
  13940. name: () => getAliasName(sanitizedId)
  13941. });
  13942. path = `_virtual/${fileName}`;
  13943. }
  13944. return makeUnique(normalize(path), bundle);
  13945. }
  13946. getChunkInfo() {
  13947. const facadeModule = this.facadeModule;
  13948. const getChunkName = this.getChunkName.bind(this);
  13949. return {
  13950. exports: this.getExportNames(),
  13951. facadeModuleId: facadeModule && facadeModule.id,
  13952. isDynamicEntry: this.dynamicEntryModules.length > 0,
  13953. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  13954. isImplicitEntry: this.implicitEntryModules.length > 0,
  13955. modules: this.renderedModules,
  13956. get name() {
  13957. return getChunkName();
  13958. },
  13959. type: 'chunk'
  13960. };
  13961. }
  13962. getChunkInfoWithFileNames() {
  13963. return Object.assign(this.getChunkInfo(), {
  13964. code: undefined,
  13965. dynamicImports: Array.from(this.dynamicDependencies, getId),
  13966. fileName: this.id,
  13967. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  13968. importedBindings: this.getImportedBindingsPerDependency(),
  13969. imports: Array.from(this.dependencies, getId),
  13970. map: undefined,
  13971. referencedFiles: this.getReferencedFiles()
  13972. });
  13973. }
  13974. getChunkName() {
  13975. var _a;
  13976. return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  13977. }
  13978. getExportNames() {
  13979. var _a;
  13980. return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
  13981. }
  13982. getRenderedHash() {
  13983. if (this.renderedHash)
  13984. return this.renderedHash;
  13985. const hash = createHash();
  13986. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  13987. if (pluginHash) {
  13988. augmentation += pluginHash;
  13989. }
  13990. return augmentation;
  13991. });
  13992. hash.update(hashAugmentation);
  13993. hash.update(this.renderedSource.toString());
  13994. hash.update(this.getExportNames()
  13995. .map(exportName => {
  13996. const variable = this.exportsByName.get(exportName);
  13997. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  13998. })
  13999. .join(','));
  14000. return (this.renderedHash = hash.digest('hex'));
  14001. }
  14002. getVariableExportName(variable) {
  14003. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  14004. return '*';
  14005. }
  14006. return this.exportNamesByVariable.get(variable)[0];
  14007. }
  14008. link() {
  14009. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  14010. for (const module of this.orderedModules) {
  14011. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  14012. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  14013. this.setUpChunkImportsAndExportsForModule(module);
  14014. }
  14015. }
  14016. // prerender allows chunk hashes and names to be generated before finalizing
  14017. preRender(options, inputBase, snippets) {
  14018. const { _, getPropertyAccess, n } = snippets;
  14019. const magicString = new Bundle$1({ separator: `${n}${n}` });
  14020. this.usedModules = [];
  14021. this.indentString = getIndentString(this.orderedModules, options);
  14022. const renderOptions = {
  14023. dynamicImportFunction: options.dynamicImportFunction,
  14024. exportNamesByVariable: this.exportNamesByVariable,
  14025. format: options.format,
  14026. freeze: options.freeze,
  14027. indent: this.indentString,
  14028. namespaceToStringTag: options.namespaceToStringTag,
  14029. outputPluginDriver: this.pluginDriver,
  14030. snippets
  14031. };
  14032. // for static and dynamic entry points, inline the execution list to avoid loading latency
  14033. if (options.hoistTransitiveImports &&
  14034. !this.outputOptions.preserveModules &&
  14035. this.facadeModule !== null) {
  14036. for (const dep of this.dependencies) {
  14037. if (dep instanceof Chunk)
  14038. this.inlineChunkDependencies(dep);
  14039. }
  14040. }
  14041. this.prepareModulesForRendering(snippets);
  14042. this.setIdentifierRenderResolutions(options);
  14043. let hoistedSource = '';
  14044. const renderedModules = this.renderedModules;
  14045. for (const module of this.orderedModules) {
  14046. let renderedLength = 0;
  14047. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  14048. const source = module.render(renderOptions).trim();
  14049. renderedLength = source.length();
  14050. if (renderedLength) {
  14051. if (options.compact && source.lastLine().includes('//'))
  14052. source.append('\n');
  14053. this.renderedModuleSources.set(module, source);
  14054. magicString.addSource(source);
  14055. this.usedModules.push(module);
  14056. }
  14057. const namespace = module.namespace;
  14058. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14059. const rendered = namespace.renderBlock(renderOptions);
  14060. if (namespace.renderFirst())
  14061. hoistedSource += n + rendered;
  14062. else
  14063. magicString.addSource(new MagicString(rendered));
  14064. }
  14065. }
  14066. const { renderedExports, removedExports } = module.getRenderedExports();
  14067. const { renderedModuleSources } = this;
  14068. renderedModules[module.id] = {
  14069. get code() {
  14070. var _a, _b;
  14071. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  14072. },
  14073. originalLength: module.originalCode.length,
  14074. removedExports,
  14075. renderedExports,
  14076. renderedLength
  14077. };
  14078. }
  14079. if (hoistedSource)
  14080. magicString.prepend(hoistedSource + n + n);
  14081. if (this.needsExportsShim) {
  14082. magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  14083. }
  14084. if (options.compact) {
  14085. this.renderedSource = magicString;
  14086. }
  14087. else {
  14088. this.renderedSource = magicString.trim();
  14089. }
  14090. this.renderedHash = undefined;
  14091. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  14092. const chunkName = this.getChunkName();
  14093. this.inputOptions.onwarn({
  14094. chunkName,
  14095. code: 'EMPTY_BUNDLE',
  14096. message: `Generated an empty chunk: "${chunkName}"`
  14097. });
  14098. }
  14099. this.setExternalRenderPaths(options, inputBase);
  14100. this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
  14101. this.renderedExports =
  14102. this.exportMode === 'none'
  14103. ? []
  14104. : this.getChunkExportDeclarations(options.format, getPropertyAccess);
  14105. }
  14106. async render(options, addons, outputChunk, snippets) {
  14107. timeStart('render format', 2);
  14108. const format = options.format;
  14109. const finalise = finalisers[format];
  14110. if (options.dynamicImportFunction && format !== 'es') {
  14111. this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
  14112. }
  14113. // populate ids in the rendered declarations only here
  14114. // as chunk ids known only after prerender
  14115. for (const dependency of this.dependencies) {
  14116. const renderedDependency = this.renderedDependencies.get(dependency);
  14117. if (dependency instanceof ExternalModule) {
  14118. const originalId = dependency.renderPath;
  14119. renderedDependency.id = escapeId(dependency.renormalizeRenderPath
  14120. ? getImportPath(this.id, originalId, false, false)
  14121. : originalId);
  14122. }
  14123. else {
  14124. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  14125. renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
  14126. }
  14127. }
  14128. this.finaliseDynamicImports(options, snippets);
  14129. this.finaliseImportMetas(format, snippets);
  14130. const hasExports = this.renderedExports.length !== 0 ||
  14131. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  14132. let topLevelAwaitModule = null;
  14133. const accessedGlobals = new Set();
  14134. for (const module of this.orderedModules) {
  14135. if (module.usesTopLevelAwait) {
  14136. topLevelAwaitModule = module.id;
  14137. }
  14138. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  14139. if (accessedGlobalVariables) {
  14140. for (const name of accessedGlobalVariables) {
  14141. accessedGlobals.add(name);
  14142. }
  14143. }
  14144. }
  14145. if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
  14146. return error({
  14147. code: 'INVALID_TLA_FORMAT',
  14148. id: topLevelAwaitModule,
  14149. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  14150. });
  14151. }
  14152. /* istanbul ignore next */
  14153. if (!this.id) {
  14154. throw new Error('Internal Error: expecting chunk id');
  14155. }
  14156. const magicString = finalise(this.renderedSource, {
  14157. accessedGlobals,
  14158. dependencies: [...this.renderedDependencies.values()],
  14159. exports: this.renderedExports,
  14160. hasExports,
  14161. id: this.id,
  14162. indent: this.indentString,
  14163. intro: addons.intro,
  14164. isEntryFacade: this.outputOptions.preserveModules ||
  14165. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  14166. isModuleFacade: this.facadeModule !== null,
  14167. namedExportsMode: this.exportMode !== 'default',
  14168. outro: addons.outro,
  14169. snippets,
  14170. usesTopLevelAwait: topLevelAwaitModule !== null,
  14171. warn: this.inputOptions.onwarn
  14172. }, options);
  14173. if (addons.banner)
  14174. magicString.prepend(addons.banner);
  14175. if (addons.footer)
  14176. magicString.append(addons.footer);
  14177. const prevCode = magicString.toString();
  14178. timeEnd('render format', 2);
  14179. let map = null;
  14180. const chunkSourcemapChain = [];
  14181. let code = await renderChunk({
  14182. code: prevCode,
  14183. options,
  14184. outputPluginDriver: this.pluginDriver,
  14185. renderChunk: outputChunk,
  14186. sourcemapChain: chunkSourcemapChain
  14187. });
  14188. if (options.sourcemap) {
  14189. timeStart('sourcemap', 2);
  14190. let file;
  14191. if (options.file)
  14192. file = require$$0.resolve(options.sourcemapFile || options.file);
  14193. else if (options.dir)
  14194. file = require$$0.resolve(options.dir, this.id);
  14195. else
  14196. file = require$$0.resolve(this.id);
  14197. const decodedMap = magicString.generateDecodedMap({});
  14198. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  14199. map.sources = map.sources
  14200. .map(sourcePath => {
  14201. const { sourcemapPathTransform } = options;
  14202. if (sourcemapPathTransform) {
  14203. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  14204. if (typeof newSourcePath !== 'string') {
  14205. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  14206. }
  14207. return newSourcePath;
  14208. }
  14209. return sourcePath;
  14210. })
  14211. .map(normalize);
  14212. timeEnd('sourcemap', 2);
  14213. }
  14214. if (!options.compact && code[code.length - 1] !== '\n')
  14215. code += '\n';
  14216. return { code, map };
  14217. }
  14218. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  14219. for (const module of moduleDependencies) {
  14220. if (module instanceof Module) {
  14221. const chunk = this.chunkByModule.get(module);
  14222. if (chunk && chunk !== this) {
  14223. chunkDependencies.add(chunk);
  14224. }
  14225. }
  14226. else {
  14227. chunkDependencies.add(module);
  14228. }
  14229. }
  14230. }
  14231. addNecessaryImportsForFacades() {
  14232. for (const [module, variables] of this.includedReexportsByModule) {
  14233. if (this.includedNamespaces.has(module)) {
  14234. for (const variable of variables) {
  14235. this.imports.add(variable);
  14236. }
  14237. }
  14238. }
  14239. }
  14240. assignFacadeName({ fileName, name }, facadedModule) {
  14241. if (fileName) {
  14242. this.fileName = fileName;
  14243. }
  14244. else {
  14245. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  14246. }
  14247. }
  14248. checkCircularDependencyImport(variable, importingModule) {
  14249. const variableModule = variable.module;
  14250. if (variableModule instanceof Module) {
  14251. const exportChunk = this.chunkByModule.get(variableModule);
  14252. let alternativeReexportModule;
  14253. do {
  14254. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  14255. if (alternativeReexportModule) {
  14256. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  14257. if (exportingChunk && exportingChunk !== exportChunk) {
  14258. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  14259. }
  14260. importingModule = alternativeReexportModule;
  14261. }
  14262. } while (alternativeReexportModule);
  14263. }
  14264. }
  14265. computeContentHashWithDependencies(addons, options, bundle) {
  14266. const hash = createHash();
  14267. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
  14268. hash.update(options.format);
  14269. const dependenciesForHashing = new Set([this]);
  14270. for (const current of dependenciesForHashing) {
  14271. if (current instanceof ExternalModule) {
  14272. hash.update(`:${current.renderPath}`);
  14273. }
  14274. else {
  14275. hash.update(current.getRenderedHash());
  14276. hash.update(current.generateId(addons, options, bundle, false));
  14277. }
  14278. if (current instanceof ExternalModule)
  14279. continue;
  14280. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  14281. dependenciesForHashing.add(dependency);
  14282. }
  14283. }
  14284. return hash.digest('hex').substr(0, 8);
  14285. }
  14286. ensureReexportsAreAvailableForModule(module) {
  14287. const includedReexports = [];
  14288. const map = module.getExportNamesByVariable();
  14289. for (const exportedVariable of map.keys()) {
  14290. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  14291. const importedVariable = isSynthetic
  14292. ? exportedVariable.getBaseVariable()
  14293. : exportedVariable;
  14294. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  14295. this.checkCircularDependencyImport(importedVariable, module);
  14296. const exportingModule = importedVariable.module;
  14297. if (exportingModule instanceof Module) {
  14298. const chunk = this.chunkByModule.get(exportingModule);
  14299. if (chunk && chunk !== this) {
  14300. chunk.exports.add(importedVariable);
  14301. includedReexports.push(importedVariable);
  14302. if (isSynthetic) {
  14303. this.imports.add(importedVariable);
  14304. }
  14305. }
  14306. }
  14307. }
  14308. }
  14309. if (includedReexports.length) {
  14310. this.includedReexportsByModule.set(module, includedReexports);
  14311. }
  14312. }
  14313. finaliseDynamicImports(options, snippets) {
  14314. const stripKnownJsExtensions = options.format === 'amd' && !options.amd.forceJsExtensionForImports;
  14315. for (const [module, code] of this.renderedModuleSources) {
  14316. for (const { node, resolution } of module.dynamicImports) {
  14317. const chunk = this.chunkByModule.get(resolution);
  14318. const facadeChunk = this.facadeChunkByModule.get(resolution);
  14319. if (!resolution || !node.included || chunk === this) {
  14320. continue;
  14321. }
  14322. const renderedResolution = resolution instanceof Module
  14323. ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
  14324. : resolution instanceof ExternalModule
  14325. ? `'${escapeId(resolution.renormalizeRenderPath
  14326. ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
  14327. : resolution.renderPath)}'`
  14328. : resolution;
  14329. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  14330. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  14331. chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
  14332. }
  14333. }
  14334. }
  14335. finaliseImportMetas(format, snippets) {
  14336. for (const [module, code] of this.renderedModuleSources) {
  14337. for (const importMeta of module.importMetas) {
  14338. importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
  14339. }
  14340. }
  14341. }
  14342. generateVariableName() {
  14343. if (this.manualChunkAlias) {
  14344. return this.manualChunkAlias;
  14345. }
  14346. const moduleForNaming = this.entryModules[0] ||
  14347. this.implicitEntryModules[0] ||
  14348. this.dynamicEntryModules[0] ||
  14349. this.orderedModules[this.orderedModules.length - 1];
  14350. if (moduleForNaming) {
  14351. return getChunkNameFromModule(moduleForNaming);
  14352. }
  14353. return 'chunk';
  14354. }
  14355. getChunkDependencyDeclarations(options, getPropertyAccess) {
  14356. const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
  14357. const reexportSpecifiers = this.getReexportSpecifiers();
  14358. const dependencyDeclaration = new Map();
  14359. for (const dep of this.dependencies) {
  14360. const imports = importSpecifiers.get(dep) || null;
  14361. const reexports = reexportSpecifiers.get(dep) || null;
  14362. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  14363. dependencyDeclaration.set(dep, {
  14364. defaultVariableName: dep.defaultVariableName,
  14365. globalName: (dep instanceof ExternalModule &&
  14366. (options.format === 'umd' || options.format === 'iife') &&
  14367. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  14368. id: undefined,
  14369. imports,
  14370. isChunk: dep instanceof Chunk,
  14371. name: dep.variableName,
  14372. namedExportsMode,
  14373. namespaceVariableName: dep.namespaceVariableName,
  14374. reexports
  14375. });
  14376. }
  14377. return dependencyDeclaration;
  14378. }
  14379. getChunkExportDeclarations(format, getPropertyAccess) {
  14380. const exports = [];
  14381. for (const exportName of this.getExportNames()) {
  14382. if (exportName[0] === '*')
  14383. continue;
  14384. const variable = this.exportsByName.get(exportName);
  14385. if (!(variable instanceof SyntheticNamedExportVariable)) {
  14386. const module = variable.module;
  14387. if (module && this.chunkByModule.get(module) !== this)
  14388. continue;
  14389. }
  14390. let expression = null;
  14391. let hoisted = false;
  14392. let local = variable.getName(getPropertyAccess);
  14393. if (variable instanceof LocalVariable) {
  14394. for (const declaration of variable.declarations) {
  14395. if (declaration.parent instanceof FunctionDeclaration ||
  14396. (declaration instanceof ExportDefaultDeclaration &&
  14397. declaration.declaration instanceof FunctionDeclaration)) {
  14398. hoisted = true;
  14399. break;
  14400. }
  14401. }
  14402. }
  14403. else if (variable instanceof SyntheticNamedExportVariable) {
  14404. expression = local;
  14405. if (format === 'es') {
  14406. local = variable.renderName;
  14407. }
  14408. }
  14409. exports.push({
  14410. exported: exportName,
  14411. expression,
  14412. hoisted,
  14413. local
  14414. });
  14415. }
  14416. return exports;
  14417. }
  14418. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  14419. const dependencies = new Set();
  14420. const deconflictedDefault = new Set();
  14421. const deconflictedNamespace = new Set();
  14422. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  14423. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  14424. const module = variable.module;
  14425. if (module instanceof ExternalModule) {
  14426. dependencies.add(module);
  14427. if (addNonNamespacesAndInteropHelpers) {
  14428. if (variable.name === 'default') {
  14429. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  14430. deconflictedDefault.add(module);
  14431. }
  14432. }
  14433. else if (variable.name === '*') {
  14434. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  14435. deconflictedNamespace.add(module);
  14436. }
  14437. }
  14438. }
  14439. }
  14440. else {
  14441. const chunk = this.chunkByModule.get(module);
  14442. if (chunk !== this) {
  14443. dependencies.add(chunk);
  14444. if (addNonNamespacesAndInteropHelpers &&
  14445. chunk.exportMode === 'default' &&
  14446. variable.isNamespace) {
  14447. deconflictedNamespace.add(chunk);
  14448. }
  14449. }
  14450. }
  14451. }
  14452. }
  14453. if (addDependenciesWithoutBindings) {
  14454. for (const dependency of this.dependencies) {
  14455. dependencies.add(dependency);
  14456. }
  14457. }
  14458. return { deconflictedDefault, deconflictedNamespace, dependencies };
  14459. }
  14460. getFallbackChunkName() {
  14461. if (this.manualChunkAlias) {
  14462. return this.manualChunkAlias;
  14463. }
  14464. if (this.dynamicName) {
  14465. return this.dynamicName;
  14466. }
  14467. if (this.fileName) {
  14468. return getAliasName(this.fileName);
  14469. }
  14470. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  14471. }
  14472. getImportSpecifiers(getPropertyAccess) {
  14473. const { interop } = this.outputOptions;
  14474. const importsByDependency = new Map();
  14475. for (const variable of this.imports) {
  14476. const module = variable.module;
  14477. let dependency;
  14478. let imported;
  14479. if (module instanceof ExternalModule) {
  14480. dependency = module;
  14481. imported = variable.name;
  14482. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14483. return error(errUnexpectedNamedImport(module.id, imported, false));
  14484. }
  14485. }
  14486. else {
  14487. dependency = this.chunkByModule.get(module);
  14488. imported = dependency.getVariableExportName(variable);
  14489. }
  14490. getOrCreate(importsByDependency, dependency, () => []).push({
  14491. imported,
  14492. local: variable.getName(getPropertyAccess)
  14493. });
  14494. }
  14495. return importsByDependency;
  14496. }
  14497. getImportedBindingsPerDependency() {
  14498. const importSpecifiers = {};
  14499. for (const [dependency, declaration] of this.renderedDependencies) {
  14500. const specifiers = new Set();
  14501. if (declaration.imports) {
  14502. for (const { imported } of declaration.imports) {
  14503. specifiers.add(imported);
  14504. }
  14505. }
  14506. if (declaration.reexports) {
  14507. for (const { imported } of declaration.reexports) {
  14508. specifiers.add(imported);
  14509. }
  14510. }
  14511. importSpecifiers[dependency.id] = [...specifiers];
  14512. }
  14513. return importSpecifiers;
  14514. }
  14515. getReexportSpecifiers() {
  14516. const { externalLiveBindings, interop } = this.outputOptions;
  14517. const reexportSpecifiers = new Map();
  14518. for (let exportName of this.getExportNames()) {
  14519. let dependency;
  14520. let imported;
  14521. let needsLiveBinding = false;
  14522. if (exportName[0] === '*') {
  14523. const id = exportName.substring(1);
  14524. if (interop(id) === 'defaultOnly') {
  14525. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  14526. }
  14527. needsLiveBinding = externalLiveBindings;
  14528. dependency = this.modulesById.get(id);
  14529. imported = exportName = '*';
  14530. }
  14531. else {
  14532. const variable = this.exportsByName.get(exportName);
  14533. if (variable instanceof SyntheticNamedExportVariable)
  14534. continue;
  14535. const module = variable.module;
  14536. if (module instanceof Module) {
  14537. dependency = this.chunkByModule.get(module);
  14538. if (dependency === this)
  14539. continue;
  14540. imported = dependency.getVariableExportName(variable);
  14541. needsLiveBinding = variable.isReassigned;
  14542. }
  14543. else {
  14544. dependency = module;
  14545. imported = variable.name;
  14546. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14547. return error(errUnexpectedNamedImport(module.id, imported, true));
  14548. }
  14549. needsLiveBinding =
  14550. externalLiveBindings &&
  14551. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  14552. }
  14553. }
  14554. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  14555. imported,
  14556. needsLiveBinding,
  14557. reexported: exportName
  14558. });
  14559. }
  14560. return reexportSpecifiers;
  14561. }
  14562. getReferencedFiles() {
  14563. const referencedFiles = [];
  14564. for (const module of this.orderedModules) {
  14565. for (const meta of module.importMetas) {
  14566. const fileName = meta.getReferencedFileName(this.pluginDriver);
  14567. if (fileName) {
  14568. referencedFiles.push(fileName);
  14569. }
  14570. }
  14571. }
  14572. return referencedFiles;
  14573. }
  14574. inlineChunkDependencies(chunk) {
  14575. for (const dep of chunk.dependencies) {
  14576. if (this.dependencies.has(dep))
  14577. continue;
  14578. this.dependencies.add(dep);
  14579. if (dep instanceof Chunk) {
  14580. this.inlineChunkDependencies(dep);
  14581. }
  14582. }
  14583. }
  14584. prepareModulesForRendering(snippets) {
  14585. var _a;
  14586. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  14587. for (const module of this.orderedModules) {
  14588. for (const { node, resolution } of module.dynamicImports) {
  14589. if (node.included) {
  14590. if (resolution instanceof Module) {
  14591. const chunk = this.chunkByModule.get(resolution);
  14592. if (chunk === this) {
  14593. node.setInternalResolution(resolution.namespace);
  14594. }
  14595. else {
  14596. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14597. }
  14598. }
  14599. else {
  14600. node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14601. }
  14602. }
  14603. }
  14604. for (const importMeta of module.importMetas) {
  14605. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  14606. }
  14607. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14608. module.namespace.prepare(accessedGlobalsByScope);
  14609. }
  14610. }
  14611. }
  14612. setExternalRenderPaths(options, inputBase) {
  14613. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  14614. if (dependency instanceof ExternalModule) {
  14615. dependency.setRenderPath(options, inputBase);
  14616. }
  14617. }
  14618. }
  14619. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  14620. const syntheticExports = new Set();
  14621. for (const exportName of this.getExportNames()) {
  14622. const exportVariable = this.exportsByName.get(exportName);
  14623. if (format !== 'es' &&
  14624. format !== 'system' &&
  14625. exportVariable.isReassigned &&
  14626. !exportVariable.isId) {
  14627. exportVariable.setRenderNames('exports', exportName);
  14628. }
  14629. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  14630. syntheticExports.add(exportVariable);
  14631. }
  14632. else {
  14633. exportVariable.setRenderNames(null, null);
  14634. }
  14635. }
  14636. for (const module of this.orderedModules) {
  14637. if (module.needsExportShim) {
  14638. this.needsExportsShim = true;
  14639. break;
  14640. }
  14641. }
  14642. const usedNames = new Set(['Object', 'Promise']);
  14643. if (this.needsExportsShim) {
  14644. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  14645. }
  14646. if (namespaceToStringTag) {
  14647. usedNames.add('Symbol');
  14648. }
  14649. switch (format) {
  14650. case 'system':
  14651. usedNames.add('module').add('exports');
  14652. break;
  14653. case 'es':
  14654. break;
  14655. case 'cjs':
  14656. usedNames.add('module').add('require').add('__filename').add('__dirname');
  14657. // fallthrough
  14658. default:
  14659. usedNames.add('exports');
  14660. for (const helper of HELPER_NAMES) {
  14661. usedNames.add(helper);
  14662. }
  14663. }
  14664. 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);
  14665. }
  14666. setUpChunkImportsAndExportsForModule(module) {
  14667. const moduleImports = new Set(module.includedImports);
  14668. // when we are not preserving modules, we need to make all namespace variables available for
  14669. // rendering the namespace object
  14670. if (!this.outputOptions.preserveModules) {
  14671. if (this.includedNamespaces.has(module)) {
  14672. const memberVariables = module.namespace.getMemberVariables();
  14673. for (const variable of Object.values(memberVariables)) {
  14674. moduleImports.add(variable);
  14675. }
  14676. }
  14677. }
  14678. for (let variable of moduleImports) {
  14679. if (variable instanceof ExportDefaultVariable) {
  14680. variable = variable.getOriginalVariable();
  14681. }
  14682. if (variable instanceof SyntheticNamedExportVariable) {
  14683. variable = variable.getBaseVariable();
  14684. }
  14685. const chunk = this.chunkByModule.get(variable.module);
  14686. if (chunk !== this) {
  14687. this.imports.add(variable);
  14688. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  14689. variable.module instanceof Module) {
  14690. chunk.exports.add(variable);
  14691. this.checkCircularDependencyImport(variable, module);
  14692. }
  14693. }
  14694. }
  14695. if (this.includedNamespaces.has(module) ||
  14696. (module.info.isEntry && module.preserveSignature !== false) ||
  14697. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  14698. this.ensureReexportsAreAvailableForModule(module);
  14699. }
  14700. for (const { node, resolution } of module.dynamicImports) {
  14701. if (node.included &&
  14702. resolution instanceof Module &&
  14703. this.chunkByModule.get(resolution) === this &&
  14704. !this.includedNamespaces.has(resolution)) {
  14705. this.includedNamespaces.add(resolution);
  14706. this.ensureReexportsAreAvailableForModule(resolution);
  14707. }
  14708. }
  14709. }
  14710. }
  14711. function getChunkNameFromModule(module) {
  14712. var _a, _b, _c, _d;
  14713. 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));
  14714. }
  14715. const QUERY_HASH_REGEX = /[?#]/;
  14716. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  14717. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  14718. async function createAddons(options, outputPluginDriver) {
  14719. try {
  14720. let [banner, footer, intro, outro] = await Promise.all([
  14721. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  14722. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  14723. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  14724. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  14725. ]);
  14726. if (intro)
  14727. intro += '\n\n';
  14728. if (outro)
  14729. outro = `\n\n${outro}`;
  14730. if (banner.length)
  14731. banner += '\n';
  14732. if (footer.length)
  14733. footer = '\n' + footer;
  14734. return { banner, footer, intro, outro };
  14735. }
  14736. catch (err) {
  14737. return error({
  14738. code: 'ADDON_ERROR',
  14739. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  14740. \tError Message: ${err.message}`
  14741. });
  14742. }
  14743. }
  14744. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  14745. const chunkDefinitions = [];
  14746. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  14747. const manualChunkModulesByAlias = Object.create(null);
  14748. for (const [entry, alias] of manualChunkAliasByEntry) {
  14749. const chunkModules = (manualChunkModulesByAlias[alias] =
  14750. manualChunkModulesByAlias[alias] || []);
  14751. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  14752. }
  14753. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  14754. chunkDefinitions.push({ alias, modules });
  14755. }
  14756. const assignedEntryPointsByModule = new Map();
  14757. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  14758. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  14759. const staticEntries = new Set(entryModules);
  14760. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  14761. const modulesToHandle = new Set([entry]);
  14762. for (const module of modulesToHandle) {
  14763. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  14764. if (dynamicDependentEntryPoints &&
  14765. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  14766. continue;
  14767. }
  14768. else {
  14769. assignedEntryPoints.add(entry);
  14770. }
  14771. for (const dependency of module.getDependenciesToBeIncluded()) {
  14772. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14773. modulesToHandle.add(dependency);
  14774. }
  14775. }
  14776. }
  14777. }
  14778. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  14779. const entriesToCheck = new Set(entryPoints);
  14780. for (const entry of entriesToCheck) {
  14781. if (!containedIn.has(entry)) {
  14782. if (staticEntries.has(entry))
  14783. return false;
  14784. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  14785. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  14786. entriesToCheck.add(dependentEntry);
  14787. }
  14788. }
  14789. }
  14790. return true;
  14791. }
  14792. for (const entry of entryModules) {
  14793. if (!modulesInManualChunks.has(entry)) {
  14794. assignEntryToStaticDependencies(entry, null);
  14795. }
  14796. }
  14797. for (const entry of dynamicEntryModules) {
  14798. if (!modulesInManualChunks.has(entry)) {
  14799. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  14800. }
  14801. }
  14802. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  14803. return chunkDefinitions;
  14804. }
  14805. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  14806. const modulesToHandle = new Set([entry]);
  14807. for (const module of modulesToHandle) {
  14808. modulesInManualChunks.add(module);
  14809. manualChunkModules.push(module);
  14810. for (const dependency of module.dependencies) {
  14811. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14812. modulesToHandle.add(dependency);
  14813. }
  14814. }
  14815. }
  14816. }
  14817. function analyzeModuleGraph(entryModules) {
  14818. const dynamicEntryModules = new Set();
  14819. const dependentEntryPointsByModule = new Map();
  14820. const entriesToHandle = new Set(entryModules);
  14821. for (const currentEntry of entriesToHandle) {
  14822. const modulesToHandle = new Set([currentEntry]);
  14823. for (const module of modulesToHandle) {
  14824. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  14825. for (const dependency of module.getDependenciesToBeIncluded()) {
  14826. if (!(dependency instanceof ExternalModule)) {
  14827. modulesToHandle.add(dependency);
  14828. }
  14829. }
  14830. for (const { resolution } of module.dynamicImports) {
  14831. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  14832. dynamicEntryModules.add(resolution);
  14833. entriesToHandle.add(resolution);
  14834. }
  14835. }
  14836. for (const dependency of module.implicitlyLoadedBefore) {
  14837. dynamicEntryModules.add(dependency);
  14838. entriesToHandle.add(dependency);
  14839. }
  14840. }
  14841. }
  14842. return { dependentEntryPointsByModule, dynamicEntryModules };
  14843. }
  14844. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  14845. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  14846. for (const dynamicEntry of dynamicEntryModules) {
  14847. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  14848. for (const importer of [
  14849. ...dynamicEntry.includedDynamicImporters,
  14850. ...dynamicEntry.implicitlyLoadedAfter
  14851. ]) {
  14852. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  14853. dynamicDependentEntryPoints.add(entryPoint);
  14854. }
  14855. }
  14856. }
  14857. return dynamicallyDependentEntryPointsByDynamicEntry;
  14858. }
  14859. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  14860. const chunkModules = Object.create(null);
  14861. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  14862. let chunkSignature = '';
  14863. for (const entry of allEntryPoints) {
  14864. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  14865. }
  14866. const chunk = chunkModules[chunkSignature];
  14867. if (chunk) {
  14868. chunk.push(module);
  14869. }
  14870. else {
  14871. chunkModules[chunkSignature] = [module];
  14872. }
  14873. }
  14874. return Object.values(chunkModules).map(modules => ({
  14875. alias: null,
  14876. modules
  14877. }));
  14878. }
  14879. // ported from https://github.com/substack/node-commondir
  14880. function commondir(files) {
  14881. if (files.length === 0)
  14882. return '/';
  14883. if (files.length === 1)
  14884. return require$$0.dirname(files[0]);
  14885. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  14886. const pathSegements = file.split(/\/+|\\+/);
  14887. let i;
  14888. for (i = 0; commonSegments[i] === pathSegements[i] &&
  14889. i < Math.min(commonSegments.length, pathSegements.length); i++)
  14890. ;
  14891. return commonSegments.slice(0, i);
  14892. }, files[0].split(/\/+|\\+/));
  14893. // Windows correctly handles paths with forward-slashes
  14894. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  14895. }
  14896. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  14897. function sortByExecutionOrder(units) {
  14898. units.sort(compareExecIndex);
  14899. }
  14900. function analyseModuleExecution(entryModules) {
  14901. let nextExecIndex = 0;
  14902. const cyclePaths = [];
  14903. const analysedModules = new Set();
  14904. const dynamicImports = new Set();
  14905. const parents = new Map();
  14906. const orderedModules = [];
  14907. const analyseModule = (module) => {
  14908. if (module instanceof Module) {
  14909. for (const dependency of module.dependencies) {
  14910. if (parents.has(dependency)) {
  14911. if (!analysedModules.has(dependency)) {
  14912. cyclePaths.push(getCyclePath(dependency, module, parents));
  14913. }
  14914. continue;
  14915. }
  14916. parents.set(dependency, module);
  14917. analyseModule(dependency);
  14918. }
  14919. for (const dependency of module.implicitlyLoadedBefore) {
  14920. dynamicImports.add(dependency);
  14921. }
  14922. for (const { resolution } of module.dynamicImports) {
  14923. if (resolution instanceof Module) {
  14924. dynamicImports.add(resolution);
  14925. }
  14926. }
  14927. orderedModules.push(module);
  14928. }
  14929. module.execIndex = nextExecIndex++;
  14930. analysedModules.add(module);
  14931. };
  14932. for (const curEntry of entryModules) {
  14933. if (!parents.has(curEntry)) {
  14934. parents.set(curEntry, null);
  14935. analyseModule(curEntry);
  14936. }
  14937. }
  14938. for (const curEntry of dynamicImports) {
  14939. if (!parents.has(curEntry)) {
  14940. parents.set(curEntry, null);
  14941. analyseModule(curEntry);
  14942. }
  14943. }
  14944. return { cyclePaths, orderedModules };
  14945. }
  14946. function getCyclePath(module, parent, parents) {
  14947. const cycleSymbol = Symbol(module.id);
  14948. const path = [relativeId(module.id)];
  14949. let nextModule = parent;
  14950. module.cycles.add(cycleSymbol);
  14951. while (nextModule !== module) {
  14952. nextModule.cycles.add(cycleSymbol);
  14953. path.push(relativeId(nextModule.id));
  14954. nextModule = parents.get(nextModule);
  14955. }
  14956. path.push(path[0]);
  14957. path.reverse();
  14958. return path;
  14959. }
  14960. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  14961. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  14962. const cnst = constBindings ? 'const' : 'var';
  14963. const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
  14964. const getFunctionIntro = arrowFunctions
  14965. ? (params, { isAsync, name }) => {
  14966. const singleParam = params.length === 1;
  14967. const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
  14968. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
  14969. }
  14970. : getNonArrowFunctionIntro;
  14971. const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
  14972. `${getFunctionIntro(params, {
  14973. isAsync: false,
  14974. name
  14975. })}${arrowFunctions
  14976. ? lineBreakIndent
  14977. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  14978. : ''
  14979. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  14980. arrowFunctions
  14981. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  14982. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  14983. ];
  14984. const isValidPropName = reservedNamesAsProps
  14985. ? (name) => validPropName.test(name)
  14986. : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
  14987. return {
  14988. _,
  14989. cnst,
  14990. getDirectReturnFunction,
  14991. getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  14992. const [left, right] = getDirectReturnFunction(params, {
  14993. functionReturn: true,
  14994. lineBreakIndent: null,
  14995. name: null
  14996. });
  14997. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  14998. },
  14999. getFunctionIntro,
  15000. getNonArrowFunctionIntro,
  15001. getObject(fields, { lineBreakIndent }) {
  15002. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  15003. return `{${fields
  15004. .map(([key, value]) => {
  15005. if (key === null)
  15006. return `${prefix}${value}`;
  15007. const needsQuotes = !isValidPropName(key);
  15008. return key === value && objectShorthand && !needsQuotes
  15009. ? prefix + key
  15010. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  15011. })
  15012. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  15013. },
  15014. getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  15015. n,
  15016. s
  15017. };
  15018. }
  15019. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  15020. const validPropName = /^(?!\d)[\w$]+$/;
  15021. class Bundle {
  15022. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  15023. this.outputOptions = outputOptions;
  15024. this.unsetOptions = unsetOptions;
  15025. this.inputOptions = inputOptions;
  15026. this.pluginDriver = pluginDriver;
  15027. this.graph = graph;
  15028. this.facadeChunkByModule = new Map();
  15029. this.includedNamespaces = new Set();
  15030. }
  15031. async generate(isWrite) {
  15032. timeStart('GENERATE', 1);
  15033. const outputBundleBase = Object.create(null);
  15034. const outputBundle = getOutputBundle(outputBundleBase);
  15035. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  15036. try {
  15037. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  15038. timeStart('generate chunks', 2);
  15039. const chunks = await this.generateChunks();
  15040. if (chunks.length > 1) {
  15041. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  15042. }
  15043. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  15044. timeEnd('generate chunks', 2);
  15045. timeStart('render modules', 2);
  15046. // We need to create addons before prerender because at the moment, there
  15047. // can be no async code between prerender and render due to internal state
  15048. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  15049. const snippets = getGenerateCodeSnippets(this.outputOptions);
  15050. this.prerenderChunks(chunks, inputBase, snippets);
  15051. timeEnd('render modules', 2);
  15052. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
  15053. }
  15054. catch (err) {
  15055. await this.pluginDriver.hookParallel('renderError', [err]);
  15056. throw err;
  15057. }
  15058. await this.pluginDriver.hookSeq('generateBundle', [
  15059. this.outputOptions,
  15060. outputBundle,
  15061. isWrite
  15062. ]);
  15063. this.finaliseAssets(outputBundle);
  15064. timeEnd('GENERATE', 1);
  15065. return outputBundleBase;
  15066. }
  15067. async addFinalizedChunksToBundle(chunks, inputBase, addons, bundle, snippets) {
  15068. this.assignChunkIds(chunks, inputBase, addons, bundle);
  15069. for (const chunk of chunks) {
  15070. bundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  15071. }
  15072. await Promise.all(chunks.map(async (chunk) => {
  15073. const outputChunk = bundle[chunk.id];
  15074. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
  15075. }));
  15076. }
  15077. async addManualChunks(manualChunks) {
  15078. const manualChunkAliasByEntry = new Map();
  15079. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  15080. alias,
  15081. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  15082. })));
  15083. for (const { alias, entries } of chunkEntries) {
  15084. for (const entry of entries) {
  15085. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  15086. }
  15087. }
  15088. return manualChunkAliasByEntry;
  15089. }
  15090. assignChunkIds(chunks, inputBase, addons, bundle) {
  15091. const entryChunks = [];
  15092. const otherChunks = [];
  15093. for (const chunk of chunks) {
  15094. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  15095. ? entryChunks
  15096. : otherChunks).push(chunk);
  15097. }
  15098. // make sure entry chunk names take precedence with regard to deconflicting
  15099. const chunksForNaming = entryChunks.concat(otherChunks);
  15100. for (const chunk of chunksForNaming) {
  15101. if (this.outputOptions.file) {
  15102. chunk.id = require$$0.basename(this.outputOptions.file);
  15103. }
  15104. else if (this.outputOptions.preserveModules) {
  15105. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  15106. }
  15107. else {
  15108. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  15109. }
  15110. bundle[chunk.id] = FILE_PLACEHOLDER;
  15111. }
  15112. }
  15113. assignManualChunks(getManualChunk) {
  15114. const manualChunkAliasesWithEntry = [];
  15115. const manualChunksApi = {
  15116. getModuleIds: () => this.graph.modulesById.keys(),
  15117. getModuleInfo: this.graph.getModuleInfo
  15118. };
  15119. for (const module of this.graph.modulesById.values()) {
  15120. if (module instanceof Module) {
  15121. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  15122. if (typeof manualChunkAlias === 'string') {
  15123. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  15124. }
  15125. }
  15126. }
  15127. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  15128. const manualChunkAliasByEntry = new Map();
  15129. for (const [alias, module] of manualChunkAliasesWithEntry) {
  15130. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  15131. }
  15132. return manualChunkAliasByEntry;
  15133. }
  15134. finaliseAssets(outputBundle) {
  15135. for (const file of Object.values(outputBundle)) {
  15136. if (!file.type) {
  15137. 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);
  15138. file.type = 'asset';
  15139. }
  15140. if (this.outputOptions.validate && 'code' in file) {
  15141. try {
  15142. this.graph.contextParse(file.code, {
  15143. allowHashBang: true,
  15144. ecmaVersion: 'latest'
  15145. });
  15146. }
  15147. catch (err) {
  15148. this.inputOptions.onwarn(errChunkInvalid(file, err));
  15149. }
  15150. }
  15151. }
  15152. this.pluginDriver.finaliseAssets();
  15153. }
  15154. async generateChunks() {
  15155. const { manualChunks } = this.outputOptions;
  15156. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  15157. ? await this.addManualChunks(manualChunks)
  15158. : this.assignManualChunks(manualChunks);
  15159. const chunks = [];
  15160. const chunkByModule = new Map();
  15161. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  15162. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  15163. : this.outputOptions.preserveModules
  15164. ? getIncludedModules(this.graph.modulesById).map(module => ({
  15165. alias: null,
  15166. modules: [module]
  15167. }))
  15168. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  15169. sortByExecutionOrder(modules);
  15170. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  15171. chunks.push(chunk);
  15172. for (const module of modules) {
  15173. chunkByModule.set(module, chunk);
  15174. }
  15175. }
  15176. for (const chunk of chunks) {
  15177. chunk.link();
  15178. }
  15179. const facades = [];
  15180. for (const chunk of chunks) {
  15181. facades.push(...chunk.generateFacades());
  15182. }
  15183. return [...chunks, ...facades];
  15184. }
  15185. prerenderChunks(chunks, inputBase, snippets) {
  15186. for (const chunk of chunks) {
  15187. chunk.generateExports();
  15188. }
  15189. for (const chunk of chunks) {
  15190. chunk.preRender(this.outputOptions, inputBase, snippets);
  15191. }
  15192. }
  15193. }
  15194. function getAbsoluteEntryModulePaths(chunks) {
  15195. const absoluteEntryModulePaths = [];
  15196. for (const chunk of chunks) {
  15197. for (const entryModule of chunk.entryModules) {
  15198. if (isAbsolute(entryModule.id)) {
  15199. absoluteEntryModulePaths.push(entryModule.id);
  15200. }
  15201. }
  15202. }
  15203. return absoluteEntryModulePaths;
  15204. }
  15205. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  15206. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  15207. return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  15208. if (typeof outputOptions.file === 'string')
  15209. 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'));
  15210. if (outputOptions.sourcemapFile)
  15211. return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
  15212. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  15213. 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'));
  15214. }
  15215. function getIncludedModules(modulesById) {
  15216. return [...modulesById.values()].filter((module) => module instanceof Module &&
  15217. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  15218. }
  15219. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  15220. const existingAlias = manualChunkAliasByEntry.get(module);
  15221. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  15222. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  15223. }
  15224. manualChunkAliasByEntry.set(module, alias);
  15225. }
  15226. // This file was generated. Do not modify manually!
  15227. 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];
  15228. // This file was generated. Do not modify manually!
  15229. 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];
  15230. // This file was generated. Do not modify manually!
  15231. 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";
  15232. // This file was generated. Do not modify manually!
  15233. 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";
  15234. // These are a run-length and offset encoded representation of the
  15235. // Reserved word lists for various dialects of the language
  15236. var reservedWords = {
  15237. 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",
  15238. 5: "class enum extends super const export import",
  15239. 6: "enum",
  15240. strict: "implements interface let package private protected public static yield",
  15241. strictBind: "eval arguments"
  15242. };
  15243. // And the keywords
  15244. 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";
  15245. var keywords$1 = {
  15246. 5: ecma5AndLessKeywords,
  15247. "5module": ecma5AndLessKeywords + " export import",
  15248. 6: ecma5AndLessKeywords + " const class extends export import super"
  15249. };
  15250. var keywordRelationalOperator = /^in(stanceof)?$/;
  15251. // ## Character categories
  15252. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  15253. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  15254. // This has a complexity linear to the value of the code. The
  15255. // assumption is that looking up astral identifier characters is
  15256. // rare.
  15257. function isInAstralSet(code, set) {
  15258. var pos = 0x10000;
  15259. for (var i = 0; i < set.length; i += 2) {
  15260. pos += set[i];
  15261. if (pos > code) { return false }
  15262. pos += set[i + 1];
  15263. if (pos >= code) { return true }
  15264. }
  15265. }
  15266. // Test whether a given character code starts an identifier.
  15267. function isIdentifierStart(code, astral) {
  15268. if (code < 65) { return code === 36 }
  15269. if (code < 91) { return true }
  15270. if (code < 97) { return code === 95 }
  15271. if (code < 123) { return true }
  15272. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  15273. if (astral === false) { return false }
  15274. return isInAstralSet(code, astralIdentifierStartCodes)
  15275. }
  15276. // Test whether a given character is part of an identifier.
  15277. function isIdentifierChar(code, astral) {
  15278. if (code < 48) { return code === 36 }
  15279. if (code < 58) { return true }
  15280. if (code < 65) { return false }
  15281. if (code < 91) { return true }
  15282. if (code < 97) { return code === 95 }
  15283. if (code < 123) { return true }
  15284. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  15285. if (astral === false) { return false }
  15286. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  15287. }
  15288. // ## Token types
  15289. // The assignment of fine-grained, information-carrying type objects
  15290. // allows the tokenizer to store the information it has about a
  15291. // token in a way that is very cheap for the parser to look up.
  15292. // All token type variables start with an underscore, to make them
  15293. // easy to recognize.
  15294. // The `beforeExpr` property is used to disambiguate between regular
  15295. // expressions and divisions. It is set on all token types that can
  15296. // be followed by an expression (thus, a slash after them would be a
  15297. // regular expression).
  15298. //
  15299. // The `startsExpr` property is used to check if the token ends a
  15300. // `yield` expression. It is set on all token types that either can
  15301. // directly start an expression (like a quotation mark) or can
  15302. // continue an expression (like the body of a string).
  15303. //
  15304. // `isLoop` marks a keyword as starting a loop, which is important
  15305. // to know when parsing a label, in order to allow or disallow
  15306. // continue jumps to that label.
  15307. var TokenType = function TokenType(label, conf) {
  15308. if ( conf === void 0 ) conf = {};
  15309. this.label = label;
  15310. this.keyword = conf.keyword;
  15311. this.beforeExpr = !!conf.beforeExpr;
  15312. this.startsExpr = !!conf.startsExpr;
  15313. this.isLoop = !!conf.isLoop;
  15314. this.isAssign = !!conf.isAssign;
  15315. this.prefix = !!conf.prefix;
  15316. this.postfix = !!conf.postfix;
  15317. this.binop = conf.binop || null;
  15318. this.updateContext = null;
  15319. };
  15320. function binop(name, prec) {
  15321. return new TokenType(name, {beforeExpr: true, binop: prec})
  15322. }
  15323. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  15324. // Map keyword names to token types.
  15325. var keywords = {};
  15326. // Succinct definitions of keyword token types
  15327. function kw(name, options) {
  15328. if ( options === void 0 ) options = {};
  15329. options.keyword = name;
  15330. return keywords[name] = new TokenType(name, options)
  15331. }
  15332. var types$1 = {
  15333. num: new TokenType("num", startsExpr),
  15334. regexp: new TokenType("regexp", startsExpr),
  15335. string: new TokenType("string", startsExpr),
  15336. name: new TokenType("name", startsExpr),
  15337. privateId: new TokenType("privateId", startsExpr),
  15338. eof: new TokenType("eof"),
  15339. // Punctuation token types.
  15340. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  15341. bracketR: new TokenType("]"),
  15342. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  15343. braceR: new TokenType("}"),
  15344. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  15345. parenR: new TokenType(")"),
  15346. comma: new TokenType(",", beforeExpr),
  15347. semi: new TokenType(";", beforeExpr),
  15348. colon: new TokenType(":", beforeExpr),
  15349. dot: new TokenType("."),
  15350. question: new TokenType("?", beforeExpr),
  15351. questionDot: new TokenType("?."),
  15352. arrow: new TokenType("=>", beforeExpr),
  15353. template: new TokenType("template"),
  15354. invalidTemplate: new TokenType("invalidTemplate"),
  15355. ellipsis: new TokenType("...", beforeExpr),
  15356. backQuote: new TokenType("`", startsExpr),
  15357. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  15358. // Operators. These carry several kinds of properties to help the
  15359. // parser use them properly (the presence of these properties is
  15360. // what categorizes them as operators).
  15361. //
  15362. // `binop`, when present, specifies that this operator is a binary
  15363. // operator, and will refer to its precedence.
  15364. //
  15365. // `prefix` and `postfix` mark the operator as a prefix or postfix
  15366. // unary operator.
  15367. //
  15368. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  15369. // binary operators with a very low precedence, that should result
  15370. // in AssignmentExpression nodes.
  15371. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  15372. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  15373. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  15374. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  15375. logicalOR: binop("||", 1),
  15376. logicalAND: binop("&&", 2),
  15377. bitwiseOR: binop("|", 3),
  15378. bitwiseXOR: binop("^", 4),
  15379. bitwiseAND: binop("&", 5),
  15380. equality: binop("==/!=/===/!==", 6),
  15381. relational: binop("</>/<=/>=", 7),
  15382. bitShift: binop("<</>>/>>>", 8),
  15383. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  15384. modulo: binop("%", 10),
  15385. star: binop("*", 10),
  15386. slash: binop("/", 10),
  15387. starstar: new TokenType("**", {beforeExpr: true}),
  15388. coalesce: binop("??", 1),
  15389. // Keyword token types.
  15390. _break: kw("break"),
  15391. _case: kw("case", beforeExpr),
  15392. _catch: kw("catch"),
  15393. _continue: kw("continue"),
  15394. _debugger: kw("debugger"),
  15395. _default: kw("default", beforeExpr),
  15396. _do: kw("do", {isLoop: true, beforeExpr: true}),
  15397. _else: kw("else", beforeExpr),
  15398. _finally: kw("finally"),
  15399. _for: kw("for", {isLoop: true}),
  15400. _function: kw("function", startsExpr),
  15401. _if: kw("if"),
  15402. _return: kw("return", beforeExpr),
  15403. _switch: kw("switch"),
  15404. _throw: kw("throw", beforeExpr),
  15405. _try: kw("try"),
  15406. _var: kw("var"),
  15407. _const: kw("const"),
  15408. _while: kw("while", {isLoop: true}),
  15409. _with: kw("with"),
  15410. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  15411. _this: kw("this", startsExpr),
  15412. _super: kw("super", startsExpr),
  15413. _class: kw("class", startsExpr),
  15414. _extends: kw("extends", beforeExpr),
  15415. _export: kw("export"),
  15416. _import: kw("import", startsExpr),
  15417. _null: kw("null", startsExpr),
  15418. _true: kw("true", startsExpr),
  15419. _false: kw("false", startsExpr),
  15420. _in: kw("in", {beforeExpr: true, binop: 7}),
  15421. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  15422. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  15423. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  15424. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  15425. };
  15426. // Matches a whole line break (where CRLF is considered a single
  15427. // line break). Used to count lines.
  15428. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  15429. var lineBreakG = new RegExp(lineBreak.source, "g");
  15430. function isNewLine(code) {
  15431. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  15432. }
  15433. function nextLineBreak(code, from, end) {
  15434. if ( end === void 0 ) end = code.length;
  15435. for (var i = from; i < end; i++) {
  15436. var next = code.charCodeAt(i);
  15437. if (isNewLine(next))
  15438. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  15439. }
  15440. return -1
  15441. }
  15442. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  15443. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  15444. var ref = Object.prototype;
  15445. var hasOwnProperty = ref.hasOwnProperty;
  15446. var toString = ref.toString;
  15447. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  15448. hasOwnProperty.call(obj, propName)
  15449. ); });
  15450. var isArray = Array.isArray || (function (obj) { return (
  15451. toString.call(obj) === "[object Array]"
  15452. ); });
  15453. function wordsRegexp(words) {
  15454. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  15455. }
  15456. function codePointToString(code) {
  15457. // UTF-16 Decoding
  15458. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  15459. code -= 0x10000;
  15460. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  15461. }
  15462. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  15463. // These are used when `options.locations` is on, for the
  15464. // `startLoc` and `endLoc` properties.
  15465. var Position = function Position(line, col) {
  15466. this.line = line;
  15467. this.column = col;
  15468. };
  15469. Position.prototype.offset = function offset (n) {
  15470. return new Position(this.line, this.column + n)
  15471. };
  15472. var SourceLocation = function SourceLocation(p, start, end) {
  15473. this.start = start;
  15474. this.end = end;
  15475. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  15476. };
  15477. // The `getLineInfo` function is mostly useful when the
  15478. // `locations` option is off (for performance reasons) and you
  15479. // want to find the line/column position for a given character
  15480. // offset. `input` should be the code string that the offset refers
  15481. // into.
  15482. function getLineInfo(input, offset) {
  15483. for (var line = 1, cur = 0;;) {
  15484. var nextBreak = nextLineBreak(input, cur, offset);
  15485. if (nextBreak < 0) { return new Position(line, offset - cur) }
  15486. ++line;
  15487. cur = nextBreak;
  15488. }
  15489. }
  15490. // A second argument must be given to configure the parser process.
  15491. // These options are recognized (only `ecmaVersion` is required):
  15492. var defaultOptions = {
  15493. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  15494. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  15495. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  15496. // latest version the library supports). This influences support
  15497. // for strict mode, the set of reserved words, and support for
  15498. // new syntax features.
  15499. ecmaVersion: null,
  15500. // `sourceType` indicates the mode the code should be parsed in.
  15501. // Can be either `"script"` or `"module"`. This influences global
  15502. // strict mode and parsing of `import` and `export` declarations.
  15503. sourceType: "script",
  15504. // `onInsertedSemicolon` can be a callback that will be called
  15505. // when a semicolon is automatically inserted. It will be passed
  15506. // the position of the comma as an offset, and if `locations` is
  15507. // enabled, it is given the location as a `{line, column}` object
  15508. // as second argument.
  15509. onInsertedSemicolon: null,
  15510. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  15511. // trailing commas.
  15512. onTrailingComma: null,
  15513. // By default, reserved words are only enforced if ecmaVersion >= 5.
  15514. // Set `allowReserved` to a boolean value to explicitly turn this on
  15515. // an off. When this option has the value "never", reserved words
  15516. // and keywords can also not be used as property names.
  15517. allowReserved: null,
  15518. // When enabled, a return at the top level is not considered an
  15519. // error.
  15520. allowReturnOutsideFunction: false,
  15521. // When enabled, import/export statements are not constrained to
  15522. // appearing at the top of the program, and an import.meta expression
  15523. // in a script isn't considered an error.
  15524. allowImportExportEverywhere: false,
  15525. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  15526. // When enabled, await identifiers are allowed to appear at the top-level scope,
  15527. // but they are still not allowed in non-async functions.
  15528. allowAwaitOutsideFunction: null,
  15529. // When enabled, super identifiers are not constrained to
  15530. // appearing in methods and do not raise an error when they appear elsewhere.
  15531. allowSuperOutsideMethod: null,
  15532. // When enabled, hashbang directive in the beginning of file
  15533. // is allowed and treated as a line comment.
  15534. allowHashBang: false,
  15535. // When `locations` is on, `loc` properties holding objects with
  15536. // `start` and `end` properties in `{line, column}` form (with
  15537. // line being 1-based and column 0-based) will be attached to the
  15538. // nodes.
  15539. locations: false,
  15540. // A function can be passed as `onToken` option, which will
  15541. // cause Acorn to call that function with object in the same
  15542. // format as tokens returned from `tokenizer().getToken()`. Note
  15543. // that you are not allowed to call the parser from the
  15544. // callback—that will corrupt its internal state.
  15545. onToken: null,
  15546. // A function can be passed as `onComment` option, which will
  15547. // cause Acorn to call that function with `(block, text, start,
  15548. // end)` parameters whenever a comment is skipped. `block` is a
  15549. // boolean indicating whether this is a block (`/* */`) comment,
  15550. // `text` is the content of the comment, and `start` and `end` are
  15551. // character offsets that denote the start and end of the comment.
  15552. // When the `locations` option is on, two more parameters are
  15553. // passed, the full `{line, column}` locations of the start and
  15554. // end of the comments. Note that you are not allowed to call the
  15555. // parser from the callback—that will corrupt its internal state.
  15556. onComment: null,
  15557. // Nodes have their start and end characters offsets recorded in
  15558. // `start` and `end` properties (directly on the node, rather than
  15559. // the `loc` object, which holds line/column data. To also add a
  15560. // [semi-standardized][range] `range` property holding a `[start,
  15561. // end]` array with the same numbers, set the `ranges` option to
  15562. // `true`.
  15563. //
  15564. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  15565. ranges: false,
  15566. // It is possible to parse multiple files into a single AST by
  15567. // passing the tree produced by parsing the first file as
  15568. // `program` option in subsequent parses. This will add the
  15569. // toplevel forms of the parsed file to the `Program` (top) node
  15570. // of an existing parse tree.
  15571. program: null,
  15572. // When `locations` is on, you can pass this to record the source
  15573. // file in every node's `loc` object.
  15574. sourceFile: null,
  15575. // This value, if given, is stored in every node, whether
  15576. // `locations` is on or off.
  15577. directSourceFile: null,
  15578. // When enabled, parenthesized expressions are represented by
  15579. // (non-standard) ParenthesizedExpression nodes
  15580. preserveParens: false
  15581. };
  15582. // Interpret and default an options object
  15583. var warnedAboutEcmaVersion = false;
  15584. function getOptions(opts) {
  15585. var options = {};
  15586. for (var opt in defaultOptions)
  15587. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  15588. if (options.ecmaVersion === "latest") {
  15589. options.ecmaVersion = 1e8;
  15590. } else if (options.ecmaVersion == null) {
  15591. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  15592. warnedAboutEcmaVersion = true;
  15593. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  15594. }
  15595. options.ecmaVersion = 11;
  15596. } else if (options.ecmaVersion >= 2015) {
  15597. options.ecmaVersion -= 2009;
  15598. }
  15599. if (options.allowReserved == null)
  15600. { options.allowReserved = options.ecmaVersion < 5; }
  15601. if (isArray(options.onToken)) {
  15602. var tokens = options.onToken;
  15603. options.onToken = function (token) { return tokens.push(token); };
  15604. }
  15605. if (isArray(options.onComment))
  15606. { options.onComment = pushComment(options, options.onComment); }
  15607. return options
  15608. }
  15609. function pushComment(options, array) {
  15610. return function(block, text, start, end, startLoc, endLoc) {
  15611. var comment = {
  15612. type: block ? "Block" : "Line",
  15613. value: text,
  15614. start: start,
  15615. end: end
  15616. };
  15617. if (options.locations)
  15618. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  15619. if (options.ranges)
  15620. { comment.range = [start, end]; }
  15621. array.push(comment);
  15622. }
  15623. }
  15624. // Each scope gets a bitset that may contain these flags
  15625. var
  15626. SCOPE_TOP = 1,
  15627. SCOPE_FUNCTION = 2,
  15628. SCOPE_ASYNC = 4,
  15629. SCOPE_GENERATOR = 8,
  15630. SCOPE_ARROW = 16,
  15631. SCOPE_SIMPLE_CATCH = 32,
  15632. SCOPE_SUPER = 64,
  15633. SCOPE_DIRECT_SUPER = 128,
  15634. SCOPE_CLASS_STATIC_BLOCK = 256,
  15635. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  15636. function functionFlags(async, generator) {
  15637. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  15638. }
  15639. // Used in checkLVal* and declareName to determine the type of a binding
  15640. var
  15641. BIND_NONE = 0, // Not a binding
  15642. BIND_VAR = 1, // Var-style binding
  15643. BIND_LEXICAL = 2, // Let- or const-style binding
  15644. BIND_FUNCTION = 3, // Function declaration
  15645. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  15646. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  15647. var Parser = function Parser(options, input, startPos) {
  15648. this.options = options = getOptions(options);
  15649. this.sourceFile = options.sourceFile;
  15650. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  15651. var reserved = "";
  15652. if (options.allowReserved !== true) {
  15653. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  15654. if (options.sourceType === "module") { reserved += " await"; }
  15655. }
  15656. this.reservedWords = wordsRegexp(reserved);
  15657. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  15658. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  15659. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  15660. this.input = String(input);
  15661. // Used to signal to callers of `readWord1` whether the word
  15662. // contained any escape sequences. This is needed because words with
  15663. // escape sequences must not be interpreted as keywords.
  15664. this.containsEsc = false;
  15665. // Set up token state
  15666. // The current position of the tokenizer in the input.
  15667. if (startPos) {
  15668. this.pos = startPos;
  15669. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  15670. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  15671. } else {
  15672. this.pos = this.lineStart = 0;
  15673. this.curLine = 1;
  15674. }
  15675. // Properties of the current token:
  15676. // Its type
  15677. this.type = types$1.eof;
  15678. // For tokens that include more information than their type, the value
  15679. this.value = null;
  15680. // Its start and end offset
  15681. this.start = this.end = this.pos;
  15682. // And, if locations are used, the {line, column} object
  15683. // corresponding to those offsets
  15684. this.startLoc = this.endLoc = this.curPosition();
  15685. // Position information for the previous token
  15686. this.lastTokEndLoc = this.lastTokStartLoc = null;
  15687. this.lastTokStart = this.lastTokEnd = this.pos;
  15688. // The context stack is used to superficially track syntactic
  15689. // context to predict whether a regular expression is allowed in a
  15690. // given position.
  15691. this.context = this.initialContext();
  15692. this.exprAllowed = true;
  15693. // Figure out if it's a module code.
  15694. this.inModule = options.sourceType === "module";
  15695. this.strict = this.inModule || this.strictDirective(this.pos);
  15696. // Used to signify the start of a potential arrow function
  15697. this.potentialArrowAt = -1;
  15698. this.potentialArrowInForAwait = false;
  15699. // Positions to delayed-check that yield/await does not exist in default parameters.
  15700. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  15701. // Labels in scope.
  15702. this.labels = [];
  15703. // Thus-far undefined exports.
  15704. this.undefinedExports = Object.create(null);
  15705. // If enabled, skip leading hashbang line.
  15706. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  15707. { this.skipLineComment(2); }
  15708. // Scope tracking for duplicate variable names (see scope.js)
  15709. this.scopeStack = [];
  15710. this.enterScope(SCOPE_TOP);
  15711. // For RegExp validation
  15712. this.regexpState = null;
  15713. // The stack of private names.
  15714. // Each element has two properties: 'declared' and 'used'.
  15715. // When it exited from the outermost class definition, all used private names must be declared.
  15716. this.privateNameStack = [];
  15717. };
  15718. 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 } };
  15719. Parser.prototype.parse = function parse () {
  15720. var node = this.options.program || this.startNode();
  15721. this.nextToken();
  15722. return this.parseTopLevel(node)
  15723. };
  15724. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  15725. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  15726. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  15727. prototypeAccessors.canAwait.get = function () {
  15728. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  15729. var scope = this.scopeStack[i];
  15730. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  15731. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  15732. }
  15733. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  15734. };
  15735. prototypeAccessors.allowSuper.get = function () {
  15736. var ref = this.currentThisScope();
  15737. var flags = ref.flags;
  15738. var inClassFieldInit = ref.inClassFieldInit;
  15739. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  15740. };
  15741. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  15742. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  15743. prototypeAccessors.allowNewDotTarget.get = function () {
  15744. var ref = this.currentThisScope();
  15745. var flags = ref.flags;
  15746. var inClassFieldInit = ref.inClassFieldInit;
  15747. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  15748. };
  15749. prototypeAccessors.inClassStaticBlock.get = function () {
  15750. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  15751. };
  15752. Parser.extend = function extend () {
  15753. var plugins = [], len = arguments.length;
  15754. while ( len-- ) plugins[ len ] = arguments[ len ];
  15755. var cls = this;
  15756. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  15757. return cls
  15758. };
  15759. Parser.parse = function parse (input, options) {
  15760. return new this(options, input).parse()
  15761. };
  15762. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  15763. var parser = new this(options, input, pos);
  15764. parser.nextToken();
  15765. return parser.parseExpression()
  15766. };
  15767. Parser.tokenizer = function tokenizer (input, options) {
  15768. return new this(options, input)
  15769. };
  15770. Object.defineProperties( Parser.prototype, prototypeAccessors );
  15771. var pp$9 = Parser.prototype;
  15772. // ## Parser utilities
  15773. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  15774. pp$9.strictDirective = function(start) {
  15775. if (this.options.ecmaVersion < 5) { return false }
  15776. for (;;) {
  15777. // Try to find string literal.
  15778. skipWhiteSpace.lastIndex = start;
  15779. start += skipWhiteSpace.exec(this.input)[0].length;
  15780. var match = literal.exec(this.input.slice(start));
  15781. if (!match) { return false }
  15782. if ((match[1] || match[2]) === "use strict") {
  15783. skipWhiteSpace.lastIndex = start + match[0].length;
  15784. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  15785. var next = this.input.charAt(end);
  15786. return next === ";" || next === "}" ||
  15787. (lineBreak.test(spaceAfter[0]) &&
  15788. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  15789. }
  15790. start += match[0].length;
  15791. // Skip semicolon, if any.
  15792. skipWhiteSpace.lastIndex = start;
  15793. start += skipWhiteSpace.exec(this.input)[0].length;
  15794. if (this.input[start] === ";")
  15795. { start++; }
  15796. }
  15797. };
  15798. // Predicate that tests whether the next token is of the given
  15799. // type, and if yes, consumes it as a side effect.
  15800. pp$9.eat = function(type) {
  15801. if (this.type === type) {
  15802. this.next();
  15803. return true
  15804. } else {
  15805. return false
  15806. }
  15807. };
  15808. // Tests whether parsed token is a contextual keyword.
  15809. pp$9.isContextual = function(name) {
  15810. return this.type === types$1.name && this.value === name && !this.containsEsc
  15811. };
  15812. // Consumes contextual keyword if possible.
  15813. pp$9.eatContextual = function(name) {
  15814. if (!this.isContextual(name)) { return false }
  15815. this.next();
  15816. return true
  15817. };
  15818. // Asserts that following token is given contextual keyword.
  15819. pp$9.expectContextual = function(name) {
  15820. if (!this.eatContextual(name)) { this.unexpected(); }
  15821. };
  15822. // Test whether a semicolon can be inserted at the current position.
  15823. pp$9.canInsertSemicolon = function() {
  15824. return this.type === types$1.eof ||
  15825. this.type === types$1.braceR ||
  15826. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15827. };
  15828. pp$9.insertSemicolon = function() {
  15829. if (this.canInsertSemicolon()) {
  15830. if (this.options.onInsertedSemicolon)
  15831. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  15832. return true
  15833. }
  15834. };
  15835. // Consume a semicolon, or, failing that, see if we are allowed to
  15836. // pretend that there is a semicolon at this position.
  15837. pp$9.semicolon = function() {
  15838. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  15839. };
  15840. pp$9.afterTrailingComma = function(tokType, notNext) {
  15841. if (this.type === tokType) {
  15842. if (this.options.onTrailingComma)
  15843. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  15844. if (!notNext)
  15845. { this.next(); }
  15846. return true
  15847. }
  15848. };
  15849. // Expect a token of a given type. If found, consume it, otherwise,
  15850. // raise an unexpected token error.
  15851. pp$9.expect = function(type) {
  15852. this.eat(type) || this.unexpected();
  15853. };
  15854. // Raise an unexpected token error.
  15855. pp$9.unexpected = function(pos) {
  15856. this.raise(pos != null ? pos : this.start, "Unexpected token");
  15857. };
  15858. var DestructuringErrors = function DestructuringErrors() {
  15859. this.shorthandAssign =
  15860. this.trailingComma =
  15861. this.parenthesizedAssign =
  15862. this.parenthesizedBind =
  15863. this.doubleProto =
  15864. -1;
  15865. };
  15866. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  15867. if (!refDestructuringErrors) { return }
  15868. if (refDestructuringErrors.trailingComma > -1)
  15869. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  15870. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  15871. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  15872. };
  15873. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  15874. if (!refDestructuringErrors) { return false }
  15875. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  15876. var doubleProto = refDestructuringErrors.doubleProto;
  15877. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  15878. if (shorthandAssign >= 0)
  15879. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  15880. if (doubleProto >= 0)
  15881. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  15882. };
  15883. pp$9.checkYieldAwaitInDefaultParams = function() {
  15884. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  15885. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  15886. if (this.awaitPos)
  15887. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  15888. };
  15889. pp$9.isSimpleAssignTarget = function(expr) {
  15890. if (expr.type === "ParenthesizedExpression")
  15891. { return this.isSimpleAssignTarget(expr.expression) }
  15892. return expr.type === "Identifier" || expr.type === "MemberExpression"
  15893. };
  15894. var pp$8 = Parser.prototype;
  15895. // ### Statement parsing
  15896. // Parse a program. Initializes the parser, reads any number of
  15897. // statements, and wraps them in a Program node. Optionally takes a
  15898. // `program` argument. If present, the statements will be appended
  15899. // to its body instead of creating a new node.
  15900. pp$8.parseTopLevel = function(node) {
  15901. var exports = Object.create(null);
  15902. if (!node.body) { node.body = []; }
  15903. while (this.type !== types$1.eof) {
  15904. var stmt = this.parseStatement(null, true, exports);
  15905. node.body.push(stmt);
  15906. }
  15907. if (this.inModule)
  15908. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  15909. {
  15910. var name = list[i];
  15911. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  15912. } }
  15913. this.adaptDirectivePrologue(node.body);
  15914. this.next();
  15915. node.sourceType = this.options.sourceType;
  15916. return this.finishNode(node, "Program")
  15917. };
  15918. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  15919. pp$8.isLet = function(context) {
  15920. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  15921. skipWhiteSpace.lastIndex = this.pos;
  15922. var skip = skipWhiteSpace.exec(this.input);
  15923. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15924. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  15925. // Statement) is allowed here. If context is not empty then only a Statement
  15926. // is allowed. However, `let [` is an explicit negative lookahead for
  15927. // ExpressionStatement, so special-case it first.
  15928. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  15929. if (context) { return false }
  15930. if (nextCh === 123) { return true } // '{'
  15931. if (isIdentifierStart(nextCh, true)) {
  15932. var pos = next + 1;
  15933. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  15934. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  15935. var ident = this.input.slice(next, pos);
  15936. if (!keywordRelationalOperator.test(ident)) { return true }
  15937. }
  15938. return false
  15939. };
  15940. // check 'async [no LineTerminator here] function'
  15941. // - 'async /*foo*/ function' is OK.
  15942. // - 'async /*\n*/ function' is invalid.
  15943. pp$8.isAsyncFunction = function() {
  15944. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  15945. { return false }
  15946. skipWhiteSpace.lastIndex = this.pos;
  15947. var skip = skipWhiteSpace.exec(this.input);
  15948. var next = this.pos + skip[0].length, after;
  15949. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  15950. this.input.slice(next, next + 8) === "function" &&
  15951. (next + 8 === this.input.length ||
  15952. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  15953. };
  15954. // Parse a single statement.
  15955. //
  15956. // If expecting a statement and finding a slash operator, parse a
  15957. // regular expression literal. This is to handle cases like
  15958. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  15959. // does not help.
  15960. pp$8.parseStatement = function(context, topLevel, exports) {
  15961. var starttype = this.type, node = this.startNode(), kind;
  15962. if (this.isLet(context)) {
  15963. starttype = types$1._var;
  15964. kind = "let";
  15965. }
  15966. // Most types of statements are recognized by the keyword they
  15967. // start with. Many are trivial to parse, some require a bit of
  15968. // complexity.
  15969. switch (starttype) {
  15970. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  15971. case types$1._debugger: return this.parseDebuggerStatement(node)
  15972. case types$1._do: return this.parseDoStatement(node)
  15973. case types$1._for: return this.parseForStatement(node)
  15974. case types$1._function:
  15975. // Function as sole body of either an if statement or a labeled statement
  15976. // works, but not when it is part of a labeled statement that is the sole
  15977. // body of an if statement.
  15978. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  15979. return this.parseFunctionStatement(node, false, !context)
  15980. case types$1._class:
  15981. if (context) { this.unexpected(); }
  15982. return this.parseClass(node, true)
  15983. case types$1._if: return this.parseIfStatement(node)
  15984. case types$1._return: return this.parseReturnStatement(node)
  15985. case types$1._switch: return this.parseSwitchStatement(node)
  15986. case types$1._throw: return this.parseThrowStatement(node)
  15987. case types$1._try: return this.parseTryStatement(node)
  15988. case types$1._const: case types$1._var:
  15989. kind = kind || this.value;
  15990. if (context && kind !== "var") { this.unexpected(); }
  15991. return this.parseVarStatement(node, kind)
  15992. case types$1._while: return this.parseWhileStatement(node)
  15993. case types$1._with: return this.parseWithStatement(node)
  15994. case types$1.braceL: return this.parseBlock(true, node)
  15995. case types$1.semi: return this.parseEmptyStatement(node)
  15996. case types$1._export:
  15997. case types$1._import:
  15998. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  15999. skipWhiteSpace.lastIndex = this.pos;
  16000. var skip = skipWhiteSpace.exec(this.input);
  16001. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  16002. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  16003. { return this.parseExpressionStatement(node, this.parseExpression()) }
  16004. }
  16005. if (!this.options.allowImportExportEverywhere) {
  16006. if (!topLevel)
  16007. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  16008. if (!this.inModule)
  16009. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  16010. }
  16011. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  16012. // If the statement does not start with a statement keyword or a
  16013. // brace, it's an ExpressionStatement or LabeledStatement. We
  16014. // simply start parsing an expression, and afterwards, if the
  16015. // next token is a colon and the expression was a simple
  16016. // Identifier node, we switch to interpreting it as a label.
  16017. default:
  16018. if (this.isAsyncFunction()) {
  16019. if (context) { this.unexpected(); }
  16020. this.next();
  16021. return this.parseFunctionStatement(node, true, !context)
  16022. }
  16023. var maybeName = this.value, expr = this.parseExpression();
  16024. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  16025. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  16026. else { return this.parseExpressionStatement(node, expr) }
  16027. }
  16028. };
  16029. pp$8.parseBreakContinueStatement = function(node, keyword) {
  16030. var isBreak = keyword === "break";
  16031. this.next();
  16032. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  16033. else if (this.type !== types$1.name) { this.unexpected(); }
  16034. else {
  16035. node.label = this.parseIdent();
  16036. this.semicolon();
  16037. }
  16038. // Verify that there is an actual destination to break or
  16039. // continue to.
  16040. var i = 0;
  16041. for (; i < this.labels.length; ++i) {
  16042. var lab = this.labels[i];
  16043. if (node.label == null || lab.name === node.label.name) {
  16044. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  16045. if (node.label && isBreak) { break }
  16046. }
  16047. }
  16048. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  16049. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  16050. };
  16051. pp$8.parseDebuggerStatement = function(node) {
  16052. this.next();
  16053. this.semicolon();
  16054. return this.finishNode(node, "DebuggerStatement")
  16055. };
  16056. pp$8.parseDoStatement = function(node) {
  16057. this.next();
  16058. this.labels.push(loopLabel);
  16059. node.body = this.parseStatement("do");
  16060. this.labels.pop();
  16061. this.expect(types$1._while);
  16062. node.test = this.parseParenExpression();
  16063. if (this.options.ecmaVersion >= 6)
  16064. { this.eat(types$1.semi); }
  16065. else
  16066. { this.semicolon(); }
  16067. return this.finishNode(node, "DoWhileStatement")
  16068. };
  16069. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  16070. // loop is non-trivial. Basically, we have to parse the init `var`
  16071. // statement or expression, disallowing the `in` operator (see
  16072. // the second parameter to `parseExpression`), and then check
  16073. // whether the next token is `in` or `of`. When there is no init
  16074. // part (semicolon immediately after the opening parenthesis), it
  16075. // is a regular `for` loop.
  16076. pp$8.parseForStatement = function(node) {
  16077. this.next();
  16078. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  16079. this.labels.push(loopLabel);
  16080. this.enterScope(0);
  16081. this.expect(types$1.parenL);
  16082. if (this.type === types$1.semi) {
  16083. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16084. return this.parseFor(node, null)
  16085. }
  16086. var isLet = this.isLet();
  16087. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  16088. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  16089. this.next();
  16090. this.parseVar(init$1, true, kind);
  16091. this.finishNode(init$1, "VariableDeclaration");
  16092. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  16093. if (this.options.ecmaVersion >= 9) {
  16094. if (this.type === types$1._in) {
  16095. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16096. } else { node.await = awaitAt > -1; }
  16097. }
  16098. return this.parseForIn(node, init$1)
  16099. }
  16100. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16101. return this.parseFor(node, init$1)
  16102. }
  16103. var startsWithLet = this.isContextual("let"), isForOf = false;
  16104. var refDestructuringErrors = new DestructuringErrors;
  16105. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  16106. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  16107. if (this.options.ecmaVersion >= 9) {
  16108. if (this.type === types$1._in) {
  16109. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16110. } else { node.await = awaitAt > -1; }
  16111. }
  16112. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  16113. this.toAssignable(init, false, refDestructuringErrors);
  16114. this.checkLValPattern(init);
  16115. return this.parseForIn(node, init)
  16116. } else {
  16117. this.checkExpressionErrors(refDestructuringErrors, true);
  16118. }
  16119. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16120. return this.parseFor(node, init)
  16121. };
  16122. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  16123. this.next();
  16124. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  16125. };
  16126. pp$8.parseIfStatement = function(node) {
  16127. this.next();
  16128. node.test = this.parseParenExpression();
  16129. // allow function declarations in branches, but only in non-strict mode
  16130. node.consequent = this.parseStatement("if");
  16131. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  16132. return this.finishNode(node, "IfStatement")
  16133. };
  16134. pp$8.parseReturnStatement = function(node) {
  16135. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  16136. { this.raise(this.start, "'return' outside of function"); }
  16137. this.next();
  16138. // In `return` (and `break`/`continue`), the keywords with
  16139. // optional arguments, we eagerly look for a semicolon or the
  16140. // possibility to insert one.
  16141. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  16142. else { node.argument = this.parseExpression(); this.semicolon(); }
  16143. return this.finishNode(node, "ReturnStatement")
  16144. };
  16145. pp$8.parseSwitchStatement = function(node) {
  16146. this.next();
  16147. node.discriminant = this.parseParenExpression();
  16148. node.cases = [];
  16149. this.expect(types$1.braceL);
  16150. this.labels.push(switchLabel);
  16151. this.enterScope(0);
  16152. // Statements under must be grouped (by label) in SwitchCase
  16153. // nodes. `cur` is used to keep the node that we are currently
  16154. // adding statements to.
  16155. var cur;
  16156. for (var sawDefault = false; this.type !== types$1.braceR;) {
  16157. if (this.type === types$1._case || this.type === types$1._default) {
  16158. var isCase = this.type === types$1._case;
  16159. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16160. node.cases.push(cur = this.startNode());
  16161. cur.consequent = [];
  16162. this.next();
  16163. if (isCase) {
  16164. cur.test = this.parseExpression();
  16165. } else {
  16166. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  16167. sawDefault = true;
  16168. cur.test = null;
  16169. }
  16170. this.expect(types$1.colon);
  16171. } else {
  16172. if (!cur) { this.unexpected(); }
  16173. cur.consequent.push(this.parseStatement(null));
  16174. }
  16175. }
  16176. this.exitScope();
  16177. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16178. this.next(); // Closing brace
  16179. this.labels.pop();
  16180. return this.finishNode(node, "SwitchStatement")
  16181. };
  16182. pp$8.parseThrowStatement = function(node) {
  16183. this.next();
  16184. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  16185. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  16186. node.argument = this.parseExpression();
  16187. this.semicolon();
  16188. return this.finishNode(node, "ThrowStatement")
  16189. };
  16190. // Reused empty array added for node fields that are always empty.
  16191. var empty$1 = [];
  16192. pp$8.parseTryStatement = function(node) {
  16193. this.next();
  16194. node.block = this.parseBlock();
  16195. node.handler = null;
  16196. if (this.type === types$1._catch) {
  16197. var clause = this.startNode();
  16198. this.next();
  16199. if (this.eat(types$1.parenL)) {
  16200. clause.param = this.parseBindingAtom();
  16201. var simple = clause.param.type === "Identifier";
  16202. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  16203. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  16204. this.expect(types$1.parenR);
  16205. } else {
  16206. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  16207. clause.param = null;
  16208. this.enterScope(0);
  16209. }
  16210. clause.body = this.parseBlock(false);
  16211. this.exitScope();
  16212. node.handler = this.finishNode(clause, "CatchClause");
  16213. }
  16214. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  16215. if (!node.handler && !node.finalizer)
  16216. { this.raise(node.start, "Missing catch or finally clause"); }
  16217. return this.finishNode(node, "TryStatement")
  16218. };
  16219. pp$8.parseVarStatement = function(node, kind) {
  16220. this.next();
  16221. this.parseVar(node, false, kind);
  16222. this.semicolon();
  16223. return this.finishNode(node, "VariableDeclaration")
  16224. };
  16225. pp$8.parseWhileStatement = function(node) {
  16226. this.next();
  16227. node.test = this.parseParenExpression();
  16228. this.labels.push(loopLabel);
  16229. node.body = this.parseStatement("while");
  16230. this.labels.pop();
  16231. return this.finishNode(node, "WhileStatement")
  16232. };
  16233. pp$8.parseWithStatement = function(node) {
  16234. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  16235. this.next();
  16236. node.object = this.parseParenExpression();
  16237. node.body = this.parseStatement("with");
  16238. return this.finishNode(node, "WithStatement")
  16239. };
  16240. pp$8.parseEmptyStatement = function(node) {
  16241. this.next();
  16242. return this.finishNode(node, "EmptyStatement")
  16243. };
  16244. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  16245. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  16246. {
  16247. var label = list[i$1];
  16248. if (label.name === maybeName)
  16249. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  16250. } }
  16251. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  16252. for (var i = this.labels.length - 1; i >= 0; i--) {
  16253. var label$1 = this.labels[i];
  16254. if (label$1.statementStart === node.start) {
  16255. // Update information about previous labels on this node
  16256. label$1.statementStart = this.start;
  16257. label$1.kind = kind;
  16258. } else { break }
  16259. }
  16260. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  16261. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  16262. this.labels.pop();
  16263. node.label = expr;
  16264. return this.finishNode(node, "LabeledStatement")
  16265. };
  16266. pp$8.parseExpressionStatement = function(node, expr) {
  16267. node.expression = expr;
  16268. this.semicolon();
  16269. return this.finishNode(node, "ExpressionStatement")
  16270. };
  16271. // Parse a semicolon-enclosed block of statements, handling `"use
  16272. // strict"` declarations when `allowStrict` is true (used for
  16273. // function bodies).
  16274. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  16275. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  16276. if ( node === void 0 ) node = this.startNode();
  16277. node.body = [];
  16278. this.expect(types$1.braceL);
  16279. if (createNewLexicalScope) { this.enterScope(0); }
  16280. while (this.type !== types$1.braceR) {
  16281. var stmt = this.parseStatement(null);
  16282. node.body.push(stmt);
  16283. }
  16284. if (exitStrict) { this.strict = false; }
  16285. this.next();
  16286. if (createNewLexicalScope) { this.exitScope(); }
  16287. return this.finishNode(node, "BlockStatement")
  16288. };
  16289. // Parse a regular `for` loop. The disambiguation code in
  16290. // `parseStatement` will already have parsed the init statement or
  16291. // expression.
  16292. pp$8.parseFor = function(node, init) {
  16293. node.init = init;
  16294. this.expect(types$1.semi);
  16295. node.test = this.type === types$1.semi ? null : this.parseExpression();
  16296. this.expect(types$1.semi);
  16297. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  16298. this.expect(types$1.parenR);
  16299. node.body = this.parseStatement("for");
  16300. this.exitScope();
  16301. this.labels.pop();
  16302. return this.finishNode(node, "ForStatement")
  16303. };
  16304. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  16305. // same from parser's perspective.
  16306. pp$8.parseForIn = function(node, init) {
  16307. var isForIn = this.type === types$1._in;
  16308. this.next();
  16309. if (
  16310. init.type === "VariableDeclaration" &&
  16311. init.declarations[0].init != null &&
  16312. (
  16313. !isForIn ||
  16314. this.options.ecmaVersion < 8 ||
  16315. this.strict ||
  16316. init.kind !== "var" ||
  16317. init.declarations[0].id.type !== "Identifier"
  16318. )
  16319. ) {
  16320. this.raise(
  16321. init.start,
  16322. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  16323. );
  16324. }
  16325. node.left = init;
  16326. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  16327. this.expect(types$1.parenR);
  16328. node.body = this.parseStatement("for");
  16329. this.exitScope();
  16330. this.labels.pop();
  16331. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  16332. };
  16333. // Parse a list of variable declarations.
  16334. pp$8.parseVar = function(node, isFor, kind) {
  16335. node.declarations = [];
  16336. node.kind = kind;
  16337. for (;;) {
  16338. var decl = this.startNode();
  16339. this.parseVarId(decl, kind);
  16340. if (this.eat(types$1.eq)) {
  16341. decl.init = this.parseMaybeAssign(isFor);
  16342. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  16343. this.unexpected();
  16344. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  16345. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  16346. } else {
  16347. decl.init = null;
  16348. }
  16349. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  16350. if (!this.eat(types$1.comma)) { break }
  16351. }
  16352. return node
  16353. };
  16354. pp$8.parseVarId = function(decl, kind) {
  16355. decl.id = this.parseBindingAtom();
  16356. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  16357. };
  16358. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  16359. // Parse a function declaration or literal (depending on the
  16360. // `statement & FUNC_STATEMENT`).
  16361. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  16362. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  16363. this.initFunction(node);
  16364. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  16365. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  16366. { this.unexpected(); }
  16367. node.generator = this.eat(types$1.star);
  16368. }
  16369. if (this.options.ecmaVersion >= 8)
  16370. { node.async = !!isAsync; }
  16371. if (statement & FUNC_STATEMENT) {
  16372. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  16373. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  16374. // If it is a regular function declaration in sloppy mode, then it is
  16375. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  16376. // mode depends on properties of the current scope (see
  16377. // treatFunctionsAsVar).
  16378. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  16379. }
  16380. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  16381. this.yieldPos = 0;
  16382. this.awaitPos = 0;
  16383. this.awaitIdentPos = 0;
  16384. this.enterScope(functionFlags(node.async, node.generator));
  16385. if (!(statement & FUNC_STATEMENT))
  16386. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  16387. this.parseFunctionParams(node);
  16388. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  16389. this.yieldPos = oldYieldPos;
  16390. this.awaitPos = oldAwaitPos;
  16391. this.awaitIdentPos = oldAwaitIdentPos;
  16392. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  16393. };
  16394. pp$8.parseFunctionParams = function(node) {
  16395. this.expect(types$1.parenL);
  16396. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  16397. this.checkYieldAwaitInDefaultParams();
  16398. };
  16399. // Parse a class declaration or literal (depending on the
  16400. // `isStatement` parameter).
  16401. pp$8.parseClass = function(node, isStatement) {
  16402. this.next();
  16403. // ecma-262 14.6 Class Definitions
  16404. // A class definition is always strict mode code.
  16405. var oldStrict = this.strict;
  16406. this.strict = true;
  16407. this.parseClassId(node, isStatement);
  16408. this.parseClassSuper(node);
  16409. var privateNameMap = this.enterClassBody();
  16410. var classBody = this.startNode();
  16411. var hadConstructor = false;
  16412. classBody.body = [];
  16413. this.expect(types$1.braceL);
  16414. while (this.type !== types$1.braceR) {
  16415. var element = this.parseClassElement(node.superClass !== null);
  16416. if (element) {
  16417. classBody.body.push(element);
  16418. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  16419. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  16420. hadConstructor = true;
  16421. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  16422. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  16423. }
  16424. }
  16425. }
  16426. this.strict = oldStrict;
  16427. this.next();
  16428. node.body = this.finishNode(classBody, "ClassBody");
  16429. this.exitClassBody();
  16430. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  16431. };
  16432. pp$8.parseClassElement = function(constructorAllowsSuper) {
  16433. if (this.eat(types$1.semi)) { return null }
  16434. var ecmaVersion = this.options.ecmaVersion;
  16435. var node = this.startNode();
  16436. var keyName = "";
  16437. var isGenerator = false;
  16438. var isAsync = false;
  16439. var kind = "method";
  16440. var isStatic = false;
  16441. if (this.eatContextual("static")) {
  16442. // Parse static init block
  16443. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  16444. this.parseClassStaticBlock(node);
  16445. return node
  16446. }
  16447. if (this.isClassElementNameStart() || this.type === types$1.star) {
  16448. isStatic = true;
  16449. } else {
  16450. keyName = "static";
  16451. }
  16452. }
  16453. node.static = isStatic;
  16454. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  16455. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  16456. isAsync = true;
  16457. } else {
  16458. keyName = "async";
  16459. }
  16460. }
  16461. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  16462. isGenerator = true;
  16463. }
  16464. if (!keyName && !isAsync && !isGenerator) {
  16465. var lastValue = this.value;
  16466. if (this.eatContextual("get") || this.eatContextual("set")) {
  16467. if (this.isClassElementNameStart()) {
  16468. kind = lastValue;
  16469. } else {
  16470. keyName = lastValue;
  16471. }
  16472. }
  16473. }
  16474. // Parse element name
  16475. if (keyName) {
  16476. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  16477. // The last token is any of those. Make it the element name.
  16478. node.computed = false;
  16479. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  16480. node.key.name = keyName;
  16481. this.finishNode(node.key, "Identifier");
  16482. } else {
  16483. this.parseClassElementName(node);
  16484. }
  16485. // Parse element value
  16486. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  16487. var isConstructor = !node.static && checkKeyName(node, "constructor");
  16488. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  16489. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  16490. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  16491. node.kind = isConstructor ? "constructor" : kind;
  16492. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  16493. } else {
  16494. this.parseClassField(node);
  16495. }
  16496. return node
  16497. };
  16498. pp$8.isClassElementNameStart = function() {
  16499. return (
  16500. this.type === types$1.name ||
  16501. this.type === types$1.privateId ||
  16502. this.type === types$1.num ||
  16503. this.type === types$1.string ||
  16504. this.type === types$1.bracketL ||
  16505. this.type.keyword
  16506. )
  16507. };
  16508. pp$8.parseClassElementName = function(element) {
  16509. if (this.type === types$1.privateId) {
  16510. if (this.value === "constructor") {
  16511. this.raise(this.start, "Classes can't have an element named '#constructor'");
  16512. }
  16513. element.computed = false;
  16514. element.key = this.parsePrivateIdent();
  16515. } else {
  16516. this.parsePropertyName(element);
  16517. }
  16518. };
  16519. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  16520. // Check key and flags
  16521. var key = method.key;
  16522. if (method.kind === "constructor") {
  16523. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  16524. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  16525. } else if (method.static && checkKeyName(method, "prototype")) {
  16526. this.raise(key.start, "Classes may not have a static property named prototype");
  16527. }
  16528. // Parse value
  16529. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  16530. // Check value
  16531. if (method.kind === "get" && value.params.length !== 0)
  16532. { this.raiseRecoverable(value.start, "getter should have no params"); }
  16533. if (method.kind === "set" && value.params.length !== 1)
  16534. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  16535. if (method.kind === "set" && value.params[0].type === "RestElement")
  16536. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  16537. return this.finishNode(method, "MethodDefinition")
  16538. };
  16539. pp$8.parseClassField = function(field) {
  16540. if (checkKeyName(field, "constructor")) {
  16541. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  16542. } else if (field.static && checkKeyName(field, "prototype")) {
  16543. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  16544. }
  16545. if (this.eat(types$1.eq)) {
  16546. // To raise SyntaxError if 'arguments' exists in the initializer.
  16547. var scope = this.currentThisScope();
  16548. var inClassFieldInit = scope.inClassFieldInit;
  16549. scope.inClassFieldInit = true;
  16550. field.value = this.parseMaybeAssign();
  16551. scope.inClassFieldInit = inClassFieldInit;
  16552. } else {
  16553. field.value = null;
  16554. }
  16555. this.semicolon();
  16556. return this.finishNode(field, "PropertyDefinition")
  16557. };
  16558. pp$8.parseClassStaticBlock = function(node) {
  16559. node.body = [];
  16560. var oldLabels = this.labels;
  16561. this.labels = [];
  16562. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  16563. while (this.type !== types$1.braceR) {
  16564. var stmt = this.parseStatement(null);
  16565. node.body.push(stmt);
  16566. }
  16567. this.next();
  16568. this.exitScope();
  16569. this.labels = oldLabels;
  16570. return this.finishNode(node, "StaticBlock")
  16571. };
  16572. pp$8.parseClassId = function(node, isStatement) {
  16573. if (this.type === types$1.name) {
  16574. node.id = this.parseIdent();
  16575. if (isStatement)
  16576. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  16577. } else {
  16578. if (isStatement === true)
  16579. { this.unexpected(); }
  16580. node.id = null;
  16581. }
  16582. };
  16583. pp$8.parseClassSuper = function(node) {
  16584. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  16585. };
  16586. pp$8.enterClassBody = function() {
  16587. var element = {declared: Object.create(null), used: []};
  16588. this.privateNameStack.push(element);
  16589. return element.declared
  16590. };
  16591. pp$8.exitClassBody = function() {
  16592. var ref = this.privateNameStack.pop();
  16593. var declared = ref.declared;
  16594. var used = ref.used;
  16595. var len = this.privateNameStack.length;
  16596. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  16597. for (var i = 0; i < used.length; ++i) {
  16598. var id = used[i];
  16599. if (!hasOwn(declared, id.name)) {
  16600. if (parent) {
  16601. parent.used.push(id);
  16602. } else {
  16603. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  16604. }
  16605. }
  16606. }
  16607. };
  16608. function isPrivateNameConflicted(privateNameMap, element) {
  16609. var name = element.key.name;
  16610. var curr = privateNameMap[name];
  16611. var next = "true";
  16612. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  16613. next = (element.static ? "s" : "i") + element.kind;
  16614. }
  16615. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  16616. if (
  16617. curr === "iget" && next === "iset" ||
  16618. curr === "iset" && next === "iget" ||
  16619. curr === "sget" && next === "sset" ||
  16620. curr === "sset" && next === "sget"
  16621. ) {
  16622. privateNameMap[name] = "true";
  16623. return false
  16624. } else if (!curr) {
  16625. privateNameMap[name] = next;
  16626. return false
  16627. } else {
  16628. return true
  16629. }
  16630. }
  16631. function checkKeyName(node, name) {
  16632. var computed = node.computed;
  16633. var key = node.key;
  16634. return !computed && (
  16635. key.type === "Identifier" && key.name === name ||
  16636. key.type === "Literal" && key.value === name
  16637. )
  16638. }
  16639. // Parses module export declaration.
  16640. pp$8.parseExport = function(node, exports) {
  16641. this.next();
  16642. // export * from '...'
  16643. if (this.eat(types$1.star)) {
  16644. if (this.options.ecmaVersion >= 11) {
  16645. if (this.eatContextual("as")) {
  16646. node.exported = this.parseModuleExportName();
  16647. this.checkExport(exports, node.exported, this.lastTokStart);
  16648. } else {
  16649. node.exported = null;
  16650. }
  16651. }
  16652. this.expectContextual("from");
  16653. if (this.type !== types$1.string) { this.unexpected(); }
  16654. node.source = this.parseExprAtom();
  16655. this.semicolon();
  16656. return this.finishNode(node, "ExportAllDeclaration")
  16657. }
  16658. if (this.eat(types$1._default)) { // export default ...
  16659. this.checkExport(exports, "default", this.lastTokStart);
  16660. var isAsync;
  16661. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  16662. var fNode = this.startNode();
  16663. this.next();
  16664. if (isAsync) { this.next(); }
  16665. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  16666. } else if (this.type === types$1._class) {
  16667. var cNode = this.startNode();
  16668. node.declaration = this.parseClass(cNode, "nullableID");
  16669. } else {
  16670. node.declaration = this.parseMaybeAssign();
  16671. this.semicolon();
  16672. }
  16673. return this.finishNode(node, "ExportDefaultDeclaration")
  16674. }
  16675. // export var|const|let|function|class ...
  16676. if (this.shouldParseExportStatement()) {
  16677. node.declaration = this.parseStatement(null);
  16678. if (node.declaration.type === "VariableDeclaration")
  16679. { this.checkVariableExport(exports, node.declaration.declarations); }
  16680. else
  16681. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  16682. node.specifiers = [];
  16683. node.source = null;
  16684. } else { // export { x, y as z } [from '...']
  16685. node.declaration = null;
  16686. node.specifiers = this.parseExportSpecifiers(exports);
  16687. if (this.eatContextual("from")) {
  16688. if (this.type !== types$1.string) { this.unexpected(); }
  16689. node.source = this.parseExprAtom();
  16690. } else {
  16691. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  16692. // check for keywords used as local names
  16693. var spec = list[i];
  16694. this.checkUnreserved(spec.local);
  16695. // check if export is defined
  16696. this.checkLocalExport(spec.local);
  16697. if (spec.local.type === "Literal") {
  16698. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  16699. }
  16700. }
  16701. node.source = null;
  16702. }
  16703. this.semicolon();
  16704. }
  16705. return this.finishNode(node, "ExportNamedDeclaration")
  16706. };
  16707. pp$8.checkExport = function(exports, name, pos) {
  16708. if (!exports) { return }
  16709. if (typeof name !== "string")
  16710. { name = name.type === "Identifier" ? name.name : name.value; }
  16711. if (hasOwn(exports, name))
  16712. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  16713. exports[name] = true;
  16714. };
  16715. pp$8.checkPatternExport = function(exports, pat) {
  16716. var type = pat.type;
  16717. if (type === "Identifier")
  16718. { this.checkExport(exports, pat, pat.start); }
  16719. else if (type === "ObjectPattern")
  16720. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  16721. {
  16722. var prop = list[i];
  16723. this.checkPatternExport(exports, prop);
  16724. } }
  16725. else if (type === "ArrayPattern")
  16726. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  16727. var elt = list$1[i$1];
  16728. if (elt) { this.checkPatternExport(exports, elt); }
  16729. } }
  16730. else if (type === "Property")
  16731. { this.checkPatternExport(exports, pat.value); }
  16732. else if (type === "AssignmentPattern")
  16733. { this.checkPatternExport(exports, pat.left); }
  16734. else if (type === "RestElement")
  16735. { this.checkPatternExport(exports, pat.argument); }
  16736. else if (type === "ParenthesizedExpression")
  16737. { this.checkPatternExport(exports, pat.expression); }
  16738. };
  16739. pp$8.checkVariableExport = function(exports, decls) {
  16740. if (!exports) { return }
  16741. for (var i = 0, list = decls; i < list.length; i += 1)
  16742. {
  16743. var decl = list[i];
  16744. this.checkPatternExport(exports, decl.id);
  16745. }
  16746. };
  16747. pp$8.shouldParseExportStatement = function() {
  16748. return this.type.keyword === "var" ||
  16749. this.type.keyword === "const" ||
  16750. this.type.keyword === "class" ||
  16751. this.type.keyword === "function" ||
  16752. this.isLet() ||
  16753. this.isAsyncFunction()
  16754. };
  16755. // Parses a comma-separated list of module exports.
  16756. pp$8.parseExportSpecifiers = function(exports) {
  16757. var nodes = [], first = true;
  16758. // export { x, y as z } [from '...']
  16759. this.expect(types$1.braceL);
  16760. while (!this.eat(types$1.braceR)) {
  16761. if (!first) {
  16762. this.expect(types$1.comma);
  16763. if (this.afterTrailingComma(types$1.braceR)) { break }
  16764. } else { first = false; }
  16765. var node = this.startNode();
  16766. node.local = this.parseModuleExportName();
  16767. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  16768. this.checkExport(
  16769. exports,
  16770. node.exported,
  16771. node.exported.start
  16772. );
  16773. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16774. }
  16775. return nodes
  16776. };
  16777. // Parses import declaration.
  16778. pp$8.parseImport = function(node) {
  16779. this.next();
  16780. // import '...'
  16781. if (this.type === types$1.string) {
  16782. node.specifiers = empty$1;
  16783. node.source = this.parseExprAtom();
  16784. } else {
  16785. node.specifiers = this.parseImportSpecifiers();
  16786. this.expectContextual("from");
  16787. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  16788. }
  16789. this.semicolon();
  16790. return this.finishNode(node, "ImportDeclaration")
  16791. };
  16792. // Parses a comma-separated list of module imports.
  16793. pp$8.parseImportSpecifiers = function() {
  16794. var nodes = [], first = true;
  16795. if (this.type === types$1.name) {
  16796. // import defaultObj, { x, y as z } from '...'
  16797. var node = this.startNode();
  16798. node.local = this.parseIdent();
  16799. this.checkLValSimple(node.local, BIND_LEXICAL);
  16800. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  16801. if (!this.eat(types$1.comma)) { return nodes }
  16802. }
  16803. if (this.type === types$1.star) {
  16804. var node$1 = this.startNode();
  16805. this.next();
  16806. this.expectContextual("as");
  16807. node$1.local = this.parseIdent();
  16808. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  16809. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  16810. return nodes
  16811. }
  16812. this.expect(types$1.braceL);
  16813. while (!this.eat(types$1.braceR)) {
  16814. if (!first) {
  16815. this.expect(types$1.comma);
  16816. if (this.afterTrailingComma(types$1.braceR)) { break }
  16817. } else { first = false; }
  16818. var node$2 = this.startNode();
  16819. node$2.imported = this.parseModuleExportName();
  16820. if (this.eatContextual("as")) {
  16821. node$2.local = this.parseIdent();
  16822. } else {
  16823. this.checkUnreserved(node$2.imported);
  16824. node$2.local = node$2.imported;
  16825. }
  16826. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  16827. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  16828. }
  16829. return nodes
  16830. };
  16831. pp$8.parseModuleExportName = function() {
  16832. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  16833. var stringLiteral = this.parseLiteral(this.value);
  16834. if (loneSurrogate.test(stringLiteral.value)) {
  16835. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  16836. }
  16837. return stringLiteral
  16838. }
  16839. return this.parseIdent(true)
  16840. };
  16841. // Set `ExpressionStatement#directive` property for directive prologues.
  16842. pp$8.adaptDirectivePrologue = function(statements) {
  16843. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  16844. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  16845. }
  16846. };
  16847. pp$8.isDirectiveCandidate = function(statement) {
  16848. return (
  16849. statement.type === "ExpressionStatement" &&
  16850. statement.expression.type === "Literal" &&
  16851. typeof statement.expression.value === "string" &&
  16852. // Reject parenthesized strings.
  16853. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  16854. )
  16855. };
  16856. var pp$7 = Parser.prototype;
  16857. // Convert existing expression atom to assignable pattern
  16858. // if possible.
  16859. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  16860. if (this.options.ecmaVersion >= 6 && node) {
  16861. switch (node.type) {
  16862. case "Identifier":
  16863. if (this.inAsync && node.name === "await")
  16864. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  16865. break
  16866. case "ObjectPattern":
  16867. case "ArrayPattern":
  16868. case "AssignmentPattern":
  16869. case "RestElement":
  16870. break
  16871. case "ObjectExpression":
  16872. node.type = "ObjectPattern";
  16873. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16874. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  16875. var prop = list[i];
  16876. this.toAssignable(prop, isBinding);
  16877. // Early error:
  16878. // AssignmentRestProperty[Yield, Await] :
  16879. // `...` DestructuringAssignmentTarget[Yield, Await]
  16880. //
  16881. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  16882. if (
  16883. prop.type === "RestElement" &&
  16884. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  16885. ) {
  16886. this.raise(prop.argument.start, "Unexpected token");
  16887. }
  16888. }
  16889. break
  16890. case "Property":
  16891. // AssignmentProperty has type === "Property"
  16892. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  16893. this.toAssignable(node.value, isBinding);
  16894. break
  16895. case "ArrayExpression":
  16896. node.type = "ArrayPattern";
  16897. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16898. this.toAssignableList(node.elements, isBinding);
  16899. break
  16900. case "SpreadElement":
  16901. node.type = "RestElement";
  16902. this.toAssignable(node.argument, isBinding);
  16903. if (node.argument.type === "AssignmentPattern")
  16904. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  16905. break
  16906. case "AssignmentExpression":
  16907. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  16908. node.type = "AssignmentPattern";
  16909. delete node.operator;
  16910. this.toAssignable(node.left, isBinding);
  16911. break
  16912. case "ParenthesizedExpression":
  16913. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  16914. break
  16915. case "ChainExpression":
  16916. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  16917. break
  16918. case "MemberExpression":
  16919. if (!isBinding) { break }
  16920. default:
  16921. this.raise(node.start, "Assigning to rvalue");
  16922. }
  16923. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16924. return node
  16925. };
  16926. // Convert list of expression atoms to binding list.
  16927. pp$7.toAssignableList = function(exprList, isBinding) {
  16928. var end = exprList.length;
  16929. for (var i = 0; i < end; i++) {
  16930. var elt = exprList[i];
  16931. if (elt) { this.toAssignable(elt, isBinding); }
  16932. }
  16933. if (end) {
  16934. var last = exprList[end - 1];
  16935. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  16936. { this.unexpected(last.argument.start); }
  16937. }
  16938. return exprList
  16939. };
  16940. // Parses spread element.
  16941. pp$7.parseSpread = function(refDestructuringErrors) {
  16942. var node = this.startNode();
  16943. this.next();
  16944. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  16945. return this.finishNode(node, "SpreadElement")
  16946. };
  16947. pp$7.parseRestBinding = function() {
  16948. var node = this.startNode();
  16949. this.next();
  16950. // RestElement inside of a function parameter must be an identifier
  16951. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  16952. { this.unexpected(); }
  16953. node.argument = this.parseBindingAtom();
  16954. return this.finishNode(node, "RestElement")
  16955. };
  16956. // Parses lvalue (assignable) atom.
  16957. pp$7.parseBindingAtom = function() {
  16958. if (this.options.ecmaVersion >= 6) {
  16959. switch (this.type) {
  16960. case types$1.bracketL:
  16961. var node = this.startNode();
  16962. this.next();
  16963. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  16964. return this.finishNode(node, "ArrayPattern")
  16965. case types$1.braceL:
  16966. return this.parseObj(true)
  16967. }
  16968. }
  16969. return this.parseIdent()
  16970. };
  16971. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  16972. var elts = [], first = true;
  16973. while (!this.eat(close)) {
  16974. if (first) { first = false; }
  16975. else { this.expect(types$1.comma); }
  16976. if (allowEmpty && this.type === types$1.comma) {
  16977. elts.push(null);
  16978. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  16979. break
  16980. } else if (this.type === types$1.ellipsis) {
  16981. var rest = this.parseRestBinding();
  16982. this.parseBindingListItem(rest);
  16983. elts.push(rest);
  16984. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  16985. this.expect(close);
  16986. break
  16987. } else {
  16988. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  16989. this.parseBindingListItem(elem);
  16990. elts.push(elem);
  16991. }
  16992. }
  16993. return elts
  16994. };
  16995. pp$7.parseBindingListItem = function(param) {
  16996. return param
  16997. };
  16998. // Parses assignment pattern around given atom if possible.
  16999. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  17000. left = left || this.parseBindingAtom();
  17001. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  17002. var node = this.startNodeAt(startPos, startLoc);
  17003. node.left = left;
  17004. node.right = this.parseMaybeAssign();
  17005. return this.finishNode(node, "AssignmentPattern")
  17006. };
  17007. // The following three functions all verify that a node is an lvalue —
  17008. // something that can be bound, or assigned to. In order to do so, they perform
  17009. // a variety of checks:
  17010. //
  17011. // - Check that none of the bound/assigned-to identifiers are reserved words.
  17012. // - Record name declarations for bindings in the appropriate scope.
  17013. // - Check duplicate argument names, if checkClashes is set.
  17014. //
  17015. // If a complex binding pattern is encountered (e.g., object and array
  17016. // destructuring), the entire pattern is recursively checked.
  17017. //
  17018. // There are three versions of checkLVal*() appropriate for different
  17019. // circumstances:
  17020. //
  17021. // - checkLValSimple() shall be used if the syntactic construct supports
  17022. // nothing other than identifiers and member expressions. Parenthesized
  17023. // expressions are also correctly handled. This is generally appropriate for
  17024. // constructs for which the spec says
  17025. //
  17026. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  17027. // > simple.
  17028. //
  17029. // It is also appropriate for checking if an identifier is valid and not
  17030. // defined elsewhere, like import declarations or function/class identifiers.
  17031. //
  17032. // Examples where this is used include:
  17033. // a += …;
  17034. // import a from '…';
  17035. // where a is the node to be checked.
  17036. //
  17037. // - checkLValPattern() shall be used if the syntactic construct supports
  17038. // anything checkLValSimple() supports, as well as object and array
  17039. // destructuring patterns. This is generally appropriate for constructs for
  17040. // which the spec says
  17041. //
  17042. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  17043. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  17044. // > simple.
  17045. //
  17046. // Examples where this is used include:
  17047. // (a = …);
  17048. // const a = …;
  17049. // try { … } catch (a) { … }
  17050. // where a is the node to be checked.
  17051. //
  17052. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  17053. // anything checkLValPattern() supports, as well as default assignment
  17054. // patterns, rest elements, and other constructs that may appear within an
  17055. // object or array destructuring pattern.
  17056. //
  17057. // As a special case, function parameters also use checkLValInnerPattern(),
  17058. // as they also support defaults and rest constructs.
  17059. //
  17060. // These functions deliberately support both assignment and binding constructs,
  17061. // as the logic for both is exceedingly similar. If the node is the target of
  17062. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  17063. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  17064. // BIND_LEXICAL.
  17065. //
  17066. // If the function is called with a non-BIND_NONE bindingType, then
  17067. // additionally a checkClashes object may be specified to allow checking for
  17068. // duplicate argument names. checkClashes is ignored if the provided construct
  17069. // is an assignment (i.e., bindingType is BIND_NONE).
  17070. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  17071. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17072. var isBind = bindingType !== BIND_NONE;
  17073. switch (expr.type) {
  17074. case "Identifier":
  17075. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  17076. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  17077. if (isBind) {
  17078. if (bindingType === BIND_LEXICAL && expr.name === "let")
  17079. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  17080. if (checkClashes) {
  17081. if (hasOwn(checkClashes, expr.name))
  17082. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  17083. checkClashes[expr.name] = true;
  17084. }
  17085. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  17086. }
  17087. break
  17088. case "ChainExpression":
  17089. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  17090. break
  17091. case "MemberExpression":
  17092. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  17093. break
  17094. case "ParenthesizedExpression":
  17095. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  17096. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  17097. default:
  17098. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  17099. }
  17100. };
  17101. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  17102. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17103. switch (expr.type) {
  17104. case "ObjectPattern":
  17105. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  17106. var prop = list[i];
  17107. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  17108. }
  17109. break
  17110. case "ArrayPattern":
  17111. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  17112. var elem = list$1[i$1];
  17113. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  17114. }
  17115. break
  17116. default:
  17117. this.checkLValSimple(expr, bindingType, checkClashes);
  17118. }
  17119. };
  17120. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  17121. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17122. switch (expr.type) {
  17123. case "Property":
  17124. // AssignmentProperty has type === "Property"
  17125. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  17126. break
  17127. case "AssignmentPattern":
  17128. this.checkLValPattern(expr.left, bindingType, checkClashes);
  17129. break
  17130. case "RestElement":
  17131. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  17132. break
  17133. default:
  17134. this.checkLValPattern(expr, bindingType, checkClashes);
  17135. }
  17136. };
  17137. // The algorithm used to determine whether a regexp can appear at a
  17138. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  17139. this.token = token;
  17140. this.isExpr = !!isExpr;
  17141. this.preserveSpace = !!preserveSpace;
  17142. this.override = override;
  17143. this.generator = !!generator;
  17144. };
  17145. var types = {
  17146. b_stat: new TokContext("{", false),
  17147. b_expr: new TokContext("{", true),
  17148. b_tmpl: new TokContext("${", false),
  17149. p_stat: new TokContext("(", false),
  17150. p_expr: new TokContext("(", true),
  17151. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  17152. f_stat: new TokContext("function", false),
  17153. f_expr: new TokContext("function", true),
  17154. f_expr_gen: new TokContext("function", true, false, null, true),
  17155. f_gen: new TokContext("function", false, false, null, true)
  17156. };
  17157. var pp$6 = Parser.prototype;
  17158. pp$6.initialContext = function() {
  17159. return [types.b_stat]
  17160. };
  17161. pp$6.curContext = function() {
  17162. return this.context[this.context.length - 1]
  17163. };
  17164. pp$6.braceIsBlock = function(prevType) {
  17165. var parent = this.curContext();
  17166. if (parent === types.f_expr || parent === types.f_stat)
  17167. { return true }
  17168. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  17169. { return !parent.isExpr }
  17170. // The check for `tt.name && exprAllowed` detects whether we are
  17171. // after a `yield` or `of` construct. See the `updateContext` for
  17172. // `tt.name`.
  17173. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  17174. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  17175. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  17176. { return true }
  17177. if (prevType === types$1.braceL)
  17178. { return parent === types.b_stat }
  17179. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  17180. { return false }
  17181. return !this.exprAllowed
  17182. };
  17183. pp$6.inGeneratorContext = function() {
  17184. for (var i = this.context.length - 1; i >= 1; i--) {
  17185. var context = this.context[i];
  17186. if (context.token === "function")
  17187. { return context.generator }
  17188. }
  17189. return false
  17190. };
  17191. pp$6.updateContext = function(prevType) {
  17192. var update, type = this.type;
  17193. if (type.keyword && prevType === types$1.dot)
  17194. { this.exprAllowed = false; }
  17195. else if (update = type.updateContext)
  17196. { update.call(this, prevType); }
  17197. else
  17198. { this.exprAllowed = type.beforeExpr; }
  17199. };
  17200. // Used to handle egde case when token context could not be inferred correctly in tokenize phase
  17201. pp$6.overrideContext = function(tokenCtx) {
  17202. if (this.curContext() !== tokenCtx) {
  17203. this.context[this.context.length - 1] = tokenCtx;
  17204. }
  17205. };
  17206. // Token-specific context update code
  17207. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  17208. if (this.context.length === 1) {
  17209. this.exprAllowed = true;
  17210. return
  17211. }
  17212. var out = this.context.pop();
  17213. if (out === types.b_stat && this.curContext().token === "function") {
  17214. out = this.context.pop();
  17215. }
  17216. this.exprAllowed = !out.isExpr;
  17217. };
  17218. types$1.braceL.updateContext = function(prevType) {
  17219. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  17220. this.exprAllowed = true;
  17221. };
  17222. types$1.dollarBraceL.updateContext = function() {
  17223. this.context.push(types.b_tmpl);
  17224. this.exprAllowed = true;
  17225. };
  17226. types$1.parenL.updateContext = function(prevType) {
  17227. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  17228. this.context.push(statementParens ? types.p_stat : types.p_expr);
  17229. this.exprAllowed = true;
  17230. };
  17231. types$1.incDec.updateContext = function() {
  17232. // tokExprAllowed stays unchanged
  17233. };
  17234. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  17235. if (prevType.beforeExpr && prevType !== types$1._else &&
  17236. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  17237. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  17238. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  17239. { this.context.push(types.f_expr); }
  17240. else
  17241. { this.context.push(types.f_stat); }
  17242. this.exprAllowed = false;
  17243. };
  17244. types$1.backQuote.updateContext = function() {
  17245. if (this.curContext() === types.q_tmpl)
  17246. { this.context.pop(); }
  17247. else
  17248. { this.context.push(types.q_tmpl); }
  17249. this.exprAllowed = false;
  17250. };
  17251. types$1.star.updateContext = function(prevType) {
  17252. if (prevType === types$1._function) {
  17253. var index = this.context.length - 1;
  17254. if (this.context[index] === types.f_expr)
  17255. { this.context[index] = types.f_expr_gen; }
  17256. else
  17257. { this.context[index] = types.f_gen; }
  17258. }
  17259. this.exprAllowed = true;
  17260. };
  17261. types$1.name.updateContext = function(prevType) {
  17262. var allowed = false;
  17263. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  17264. if (this.value === "of" && !this.exprAllowed ||
  17265. this.value === "yield" && this.inGeneratorContext())
  17266. { allowed = true; }
  17267. }
  17268. this.exprAllowed = allowed;
  17269. };
  17270. // A recursive descent parser operates by defining functions for all
  17271. var pp$5 = Parser.prototype;
  17272. // Check if property name clashes with already added.
  17273. // Object/class getters and setters are not allowed to clash —
  17274. // either with each other or with an init property — and in
  17275. // strict mode, init properties are also not allowed to be repeated.
  17276. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  17277. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  17278. { return }
  17279. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  17280. { return }
  17281. var key = prop.key;
  17282. var name;
  17283. switch (key.type) {
  17284. case "Identifier": name = key.name; break
  17285. case "Literal": name = String(key.value); break
  17286. default: return
  17287. }
  17288. var kind = prop.kind;
  17289. if (this.options.ecmaVersion >= 6) {
  17290. if (name === "__proto__" && kind === "init") {
  17291. if (propHash.proto) {
  17292. if (refDestructuringErrors) {
  17293. if (refDestructuringErrors.doubleProto < 0) {
  17294. refDestructuringErrors.doubleProto = key.start;
  17295. }
  17296. } else {
  17297. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  17298. }
  17299. }
  17300. propHash.proto = true;
  17301. }
  17302. return
  17303. }
  17304. name = "$" + name;
  17305. var other = propHash[name];
  17306. if (other) {
  17307. var redefinition;
  17308. if (kind === "init") {
  17309. redefinition = this.strict && other.init || other.get || other.set;
  17310. } else {
  17311. redefinition = other.init || other[kind];
  17312. }
  17313. if (redefinition)
  17314. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  17315. } else {
  17316. other = propHash[name] = {
  17317. init: false,
  17318. get: false,
  17319. set: false
  17320. };
  17321. }
  17322. other[kind] = true;
  17323. };
  17324. // ### Expression parsing
  17325. // These nest, from the most general expression type at the top to
  17326. // 'atomic', nondivisible expression types at the bottom. Most of
  17327. // the functions will simply let the function(s) below them parse,
  17328. // and, *if* the syntactic construct they handle is present, wrap
  17329. // the AST node that the inner parser gave them in another node.
  17330. // Parse a full expression. The optional arguments are used to
  17331. // forbid the `in` operator (in for loops initalization expressions)
  17332. // and provide reference for storing '=' operator inside shorthand
  17333. // property assignment in contexts where both object expression
  17334. // and object pattern might appear (so it's possible to raise
  17335. // delayed syntax error at correct position).
  17336. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  17337. var startPos = this.start, startLoc = this.startLoc;
  17338. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  17339. if (this.type === types$1.comma) {
  17340. var node = this.startNodeAt(startPos, startLoc);
  17341. node.expressions = [expr];
  17342. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  17343. return this.finishNode(node, "SequenceExpression")
  17344. }
  17345. return expr
  17346. };
  17347. // Parse an assignment expression. This includes applications of
  17348. // operators like `+=`.
  17349. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  17350. if (this.isContextual("yield")) {
  17351. if (this.inGenerator) { return this.parseYield(forInit) }
  17352. // The tokenizer will assume an expression is allowed after
  17353. // `yield`, but this isn't that kind of yield
  17354. else { this.exprAllowed = false; }
  17355. }
  17356. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  17357. if (refDestructuringErrors) {
  17358. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  17359. oldTrailingComma = refDestructuringErrors.trailingComma;
  17360. oldDoubleProto = refDestructuringErrors.doubleProto;
  17361. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  17362. } else {
  17363. refDestructuringErrors = new DestructuringErrors;
  17364. ownDestructuringErrors = true;
  17365. }
  17366. var startPos = this.start, startLoc = this.startLoc;
  17367. if (this.type === types$1.parenL || this.type === types$1.name) {
  17368. this.potentialArrowAt = this.start;
  17369. this.potentialArrowInForAwait = forInit === "await";
  17370. }
  17371. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  17372. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  17373. if (this.type.isAssign) {
  17374. var node = this.startNodeAt(startPos, startLoc);
  17375. node.operator = this.value;
  17376. if (this.type === types$1.eq)
  17377. { left = this.toAssignable(left, false, refDestructuringErrors); }
  17378. if (!ownDestructuringErrors) {
  17379. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  17380. }
  17381. if (refDestructuringErrors.shorthandAssign >= left.start)
  17382. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  17383. if (this.type === types$1.eq)
  17384. { this.checkLValPattern(left); }
  17385. else
  17386. { this.checkLValSimple(left); }
  17387. node.left = left;
  17388. this.next();
  17389. node.right = this.parseMaybeAssign(forInit);
  17390. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  17391. return this.finishNode(node, "AssignmentExpression")
  17392. } else {
  17393. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  17394. }
  17395. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  17396. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  17397. return left
  17398. };
  17399. // Parse a ternary conditional (`?:`) operator.
  17400. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  17401. var startPos = this.start, startLoc = this.startLoc;
  17402. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  17403. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17404. if (this.eat(types$1.question)) {
  17405. var node = this.startNodeAt(startPos, startLoc);
  17406. node.test = expr;
  17407. node.consequent = this.parseMaybeAssign();
  17408. this.expect(types$1.colon);
  17409. node.alternate = this.parseMaybeAssign(forInit);
  17410. return this.finishNode(node, "ConditionalExpression")
  17411. }
  17412. return expr
  17413. };
  17414. // Start the precedence parser.
  17415. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  17416. var startPos = this.start, startLoc = this.startLoc;
  17417. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  17418. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17419. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  17420. };
  17421. // Parse binary operators with the operator precedence parsing
  17422. // algorithm. `left` is the left-hand side of the operator.
  17423. // `minPrec` provides context that allows the function to stop and
  17424. // defer further parser to one of its callers when it encounters an
  17425. // operator that has a lower precedence than the set it is parsing.
  17426. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  17427. var prec = this.type.binop;
  17428. if (prec != null && (!forInit || this.type !== types$1._in)) {
  17429. if (prec > minPrec) {
  17430. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  17431. var coalesce = this.type === types$1.coalesce;
  17432. if (coalesce) {
  17433. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  17434. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  17435. prec = types$1.logicalAND.binop;
  17436. }
  17437. var op = this.value;
  17438. this.next();
  17439. var startPos = this.start, startLoc = this.startLoc;
  17440. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  17441. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  17442. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  17443. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  17444. }
  17445. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  17446. }
  17447. }
  17448. return left
  17449. };
  17450. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  17451. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  17452. var node = this.startNodeAt(startPos, startLoc);
  17453. node.left = left;
  17454. node.operator = op;
  17455. node.right = right;
  17456. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  17457. };
  17458. // Parse unary operators, both prefix and postfix.
  17459. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  17460. var startPos = this.start, startLoc = this.startLoc, expr;
  17461. if (this.isContextual("await") && this.canAwait) {
  17462. expr = this.parseAwait(forInit);
  17463. sawUnary = true;
  17464. } else if (this.type.prefix) {
  17465. var node = this.startNode(), update = this.type === types$1.incDec;
  17466. node.operator = this.value;
  17467. node.prefix = true;
  17468. this.next();
  17469. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  17470. this.checkExpressionErrors(refDestructuringErrors, true);
  17471. if (update) { this.checkLValSimple(node.argument); }
  17472. else if (this.strict && node.operator === "delete" &&
  17473. node.argument.type === "Identifier")
  17474. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  17475. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  17476. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  17477. else { sawUnary = true; }
  17478. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  17479. } else if (!sawUnary && this.type === types$1.privateId) {
  17480. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  17481. expr = this.parsePrivateIdent();
  17482. // only could be private fields in 'in', such as #x in obj
  17483. if (this.type !== types$1._in) { this.unexpected(); }
  17484. } else {
  17485. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  17486. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17487. while (this.type.postfix && !this.canInsertSemicolon()) {
  17488. var node$1 = this.startNodeAt(startPos, startLoc);
  17489. node$1.operator = this.value;
  17490. node$1.prefix = false;
  17491. node$1.argument = expr;
  17492. this.checkLValSimple(expr);
  17493. this.next();
  17494. expr = this.finishNode(node$1, "UpdateExpression");
  17495. }
  17496. }
  17497. if (!incDec && this.eat(types$1.starstar)) {
  17498. if (sawUnary)
  17499. { this.unexpected(this.lastTokStart); }
  17500. else
  17501. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  17502. } else {
  17503. return expr
  17504. }
  17505. };
  17506. function isPrivateFieldAccess(node) {
  17507. return (
  17508. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  17509. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  17510. )
  17511. }
  17512. // Parse call, dot, and `[]`-subscript expressions.
  17513. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  17514. var startPos = this.start, startLoc = this.startLoc;
  17515. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  17516. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  17517. { return expr }
  17518. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  17519. if (refDestructuringErrors && result.type === "MemberExpression") {
  17520. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  17521. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  17522. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  17523. }
  17524. return result
  17525. };
  17526. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  17527. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  17528. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  17529. this.potentialArrowAt === base.start;
  17530. var optionalChained = false;
  17531. while (true) {
  17532. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  17533. if (element.optional) { optionalChained = true; }
  17534. if (element === base || element.type === "ArrowFunctionExpression") {
  17535. if (optionalChained) {
  17536. var chainNode = this.startNodeAt(startPos, startLoc);
  17537. chainNode.expression = element;
  17538. element = this.finishNode(chainNode, "ChainExpression");
  17539. }
  17540. return element
  17541. }
  17542. base = element;
  17543. }
  17544. };
  17545. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  17546. var optionalSupported = this.options.ecmaVersion >= 11;
  17547. var optional = optionalSupported && this.eat(types$1.questionDot);
  17548. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  17549. var computed = this.eat(types$1.bracketL);
  17550. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  17551. var node = this.startNodeAt(startPos, startLoc);
  17552. node.object = base;
  17553. if (computed) {
  17554. node.property = this.parseExpression();
  17555. this.expect(types$1.bracketR);
  17556. } else if (this.type === types$1.privateId && base.type !== "Super") {
  17557. node.property = this.parsePrivateIdent();
  17558. } else {
  17559. node.property = this.parseIdent(this.options.allowReserved !== "never");
  17560. }
  17561. node.computed = !!computed;
  17562. if (optionalSupported) {
  17563. node.optional = optional;
  17564. }
  17565. base = this.finishNode(node, "MemberExpression");
  17566. } else if (!noCalls && this.eat(types$1.parenL)) {
  17567. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17568. this.yieldPos = 0;
  17569. this.awaitPos = 0;
  17570. this.awaitIdentPos = 0;
  17571. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  17572. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17573. this.checkPatternErrors(refDestructuringErrors, false);
  17574. this.checkYieldAwaitInDefaultParams();
  17575. if (this.awaitIdentPos > 0)
  17576. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  17577. this.yieldPos = oldYieldPos;
  17578. this.awaitPos = oldAwaitPos;
  17579. this.awaitIdentPos = oldAwaitIdentPos;
  17580. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  17581. }
  17582. this.checkExpressionErrors(refDestructuringErrors, true);
  17583. this.yieldPos = oldYieldPos || this.yieldPos;
  17584. this.awaitPos = oldAwaitPos || this.awaitPos;
  17585. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  17586. var node$1 = this.startNodeAt(startPos, startLoc);
  17587. node$1.callee = base;
  17588. node$1.arguments = exprList;
  17589. if (optionalSupported) {
  17590. node$1.optional = optional;
  17591. }
  17592. base = this.finishNode(node$1, "CallExpression");
  17593. } else if (this.type === types$1.backQuote) {
  17594. if (optional || optionalChained) {
  17595. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  17596. }
  17597. var node$2 = this.startNodeAt(startPos, startLoc);
  17598. node$2.tag = base;
  17599. node$2.quasi = this.parseTemplate({isTagged: true});
  17600. base = this.finishNode(node$2, "TaggedTemplateExpression");
  17601. }
  17602. return base
  17603. };
  17604. // Parse an atomic expression — either a single token that is an
  17605. // expression, an expression started by a keyword like `function` or
  17606. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  17607. // or `{}`.
  17608. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  17609. // If a division operator appears in an expression position, the
  17610. // tokenizer got confused, and we force it to read a regexp instead.
  17611. if (this.type === types$1.slash) { this.readRegexp(); }
  17612. var node, canBeArrow = this.potentialArrowAt === this.start;
  17613. switch (this.type) {
  17614. case types$1._super:
  17615. if (!this.allowSuper)
  17616. { this.raise(this.start, "'super' keyword outside a method"); }
  17617. node = this.startNode();
  17618. this.next();
  17619. if (this.type === types$1.parenL && !this.allowDirectSuper)
  17620. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  17621. // The `super` keyword can appear at below:
  17622. // SuperProperty:
  17623. // super [ Expression ]
  17624. // super . IdentifierName
  17625. // SuperCall:
  17626. // super ( Arguments )
  17627. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  17628. { this.unexpected(); }
  17629. return this.finishNode(node, "Super")
  17630. case types$1._this:
  17631. node = this.startNode();
  17632. this.next();
  17633. return this.finishNode(node, "ThisExpression")
  17634. case types$1.name:
  17635. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  17636. var id = this.parseIdent(false);
  17637. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  17638. this.overrideContext(types.f_expr);
  17639. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  17640. }
  17641. if (canBeArrow && !this.canInsertSemicolon()) {
  17642. if (this.eat(types$1.arrow))
  17643. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  17644. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  17645. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  17646. id = this.parseIdent(false);
  17647. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  17648. { this.unexpected(); }
  17649. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  17650. }
  17651. }
  17652. return id
  17653. case types$1.regexp:
  17654. var value = this.value;
  17655. node = this.parseLiteral(value.value);
  17656. node.regex = {pattern: value.pattern, flags: value.flags};
  17657. return node
  17658. case types$1.num: case types$1.string:
  17659. return this.parseLiteral(this.value)
  17660. case types$1._null: case types$1._true: case types$1._false:
  17661. node = this.startNode();
  17662. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  17663. node.raw = this.type.keyword;
  17664. this.next();
  17665. return this.finishNode(node, "Literal")
  17666. case types$1.parenL:
  17667. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  17668. if (refDestructuringErrors) {
  17669. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  17670. { refDestructuringErrors.parenthesizedAssign = start; }
  17671. if (refDestructuringErrors.parenthesizedBind < 0)
  17672. { refDestructuringErrors.parenthesizedBind = start; }
  17673. }
  17674. return expr
  17675. case types$1.bracketL:
  17676. node = this.startNode();
  17677. this.next();
  17678. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  17679. return this.finishNode(node, "ArrayExpression")
  17680. case types$1.braceL:
  17681. this.overrideContext(types.b_expr);
  17682. return this.parseObj(false, refDestructuringErrors)
  17683. case types$1._function:
  17684. node = this.startNode();
  17685. this.next();
  17686. return this.parseFunction(node, 0)
  17687. case types$1._class:
  17688. return this.parseClass(this.startNode(), false)
  17689. case types$1._new:
  17690. return this.parseNew()
  17691. case types$1.backQuote:
  17692. return this.parseTemplate()
  17693. case types$1._import:
  17694. if (this.options.ecmaVersion >= 11) {
  17695. return this.parseExprImport()
  17696. } else {
  17697. return this.unexpected()
  17698. }
  17699. default:
  17700. this.unexpected();
  17701. }
  17702. };
  17703. pp$5.parseExprImport = function() {
  17704. var node = this.startNode();
  17705. // Consume `import` as an identifier for `import.meta`.
  17706. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  17707. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  17708. var meta = this.parseIdent(true);
  17709. switch (this.type) {
  17710. case types$1.parenL:
  17711. return this.parseDynamicImport(node)
  17712. case types$1.dot:
  17713. node.meta = meta;
  17714. return this.parseImportMeta(node)
  17715. default:
  17716. this.unexpected();
  17717. }
  17718. };
  17719. pp$5.parseDynamicImport = function(node) {
  17720. this.next(); // skip `(`
  17721. // Parse node.source.
  17722. node.source = this.parseMaybeAssign();
  17723. // Verify ending.
  17724. if (!this.eat(types$1.parenR)) {
  17725. var errorPos = this.start;
  17726. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  17727. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  17728. } else {
  17729. this.unexpected(errorPos);
  17730. }
  17731. }
  17732. return this.finishNode(node, "ImportExpression")
  17733. };
  17734. pp$5.parseImportMeta = function(node) {
  17735. this.next(); // skip `.`
  17736. var containsEsc = this.containsEsc;
  17737. node.property = this.parseIdent(true);
  17738. if (node.property.name !== "meta")
  17739. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  17740. if (containsEsc)
  17741. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  17742. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  17743. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  17744. return this.finishNode(node, "MetaProperty")
  17745. };
  17746. pp$5.parseLiteral = function(value) {
  17747. var node = this.startNode();
  17748. node.value = value;
  17749. node.raw = this.input.slice(this.start, this.end);
  17750. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  17751. this.next();
  17752. return this.finishNode(node, "Literal")
  17753. };
  17754. pp$5.parseParenExpression = function() {
  17755. this.expect(types$1.parenL);
  17756. var val = this.parseExpression();
  17757. this.expect(types$1.parenR);
  17758. return val
  17759. };
  17760. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  17761. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  17762. if (this.options.ecmaVersion >= 6) {
  17763. this.next();
  17764. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  17765. var exprList = [], first = true, lastIsComma = false;
  17766. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  17767. this.yieldPos = 0;
  17768. this.awaitPos = 0;
  17769. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  17770. while (this.type !== types$1.parenR) {
  17771. first ? first = false : this.expect(types$1.comma);
  17772. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  17773. lastIsComma = true;
  17774. break
  17775. } else if (this.type === types$1.ellipsis) {
  17776. spreadStart = this.start;
  17777. exprList.push(this.parseParenItem(this.parseRestBinding()));
  17778. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17779. break
  17780. } else {
  17781. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  17782. }
  17783. }
  17784. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  17785. this.expect(types$1.parenR);
  17786. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17787. this.checkPatternErrors(refDestructuringErrors, false);
  17788. this.checkYieldAwaitInDefaultParams();
  17789. this.yieldPos = oldYieldPos;
  17790. this.awaitPos = oldAwaitPos;
  17791. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  17792. }
  17793. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  17794. if (spreadStart) { this.unexpected(spreadStart); }
  17795. this.checkExpressionErrors(refDestructuringErrors, true);
  17796. this.yieldPos = oldYieldPos || this.yieldPos;
  17797. this.awaitPos = oldAwaitPos || this.awaitPos;
  17798. if (exprList.length > 1) {
  17799. val = this.startNodeAt(innerStartPos, innerStartLoc);
  17800. val.expressions = exprList;
  17801. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  17802. } else {
  17803. val = exprList[0];
  17804. }
  17805. } else {
  17806. val = this.parseParenExpression();
  17807. }
  17808. if (this.options.preserveParens) {
  17809. var par = this.startNodeAt(startPos, startLoc);
  17810. par.expression = val;
  17811. return this.finishNode(par, "ParenthesizedExpression")
  17812. } else {
  17813. return val
  17814. }
  17815. };
  17816. pp$5.parseParenItem = function(item) {
  17817. return item
  17818. };
  17819. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  17820. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  17821. };
  17822. // New's precedence is slightly tricky. It must allow its argument to
  17823. // be a `[]` or dot subscript expression, but not a call — at least,
  17824. // not without wrapping it in parentheses. Thus, it uses the noCalls
  17825. // argument to parseSubscripts to prevent it from consuming the
  17826. // argument list.
  17827. var empty = [];
  17828. pp$5.parseNew = function() {
  17829. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  17830. var node = this.startNode();
  17831. var meta = this.parseIdent(true);
  17832. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  17833. node.meta = meta;
  17834. var containsEsc = this.containsEsc;
  17835. node.property = this.parseIdent(true);
  17836. if (node.property.name !== "target")
  17837. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  17838. if (containsEsc)
  17839. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  17840. if (!this.allowNewDotTarget)
  17841. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  17842. return this.finishNode(node, "MetaProperty")
  17843. }
  17844. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  17845. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  17846. if (isImport && node.callee.type === "ImportExpression") {
  17847. this.raise(startPos, "Cannot use new with import()");
  17848. }
  17849. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  17850. else { node.arguments = empty; }
  17851. return this.finishNode(node, "NewExpression")
  17852. };
  17853. // Parse template expression.
  17854. pp$5.parseTemplateElement = function(ref) {
  17855. var isTagged = ref.isTagged;
  17856. var elem = this.startNode();
  17857. if (this.type === types$1.invalidTemplate) {
  17858. if (!isTagged) {
  17859. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  17860. }
  17861. elem.value = {
  17862. raw: this.value,
  17863. cooked: null
  17864. };
  17865. } else {
  17866. elem.value = {
  17867. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  17868. cooked: this.value
  17869. };
  17870. }
  17871. this.next();
  17872. elem.tail = this.type === types$1.backQuote;
  17873. return this.finishNode(elem, "TemplateElement")
  17874. };
  17875. pp$5.parseTemplate = function(ref) {
  17876. if ( ref === void 0 ) ref = {};
  17877. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  17878. var node = this.startNode();
  17879. this.next();
  17880. node.expressions = [];
  17881. var curElt = this.parseTemplateElement({isTagged: isTagged});
  17882. node.quasis = [curElt];
  17883. while (!curElt.tail) {
  17884. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  17885. this.expect(types$1.dollarBraceL);
  17886. node.expressions.push(this.parseExpression());
  17887. this.expect(types$1.braceR);
  17888. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  17889. }
  17890. this.next();
  17891. return this.finishNode(node, "TemplateLiteral")
  17892. };
  17893. pp$5.isAsyncProp = function(prop) {
  17894. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  17895. (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)) &&
  17896. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17897. };
  17898. // Parse an object literal or binding pattern.
  17899. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  17900. var node = this.startNode(), first = true, propHash = {};
  17901. node.properties = [];
  17902. this.next();
  17903. while (!this.eat(types$1.braceR)) {
  17904. if (!first) {
  17905. this.expect(types$1.comma);
  17906. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  17907. } else { first = false; }
  17908. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  17909. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  17910. node.properties.push(prop);
  17911. }
  17912. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  17913. };
  17914. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  17915. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  17916. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  17917. if (isPattern) {
  17918. prop.argument = this.parseIdent(false);
  17919. if (this.type === types$1.comma) {
  17920. this.raise(this.start, "Comma is not permitted after the rest element");
  17921. }
  17922. return this.finishNode(prop, "RestElement")
  17923. }
  17924. // To disallow parenthesized identifier via `this.toAssignable()`.
  17925. if (this.type === types$1.parenL && refDestructuringErrors) {
  17926. if (refDestructuringErrors.parenthesizedAssign < 0) {
  17927. refDestructuringErrors.parenthesizedAssign = this.start;
  17928. }
  17929. if (refDestructuringErrors.parenthesizedBind < 0) {
  17930. refDestructuringErrors.parenthesizedBind = this.start;
  17931. }
  17932. }
  17933. // Parse argument.
  17934. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  17935. // To disallow trailing comma via `this.toAssignable()`.
  17936. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  17937. refDestructuringErrors.trailingComma = this.start;
  17938. }
  17939. // Finish
  17940. return this.finishNode(prop, "SpreadElement")
  17941. }
  17942. if (this.options.ecmaVersion >= 6) {
  17943. prop.method = false;
  17944. prop.shorthand = false;
  17945. if (isPattern || refDestructuringErrors) {
  17946. startPos = this.start;
  17947. startLoc = this.startLoc;
  17948. }
  17949. if (!isPattern)
  17950. { isGenerator = this.eat(types$1.star); }
  17951. }
  17952. var containsEsc = this.containsEsc;
  17953. this.parsePropertyName(prop);
  17954. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  17955. isAsync = true;
  17956. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  17957. this.parsePropertyName(prop, refDestructuringErrors);
  17958. } else {
  17959. isAsync = false;
  17960. }
  17961. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  17962. return this.finishNode(prop, "Property")
  17963. };
  17964. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  17965. if ((isGenerator || isAsync) && this.type === types$1.colon)
  17966. { this.unexpected(); }
  17967. if (this.eat(types$1.colon)) {
  17968. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  17969. prop.kind = "init";
  17970. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  17971. if (isPattern) { this.unexpected(); }
  17972. prop.kind = "init";
  17973. prop.method = true;
  17974. prop.value = this.parseMethod(isGenerator, isAsync);
  17975. } else if (!isPattern && !containsEsc &&
  17976. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  17977. (prop.key.name === "get" || prop.key.name === "set") &&
  17978. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  17979. if (isGenerator || isAsync) { this.unexpected(); }
  17980. prop.kind = prop.key.name;
  17981. this.parsePropertyName(prop);
  17982. prop.value = this.parseMethod(false);
  17983. var paramCount = prop.kind === "get" ? 0 : 1;
  17984. if (prop.value.params.length !== paramCount) {
  17985. var start = prop.value.start;
  17986. if (prop.kind === "get")
  17987. { this.raiseRecoverable(start, "getter should have no params"); }
  17988. else
  17989. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  17990. } else {
  17991. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  17992. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  17993. }
  17994. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  17995. if (isGenerator || isAsync) { this.unexpected(); }
  17996. this.checkUnreserved(prop.key);
  17997. if (prop.key.name === "await" && !this.awaitIdentPos)
  17998. { this.awaitIdentPos = startPos; }
  17999. prop.kind = "init";
  18000. if (isPattern) {
  18001. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18002. } else if (this.type === types$1.eq && refDestructuringErrors) {
  18003. if (refDestructuringErrors.shorthandAssign < 0)
  18004. { refDestructuringErrors.shorthandAssign = this.start; }
  18005. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18006. } else {
  18007. prop.value = this.copyNode(prop.key);
  18008. }
  18009. prop.shorthand = true;
  18010. } else { this.unexpected(); }
  18011. };
  18012. pp$5.parsePropertyName = function(prop) {
  18013. if (this.options.ecmaVersion >= 6) {
  18014. if (this.eat(types$1.bracketL)) {
  18015. prop.computed = true;
  18016. prop.key = this.parseMaybeAssign();
  18017. this.expect(types$1.bracketR);
  18018. return prop.key
  18019. } else {
  18020. prop.computed = false;
  18021. }
  18022. }
  18023. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  18024. };
  18025. // Initialize empty function node.
  18026. pp$5.initFunction = function(node) {
  18027. node.id = null;
  18028. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  18029. if (this.options.ecmaVersion >= 8) { node.async = false; }
  18030. };
  18031. // Parse object or class method.
  18032. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  18033. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18034. this.initFunction(node);
  18035. if (this.options.ecmaVersion >= 6)
  18036. { node.generator = isGenerator; }
  18037. if (this.options.ecmaVersion >= 8)
  18038. { node.async = !!isAsync; }
  18039. this.yieldPos = 0;
  18040. this.awaitPos = 0;
  18041. this.awaitIdentPos = 0;
  18042. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  18043. this.expect(types$1.parenL);
  18044. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18045. this.checkYieldAwaitInDefaultParams();
  18046. this.parseFunctionBody(node, false, true, false);
  18047. this.yieldPos = oldYieldPos;
  18048. this.awaitPos = oldAwaitPos;
  18049. this.awaitIdentPos = oldAwaitIdentPos;
  18050. return this.finishNode(node, "FunctionExpression")
  18051. };
  18052. // Parse arrow function expression with given parameters.
  18053. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  18054. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18055. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  18056. this.initFunction(node);
  18057. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  18058. this.yieldPos = 0;
  18059. this.awaitPos = 0;
  18060. this.awaitIdentPos = 0;
  18061. node.params = this.toAssignableList(params, true);
  18062. this.parseFunctionBody(node, true, false, forInit);
  18063. this.yieldPos = oldYieldPos;
  18064. this.awaitPos = oldAwaitPos;
  18065. this.awaitIdentPos = oldAwaitIdentPos;
  18066. return this.finishNode(node, "ArrowFunctionExpression")
  18067. };
  18068. // Parse function body and check parameters.
  18069. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  18070. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  18071. var oldStrict = this.strict, useStrict = false;
  18072. if (isExpression) {
  18073. node.body = this.parseMaybeAssign(forInit);
  18074. node.expression = true;
  18075. this.checkParams(node, false);
  18076. } else {
  18077. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  18078. if (!oldStrict || nonSimple) {
  18079. useStrict = this.strictDirective(this.end);
  18080. // If this is a strict mode function, verify that argument names
  18081. // are not repeated, and it does not try to bind the words `eval`
  18082. // or `arguments`.
  18083. if (useStrict && nonSimple)
  18084. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  18085. }
  18086. // Start a new scope with regard to labels and the `inFunction`
  18087. // flag (restore them to their old value afterwards).
  18088. var oldLabels = this.labels;
  18089. this.labels = [];
  18090. if (useStrict) { this.strict = true; }
  18091. // Add the params to varDeclaredNames to ensure that an error is thrown
  18092. // if a let/const declaration in the function clashes with one of the params.
  18093. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  18094. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  18095. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  18096. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  18097. node.expression = false;
  18098. this.adaptDirectivePrologue(node.body.body);
  18099. this.labels = oldLabels;
  18100. }
  18101. this.exitScope();
  18102. };
  18103. pp$5.isSimpleParamList = function(params) {
  18104. for (var i = 0, list = params; i < list.length; i += 1)
  18105. {
  18106. var param = list[i];
  18107. if (param.type !== "Identifier") { return false
  18108. } }
  18109. return true
  18110. };
  18111. // Checks function params for various disallowed patterns such as using "eval"
  18112. // or "arguments" and duplicate parameters.
  18113. pp$5.checkParams = function(node, allowDuplicates) {
  18114. var nameHash = Object.create(null);
  18115. for (var i = 0, list = node.params; i < list.length; i += 1)
  18116. {
  18117. var param = list[i];
  18118. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  18119. }
  18120. };
  18121. // Parses a comma-separated list of expressions, and returns them as
  18122. // an array. `close` is the token type that ends the list, and
  18123. // `allowEmpty` can be turned on to allow subsequent commas with
  18124. // nothing in between them to be parsed as `null` (which is needed
  18125. // for array literals).
  18126. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  18127. var elts = [], first = true;
  18128. while (!this.eat(close)) {
  18129. if (!first) {
  18130. this.expect(types$1.comma);
  18131. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  18132. } else { first = false; }
  18133. var elt = (void 0);
  18134. if (allowEmpty && this.type === types$1.comma)
  18135. { elt = null; }
  18136. else if (this.type === types$1.ellipsis) {
  18137. elt = this.parseSpread(refDestructuringErrors);
  18138. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  18139. { refDestructuringErrors.trailingComma = this.start; }
  18140. } else {
  18141. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  18142. }
  18143. elts.push(elt);
  18144. }
  18145. return elts
  18146. };
  18147. pp$5.checkUnreserved = function(ref) {
  18148. var start = ref.start;
  18149. var end = ref.end;
  18150. var name = ref.name;
  18151. if (this.inGenerator && name === "yield")
  18152. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  18153. if (this.inAsync && name === "await")
  18154. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  18155. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  18156. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  18157. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  18158. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  18159. if (this.keywords.test(name))
  18160. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  18161. if (this.options.ecmaVersion < 6 &&
  18162. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  18163. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  18164. if (re.test(name)) {
  18165. if (!this.inAsync && name === "await")
  18166. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  18167. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  18168. }
  18169. };
  18170. // Parse the next token as an identifier. If `liberal` is true (used
  18171. // when parsing properties), it will also convert keywords into
  18172. // identifiers.
  18173. pp$5.parseIdent = function(liberal, isBinding) {
  18174. var node = this.startNode();
  18175. if (this.type === types$1.name) {
  18176. node.name = this.value;
  18177. } else if (this.type.keyword) {
  18178. node.name = this.type.keyword;
  18179. // To fix https://github.com/acornjs/acorn/issues/575
  18180. // `class` and `function` keywords push new context into this.context.
  18181. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  18182. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  18183. if ((node.name === "class" || node.name === "function") &&
  18184. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  18185. this.context.pop();
  18186. }
  18187. } else {
  18188. this.unexpected();
  18189. }
  18190. this.next(!!liberal);
  18191. this.finishNode(node, "Identifier");
  18192. if (!liberal) {
  18193. this.checkUnreserved(node);
  18194. if (node.name === "await" && !this.awaitIdentPos)
  18195. { this.awaitIdentPos = node.start; }
  18196. }
  18197. return node
  18198. };
  18199. pp$5.parsePrivateIdent = function() {
  18200. var node = this.startNode();
  18201. if (this.type === types$1.privateId) {
  18202. node.name = this.value;
  18203. } else {
  18204. this.unexpected();
  18205. }
  18206. this.next();
  18207. this.finishNode(node, "PrivateIdentifier");
  18208. // For validating existence
  18209. if (this.privateNameStack.length === 0) {
  18210. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  18211. } else {
  18212. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  18213. }
  18214. return node
  18215. };
  18216. // Parses yield expression inside generator.
  18217. pp$5.parseYield = function(forInit) {
  18218. if (!this.yieldPos) { this.yieldPos = this.start; }
  18219. var node = this.startNode();
  18220. this.next();
  18221. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  18222. node.delegate = false;
  18223. node.argument = null;
  18224. } else {
  18225. node.delegate = this.eat(types$1.star);
  18226. node.argument = this.parseMaybeAssign(forInit);
  18227. }
  18228. return this.finishNode(node, "YieldExpression")
  18229. };
  18230. pp$5.parseAwait = function(forInit) {
  18231. if (!this.awaitPos) { this.awaitPos = this.start; }
  18232. var node = this.startNode();
  18233. this.next();
  18234. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  18235. return this.finishNode(node, "AwaitExpression")
  18236. };
  18237. var pp$4 = Parser.prototype;
  18238. // This function is used to raise exceptions on parse errors. It
  18239. // takes an offset integer (into the current `input`) to indicate
  18240. // the location of the error, attaches the position to the end
  18241. // of the error message, and then raises a `SyntaxError` with that
  18242. // message.
  18243. pp$4.raise = function(pos, message) {
  18244. var loc = getLineInfo(this.input, pos);
  18245. message += " (" + loc.line + ":" + loc.column + ")";
  18246. var err = new SyntaxError(message);
  18247. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  18248. throw err
  18249. };
  18250. pp$4.raiseRecoverable = pp$4.raise;
  18251. pp$4.curPosition = function() {
  18252. if (this.options.locations) {
  18253. return new Position(this.curLine, this.pos - this.lineStart)
  18254. }
  18255. };
  18256. var pp$3 = Parser.prototype;
  18257. var Scope = function Scope(flags) {
  18258. this.flags = flags;
  18259. // A list of var-declared names in the current lexical scope
  18260. this.var = [];
  18261. // A list of lexically-declared names in the current lexical scope
  18262. this.lexical = [];
  18263. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  18264. this.functions = [];
  18265. // A switch to disallow the identifier reference 'arguments'
  18266. this.inClassFieldInit = false;
  18267. };
  18268. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  18269. pp$3.enterScope = function(flags) {
  18270. this.scopeStack.push(new Scope(flags));
  18271. };
  18272. pp$3.exitScope = function() {
  18273. this.scopeStack.pop();
  18274. };
  18275. // The spec says:
  18276. // > At the top level of a function, or script, function declarations are
  18277. // > treated like var declarations rather than like lexical declarations.
  18278. pp$3.treatFunctionsAsVarInScope = function(scope) {
  18279. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  18280. };
  18281. pp$3.declareName = function(name, bindingType, pos) {
  18282. var redeclared = false;
  18283. if (bindingType === BIND_LEXICAL) {
  18284. var scope = this.currentScope();
  18285. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  18286. scope.lexical.push(name);
  18287. if (this.inModule && (scope.flags & SCOPE_TOP))
  18288. { delete this.undefinedExports[name]; }
  18289. } else if (bindingType === BIND_SIMPLE_CATCH) {
  18290. var scope$1 = this.currentScope();
  18291. scope$1.lexical.push(name);
  18292. } else if (bindingType === BIND_FUNCTION) {
  18293. var scope$2 = this.currentScope();
  18294. if (this.treatFunctionsAsVar)
  18295. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  18296. else
  18297. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  18298. scope$2.functions.push(name);
  18299. } else {
  18300. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  18301. var scope$3 = this.scopeStack[i];
  18302. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  18303. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  18304. redeclared = true;
  18305. break
  18306. }
  18307. scope$3.var.push(name);
  18308. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  18309. { delete this.undefinedExports[name]; }
  18310. if (scope$3.flags & SCOPE_VAR) { break }
  18311. }
  18312. }
  18313. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  18314. };
  18315. pp$3.checkLocalExport = function(id) {
  18316. // scope.functions must be empty as Module code is always strict.
  18317. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  18318. this.scopeStack[0].var.indexOf(id.name) === -1) {
  18319. this.undefinedExports[id.name] = id;
  18320. }
  18321. };
  18322. pp$3.currentScope = function() {
  18323. return this.scopeStack[this.scopeStack.length - 1]
  18324. };
  18325. pp$3.currentVarScope = function() {
  18326. for (var i = this.scopeStack.length - 1;; i--) {
  18327. var scope = this.scopeStack[i];
  18328. if (scope.flags & SCOPE_VAR) { return scope }
  18329. }
  18330. };
  18331. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  18332. pp$3.currentThisScope = function() {
  18333. for (var i = this.scopeStack.length - 1;; i--) {
  18334. var scope = this.scopeStack[i];
  18335. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  18336. }
  18337. };
  18338. var Node = function Node(parser, pos, loc) {
  18339. this.type = "";
  18340. this.start = pos;
  18341. this.end = 0;
  18342. if (parser.options.locations)
  18343. { this.loc = new SourceLocation(parser, loc); }
  18344. if (parser.options.directSourceFile)
  18345. { this.sourceFile = parser.options.directSourceFile; }
  18346. if (parser.options.ranges)
  18347. { this.range = [pos, 0]; }
  18348. };
  18349. // Start an AST node, attaching a start offset.
  18350. var pp$2 = Parser.prototype;
  18351. pp$2.startNode = function() {
  18352. return new Node(this, this.start, this.startLoc)
  18353. };
  18354. pp$2.startNodeAt = function(pos, loc) {
  18355. return new Node(this, pos, loc)
  18356. };
  18357. // Finish an AST node, adding `type` and `end` properties.
  18358. function finishNodeAt(node, type, pos, loc) {
  18359. node.type = type;
  18360. node.end = pos;
  18361. if (this.options.locations)
  18362. { node.loc.end = loc; }
  18363. if (this.options.ranges)
  18364. { node.range[1] = pos; }
  18365. return node
  18366. }
  18367. pp$2.finishNode = function(node, type) {
  18368. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  18369. };
  18370. // Finish node at given position
  18371. pp$2.finishNodeAt = function(node, type, pos, loc) {
  18372. return finishNodeAt.call(this, node, type, pos, loc)
  18373. };
  18374. pp$2.copyNode = function(node) {
  18375. var newNode = new Node(this, node.start, this.startLoc);
  18376. for (var prop in node) { newNode[prop] = node[prop]; }
  18377. return newNode
  18378. };
  18379. // This file contains Unicode properties extracted from the ECMAScript
  18380. // specification. The lists are extracted like so:
  18381. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  18382. // #table-binary-unicode-properties
  18383. 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";
  18384. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  18385. var ecma11BinaryProperties = ecma10BinaryProperties;
  18386. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  18387. var ecma13BinaryProperties = ecma12BinaryProperties;
  18388. var unicodeBinaryProperties = {
  18389. 9: ecma9BinaryProperties,
  18390. 10: ecma10BinaryProperties,
  18391. 11: ecma11BinaryProperties,
  18392. 12: ecma12BinaryProperties,
  18393. 13: ecma13BinaryProperties
  18394. };
  18395. // #table-unicode-general-category-values
  18396. 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";
  18397. // #table-unicode-script-values
  18398. 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";
  18399. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  18400. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  18401. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  18402. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  18403. var unicodeScriptValues = {
  18404. 9: ecma9ScriptValues,
  18405. 10: ecma10ScriptValues,
  18406. 11: ecma11ScriptValues,
  18407. 12: ecma12ScriptValues,
  18408. 13: ecma13ScriptValues
  18409. };
  18410. var data = {};
  18411. function buildUnicodeData(ecmaVersion) {
  18412. var d = data[ecmaVersion] = {
  18413. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  18414. nonBinary: {
  18415. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  18416. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  18417. }
  18418. };
  18419. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  18420. d.nonBinary.gc = d.nonBinary.General_Category;
  18421. d.nonBinary.sc = d.nonBinary.Script;
  18422. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  18423. }
  18424. for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
  18425. var ecmaVersion = list[i];
  18426. buildUnicodeData(ecmaVersion);
  18427. }
  18428. var pp$1 = Parser.prototype;
  18429. var RegExpValidationState = function RegExpValidationState(parser) {
  18430. this.parser = parser;
  18431. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  18432. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  18433. this.source = "";
  18434. this.flags = "";
  18435. this.start = 0;
  18436. this.switchU = false;
  18437. this.switchN = false;
  18438. this.pos = 0;
  18439. this.lastIntValue = 0;
  18440. this.lastStringValue = "";
  18441. this.lastAssertionIsQuantifiable = false;
  18442. this.numCapturingParens = 0;
  18443. this.maxBackReference = 0;
  18444. this.groupNames = [];
  18445. this.backReferenceNames = [];
  18446. };
  18447. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  18448. var unicode = flags.indexOf("u") !== -1;
  18449. this.start = start | 0;
  18450. this.source = pattern + "";
  18451. this.flags = flags;
  18452. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  18453. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  18454. };
  18455. RegExpValidationState.prototype.raise = function raise (message) {
  18456. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  18457. };
  18458. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  18459. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  18460. RegExpValidationState.prototype.at = function at (i, forceU) {
  18461. if ( forceU === void 0 ) forceU = false;
  18462. var s = this.source;
  18463. var l = s.length;
  18464. if (i >= l) {
  18465. return -1
  18466. }
  18467. var c = s.charCodeAt(i);
  18468. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  18469. return c
  18470. }
  18471. var next = s.charCodeAt(i + 1);
  18472. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  18473. };
  18474. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  18475. if ( forceU === void 0 ) forceU = false;
  18476. var s = this.source;
  18477. var l = s.length;
  18478. if (i >= l) {
  18479. return l
  18480. }
  18481. var c = s.charCodeAt(i), next;
  18482. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  18483. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  18484. return i + 1
  18485. }
  18486. return i + 2
  18487. };
  18488. RegExpValidationState.prototype.current = function current (forceU) {
  18489. if ( forceU === void 0 ) forceU = false;
  18490. return this.at(this.pos, forceU)
  18491. };
  18492. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  18493. if ( forceU === void 0 ) forceU = false;
  18494. return this.at(this.nextIndex(this.pos, forceU), forceU)
  18495. };
  18496. RegExpValidationState.prototype.advance = function advance (forceU) {
  18497. if ( forceU === void 0 ) forceU = false;
  18498. this.pos = this.nextIndex(this.pos, forceU);
  18499. };
  18500. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  18501. if ( forceU === void 0 ) forceU = false;
  18502. if (this.current(forceU) === ch) {
  18503. this.advance(forceU);
  18504. return true
  18505. }
  18506. return false
  18507. };
  18508. /**
  18509. * Validate the flags part of a given RegExpLiteral.
  18510. *
  18511. * @param {RegExpValidationState} state The state to validate RegExp.
  18512. * @returns {void}
  18513. */
  18514. pp$1.validateRegExpFlags = function(state) {
  18515. var validFlags = state.validFlags;
  18516. var flags = state.flags;
  18517. for (var i = 0; i < flags.length; i++) {
  18518. var flag = flags.charAt(i);
  18519. if (validFlags.indexOf(flag) === -1) {
  18520. this.raise(state.start, "Invalid regular expression flag");
  18521. }
  18522. if (flags.indexOf(flag, i + 1) > -1) {
  18523. this.raise(state.start, "Duplicate regular expression flag");
  18524. }
  18525. }
  18526. };
  18527. /**
  18528. * Validate the pattern part of a given RegExpLiteral.
  18529. *
  18530. * @param {RegExpValidationState} state The state to validate RegExp.
  18531. * @returns {void}
  18532. */
  18533. pp$1.validateRegExpPattern = function(state) {
  18534. this.regexp_pattern(state);
  18535. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  18536. // parsing contains a |GroupName|, reparse with the goal symbol
  18537. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  18538. // exception if _P_ did not conform to the grammar, if any elements of _P_
  18539. // were not matched by the parse, or if any Early Error conditions exist.
  18540. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  18541. state.switchN = true;
  18542. this.regexp_pattern(state);
  18543. }
  18544. };
  18545. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  18546. pp$1.regexp_pattern = function(state) {
  18547. state.pos = 0;
  18548. state.lastIntValue = 0;
  18549. state.lastStringValue = "";
  18550. state.lastAssertionIsQuantifiable = false;
  18551. state.numCapturingParens = 0;
  18552. state.maxBackReference = 0;
  18553. state.groupNames.length = 0;
  18554. state.backReferenceNames.length = 0;
  18555. this.regexp_disjunction(state);
  18556. if (state.pos !== state.source.length) {
  18557. // Make the same messages as V8.
  18558. if (state.eat(0x29 /* ) */)) {
  18559. state.raise("Unmatched ')'");
  18560. }
  18561. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  18562. state.raise("Lone quantifier brackets");
  18563. }
  18564. }
  18565. if (state.maxBackReference > state.numCapturingParens) {
  18566. state.raise("Invalid escape");
  18567. }
  18568. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  18569. var name = list[i];
  18570. if (state.groupNames.indexOf(name) === -1) {
  18571. state.raise("Invalid named capture referenced");
  18572. }
  18573. }
  18574. };
  18575. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  18576. pp$1.regexp_disjunction = function(state) {
  18577. this.regexp_alternative(state);
  18578. while (state.eat(0x7C /* | */)) {
  18579. this.regexp_alternative(state);
  18580. }
  18581. // Make the same message as V8.
  18582. if (this.regexp_eatQuantifier(state, true)) {
  18583. state.raise("Nothing to repeat");
  18584. }
  18585. if (state.eat(0x7B /* { */)) {
  18586. state.raise("Lone quantifier brackets");
  18587. }
  18588. };
  18589. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  18590. pp$1.regexp_alternative = function(state) {
  18591. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  18592. { }
  18593. };
  18594. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  18595. pp$1.regexp_eatTerm = function(state) {
  18596. if (this.regexp_eatAssertion(state)) {
  18597. // Handle `QuantifiableAssertion Quantifier` alternative.
  18598. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  18599. // is a QuantifiableAssertion.
  18600. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  18601. // Make the same message as V8.
  18602. if (state.switchU) {
  18603. state.raise("Invalid quantifier");
  18604. }
  18605. }
  18606. return true
  18607. }
  18608. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  18609. this.regexp_eatQuantifier(state);
  18610. return true
  18611. }
  18612. return false
  18613. };
  18614. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  18615. pp$1.regexp_eatAssertion = function(state) {
  18616. var start = state.pos;
  18617. state.lastAssertionIsQuantifiable = false;
  18618. // ^, $
  18619. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  18620. return true
  18621. }
  18622. // \b \B
  18623. if (state.eat(0x5C /* \ */)) {
  18624. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  18625. return true
  18626. }
  18627. state.pos = start;
  18628. }
  18629. // Lookahead / Lookbehind
  18630. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  18631. var lookbehind = false;
  18632. if (this.options.ecmaVersion >= 9) {
  18633. lookbehind = state.eat(0x3C /* < */);
  18634. }
  18635. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  18636. this.regexp_disjunction(state);
  18637. if (!state.eat(0x29 /* ) */)) {
  18638. state.raise("Unterminated group");
  18639. }
  18640. state.lastAssertionIsQuantifiable = !lookbehind;
  18641. return true
  18642. }
  18643. }
  18644. state.pos = start;
  18645. return false
  18646. };
  18647. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  18648. pp$1.regexp_eatQuantifier = function(state, noError) {
  18649. if ( noError === void 0 ) noError = false;
  18650. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  18651. state.eat(0x3F /* ? */);
  18652. return true
  18653. }
  18654. return false
  18655. };
  18656. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  18657. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  18658. return (
  18659. state.eat(0x2A /* * */) ||
  18660. state.eat(0x2B /* + */) ||
  18661. state.eat(0x3F /* ? */) ||
  18662. this.regexp_eatBracedQuantifier(state, noError)
  18663. )
  18664. };
  18665. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  18666. var start = state.pos;
  18667. if (state.eat(0x7B /* { */)) {
  18668. var min = 0, max = -1;
  18669. if (this.regexp_eatDecimalDigits(state)) {
  18670. min = state.lastIntValue;
  18671. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  18672. max = state.lastIntValue;
  18673. }
  18674. if (state.eat(0x7D /* } */)) {
  18675. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  18676. if (max !== -1 && max < min && !noError) {
  18677. state.raise("numbers out of order in {} quantifier");
  18678. }
  18679. return true
  18680. }
  18681. }
  18682. if (state.switchU && !noError) {
  18683. state.raise("Incomplete quantifier");
  18684. }
  18685. state.pos = start;
  18686. }
  18687. return false
  18688. };
  18689. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  18690. pp$1.regexp_eatAtom = function(state) {
  18691. return (
  18692. this.regexp_eatPatternCharacters(state) ||
  18693. state.eat(0x2E /* . */) ||
  18694. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18695. this.regexp_eatCharacterClass(state) ||
  18696. this.regexp_eatUncapturingGroup(state) ||
  18697. this.regexp_eatCapturingGroup(state)
  18698. )
  18699. };
  18700. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  18701. var start = state.pos;
  18702. if (state.eat(0x5C /* \ */)) {
  18703. if (this.regexp_eatAtomEscape(state)) {
  18704. return true
  18705. }
  18706. state.pos = start;
  18707. }
  18708. return false
  18709. };
  18710. pp$1.regexp_eatUncapturingGroup = function(state) {
  18711. var start = state.pos;
  18712. if (state.eat(0x28 /* ( */)) {
  18713. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  18714. this.regexp_disjunction(state);
  18715. if (state.eat(0x29 /* ) */)) {
  18716. return true
  18717. }
  18718. state.raise("Unterminated group");
  18719. }
  18720. state.pos = start;
  18721. }
  18722. return false
  18723. };
  18724. pp$1.regexp_eatCapturingGroup = function(state) {
  18725. if (state.eat(0x28 /* ( */)) {
  18726. if (this.options.ecmaVersion >= 9) {
  18727. this.regexp_groupSpecifier(state);
  18728. } else if (state.current() === 0x3F /* ? */) {
  18729. state.raise("Invalid group");
  18730. }
  18731. this.regexp_disjunction(state);
  18732. if (state.eat(0x29 /* ) */)) {
  18733. state.numCapturingParens += 1;
  18734. return true
  18735. }
  18736. state.raise("Unterminated group");
  18737. }
  18738. return false
  18739. };
  18740. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  18741. pp$1.regexp_eatExtendedAtom = function(state) {
  18742. return (
  18743. state.eat(0x2E /* . */) ||
  18744. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18745. this.regexp_eatCharacterClass(state) ||
  18746. this.regexp_eatUncapturingGroup(state) ||
  18747. this.regexp_eatCapturingGroup(state) ||
  18748. this.regexp_eatInvalidBracedQuantifier(state) ||
  18749. this.regexp_eatExtendedPatternCharacter(state)
  18750. )
  18751. };
  18752. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  18753. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  18754. if (this.regexp_eatBracedQuantifier(state, true)) {
  18755. state.raise("Nothing to repeat");
  18756. }
  18757. return false
  18758. };
  18759. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  18760. pp$1.regexp_eatSyntaxCharacter = function(state) {
  18761. var ch = state.current();
  18762. if (isSyntaxCharacter(ch)) {
  18763. state.lastIntValue = ch;
  18764. state.advance();
  18765. return true
  18766. }
  18767. return false
  18768. };
  18769. function isSyntaxCharacter(ch) {
  18770. return (
  18771. ch === 0x24 /* $ */ ||
  18772. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  18773. ch === 0x2E /* . */ ||
  18774. ch === 0x3F /* ? */ ||
  18775. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  18776. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  18777. )
  18778. }
  18779. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  18780. // But eat eager.
  18781. pp$1.regexp_eatPatternCharacters = function(state) {
  18782. var start = state.pos;
  18783. var ch = 0;
  18784. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  18785. state.advance();
  18786. }
  18787. return state.pos !== start
  18788. };
  18789. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  18790. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  18791. var ch = state.current();
  18792. if (
  18793. ch !== -1 &&
  18794. ch !== 0x24 /* $ */ &&
  18795. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  18796. ch !== 0x2E /* . */ &&
  18797. ch !== 0x3F /* ? */ &&
  18798. ch !== 0x5B /* [ */ &&
  18799. ch !== 0x5E /* ^ */ &&
  18800. ch !== 0x7C /* | */
  18801. ) {
  18802. state.advance();
  18803. return true
  18804. }
  18805. return false
  18806. };
  18807. // GroupSpecifier ::
  18808. // [empty]
  18809. // `?` GroupName
  18810. pp$1.regexp_groupSpecifier = function(state) {
  18811. if (state.eat(0x3F /* ? */)) {
  18812. if (this.regexp_eatGroupName(state)) {
  18813. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  18814. state.raise("Duplicate capture group name");
  18815. }
  18816. state.groupNames.push(state.lastStringValue);
  18817. return
  18818. }
  18819. state.raise("Invalid group");
  18820. }
  18821. };
  18822. // GroupName ::
  18823. // `<` RegExpIdentifierName `>`
  18824. // Note: this updates `state.lastStringValue` property with the eaten name.
  18825. pp$1.regexp_eatGroupName = function(state) {
  18826. state.lastStringValue = "";
  18827. if (state.eat(0x3C /* < */)) {
  18828. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  18829. return true
  18830. }
  18831. state.raise("Invalid capture group name");
  18832. }
  18833. return false
  18834. };
  18835. // RegExpIdentifierName ::
  18836. // RegExpIdentifierStart
  18837. // RegExpIdentifierName RegExpIdentifierPart
  18838. // Note: this updates `state.lastStringValue` property with the eaten name.
  18839. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  18840. state.lastStringValue = "";
  18841. if (this.regexp_eatRegExpIdentifierStart(state)) {
  18842. state.lastStringValue += codePointToString(state.lastIntValue);
  18843. while (this.regexp_eatRegExpIdentifierPart(state)) {
  18844. state.lastStringValue += codePointToString(state.lastIntValue);
  18845. }
  18846. return true
  18847. }
  18848. return false
  18849. };
  18850. // RegExpIdentifierStart ::
  18851. // UnicodeIDStart
  18852. // `$`
  18853. // `_`
  18854. // `\` RegExpUnicodeEscapeSequence[+U]
  18855. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  18856. var start = state.pos;
  18857. var forceU = this.options.ecmaVersion >= 11;
  18858. var ch = state.current(forceU);
  18859. state.advance(forceU);
  18860. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18861. ch = state.lastIntValue;
  18862. }
  18863. if (isRegExpIdentifierStart(ch)) {
  18864. state.lastIntValue = ch;
  18865. return true
  18866. }
  18867. state.pos = start;
  18868. return false
  18869. };
  18870. function isRegExpIdentifierStart(ch) {
  18871. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  18872. }
  18873. // RegExpIdentifierPart ::
  18874. // UnicodeIDContinue
  18875. // `$`
  18876. // `_`
  18877. // `\` RegExpUnicodeEscapeSequence[+U]
  18878. // <ZWNJ>
  18879. // <ZWJ>
  18880. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  18881. var start = state.pos;
  18882. var forceU = this.options.ecmaVersion >= 11;
  18883. var ch = state.current(forceU);
  18884. state.advance(forceU);
  18885. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18886. ch = state.lastIntValue;
  18887. }
  18888. if (isRegExpIdentifierPart(ch)) {
  18889. state.lastIntValue = ch;
  18890. return true
  18891. }
  18892. state.pos = start;
  18893. return false
  18894. };
  18895. function isRegExpIdentifierPart(ch) {
  18896. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  18897. }
  18898. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  18899. pp$1.regexp_eatAtomEscape = function(state) {
  18900. if (
  18901. this.regexp_eatBackReference(state) ||
  18902. this.regexp_eatCharacterClassEscape(state) ||
  18903. this.regexp_eatCharacterEscape(state) ||
  18904. (state.switchN && this.regexp_eatKGroupName(state))
  18905. ) {
  18906. return true
  18907. }
  18908. if (state.switchU) {
  18909. // Make the same message as V8.
  18910. if (state.current() === 0x63 /* c */) {
  18911. state.raise("Invalid unicode escape");
  18912. }
  18913. state.raise("Invalid escape");
  18914. }
  18915. return false
  18916. };
  18917. pp$1.regexp_eatBackReference = function(state) {
  18918. var start = state.pos;
  18919. if (this.regexp_eatDecimalEscape(state)) {
  18920. var n = state.lastIntValue;
  18921. if (state.switchU) {
  18922. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  18923. if (n > state.maxBackReference) {
  18924. state.maxBackReference = n;
  18925. }
  18926. return true
  18927. }
  18928. if (n <= state.numCapturingParens) {
  18929. return true
  18930. }
  18931. state.pos = start;
  18932. }
  18933. return false
  18934. };
  18935. pp$1.regexp_eatKGroupName = function(state) {
  18936. if (state.eat(0x6B /* k */)) {
  18937. if (this.regexp_eatGroupName(state)) {
  18938. state.backReferenceNames.push(state.lastStringValue);
  18939. return true
  18940. }
  18941. state.raise("Invalid named reference");
  18942. }
  18943. return false
  18944. };
  18945. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  18946. pp$1.regexp_eatCharacterEscape = function(state) {
  18947. return (
  18948. this.regexp_eatControlEscape(state) ||
  18949. this.regexp_eatCControlLetter(state) ||
  18950. this.regexp_eatZero(state) ||
  18951. this.regexp_eatHexEscapeSequence(state) ||
  18952. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  18953. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  18954. this.regexp_eatIdentityEscape(state)
  18955. )
  18956. };
  18957. pp$1.regexp_eatCControlLetter = function(state) {
  18958. var start = state.pos;
  18959. if (state.eat(0x63 /* c */)) {
  18960. if (this.regexp_eatControlLetter(state)) {
  18961. return true
  18962. }
  18963. state.pos = start;
  18964. }
  18965. return false
  18966. };
  18967. pp$1.regexp_eatZero = function(state) {
  18968. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  18969. state.lastIntValue = 0;
  18970. state.advance();
  18971. return true
  18972. }
  18973. return false
  18974. };
  18975. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  18976. pp$1.regexp_eatControlEscape = function(state) {
  18977. var ch = state.current();
  18978. if (ch === 0x74 /* t */) {
  18979. state.lastIntValue = 0x09; /* \t */
  18980. state.advance();
  18981. return true
  18982. }
  18983. if (ch === 0x6E /* n */) {
  18984. state.lastIntValue = 0x0A; /* \n */
  18985. state.advance();
  18986. return true
  18987. }
  18988. if (ch === 0x76 /* v */) {
  18989. state.lastIntValue = 0x0B; /* \v */
  18990. state.advance();
  18991. return true
  18992. }
  18993. if (ch === 0x66 /* f */) {
  18994. state.lastIntValue = 0x0C; /* \f */
  18995. state.advance();
  18996. return true
  18997. }
  18998. if (ch === 0x72 /* r */) {
  18999. state.lastIntValue = 0x0D; /* \r */
  19000. state.advance();
  19001. return true
  19002. }
  19003. return false
  19004. };
  19005. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  19006. pp$1.regexp_eatControlLetter = function(state) {
  19007. var ch = state.current();
  19008. if (isControlLetter(ch)) {
  19009. state.lastIntValue = ch % 0x20;
  19010. state.advance();
  19011. return true
  19012. }
  19013. return false
  19014. };
  19015. function isControlLetter(ch) {
  19016. return (
  19017. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  19018. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  19019. )
  19020. }
  19021. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  19022. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  19023. if ( forceU === void 0 ) forceU = false;
  19024. var start = state.pos;
  19025. var switchU = forceU || state.switchU;
  19026. if (state.eat(0x75 /* u */)) {
  19027. if (this.regexp_eatFixedHexDigits(state, 4)) {
  19028. var lead = state.lastIntValue;
  19029. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  19030. var leadSurrogateEnd = state.pos;
  19031. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  19032. var trail = state.lastIntValue;
  19033. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  19034. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  19035. return true
  19036. }
  19037. }
  19038. state.pos = leadSurrogateEnd;
  19039. state.lastIntValue = lead;
  19040. }
  19041. return true
  19042. }
  19043. if (
  19044. switchU &&
  19045. state.eat(0x7B /* { */) &&
  19046. this.regexp_eatHexDigits(state) &&
  19047. state.eat(0x7D /* } */) &&
  19048. isValidUnicode(state.lastIntValue)
  19049. ) {
  19050. return true
  19051. }
  19052. if (switchU) {
  19053. state.raise("Invalid unicode escape");
  19054. }
  19055. state.pos = start;
  19056. }
  19057. return false
  19058. };
  19059. function isValidUnicode(ch) {
  19060. return ch >= 0 && ch <= 0x10FFFF
  19061. }
  19062. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  19063. pp$1.regexp_eatIdentityEscape = function(state) {
  19064. if (state.switchU) {
  19065. if (this.regexp_eatSyntaxCharacter(state)) {
  19066. return true
  19067. }
  19068. if (state.eat(0x2F /* / */)) {
  19069. state.lastIntValue = 0x2F; /* / */
  19070. return true
  19071. }
  19072. return false
  19073. }
  19074. var ch = state.current();
  19075. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  19076. state.lastIntValue = ch;
  19077. state.advance();
  19078. return true
  19079. }
  19080. return false
  19081. };
  19082. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  19083. pp$1.regexp_eatDecimalEscape = function(state) {
  19084. state.lastIntValue = 0;
  19085. var ch = state.current();
  19086. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  19087. do {
  19088. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19089. state.advance();
  19090. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  19091. return true
  19092. }
  19093. return false
  19094. };
  19095. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  19096. pp$1.regexp_eatCharacterClassEscape = function(state) {
  19097. var ch = state.current();
  19098. if (isCharacterClassEscape(ch)) {
  19099. state.lastIntValue = -1;
  19100. state.advance();
  19101. return true
  19102. }
  19103. if (
  19104. state.switchU &&
  19105. this.options.ecmaVersion >= 9 &&
  19106. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  19107. ) {
  19108. state.lastIntValue = -1;
  19109. state.advance();
  19110. if (
  19111. state.eat(0x7B /* { */) &&
  19112. this.regexp_eatUnicodePropertyValueExpression(state) &&
  19113. state.eat(0x7D /* } */)
  19114. ) {
  19115. return true
  19116. }
  19117. state.raise("Invalid property name");
  19118. }
  19119. return false
  19120. };
  19121. function isCharacterClassEscape(ch) {
  19122. return (
  19123. ch === 0x64 /* d */ ||
  19124. ch === 0x44 /* D */ ||
  19125. ch === 0x73 /* s */ ||
  19126. ch === 0x53 /* S */ ||
  19127. ch === 0x77 /* w */ ||
  19128. ch === 0x57 /* W */
  19129. )
  19130. }
  19131. // UnicodePropertyValueExpression ::
  19132. // UnicodePropertyName `=` UnicodePropertyValue
  19133. // LoneUnicodePropertyNameOrValue
  19134. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  19135. var start = state.pos;
  19136. // UnicodePropertyName `=` UnicodePropertyValue
  19137. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  19138. var name = state.lastStringValue;
  19139. if (this.regexp_eatUnicodePropertyValue(state)) {
  19140. var value = state.lastStringValue;
  19141. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  19142. return true
  19143. }
  19144. }
  19145. state.pos = start;
  19146. // LoneUnicodePropertyNameOrValue
  19147. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  19148. var nameOrValue = state.lastStringValue;
  19149. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  19150. return true
  19151. }
  19152. return false
  19153. };
  19154. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  19155. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  19156. { state.raise("Invalid property name"); }
  19157. if (!state.unicodeProperties.nonBinary[name].test(value))
  19158. { state.raise("Invalid property value"); }
  19159. };
  19160. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  19161. if (!state.unicodeProperties.binary.test(nameOrValue))
  19162. { state.raise("Invalid property name"); }
  19163. };
  19164. // UnicodePropertyName ::
  19165. // UnicodePropertyNameCharacters
  19166. pp$1.regexp_eatUnicodePropertyName = function(state) {
  19167. var ch = 0;
  19168. state.lastStringValue = "";
  19169. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  19170. state.lastStringValue += codePointToString(ch);
  19171. state.advance();
  19172. }
  19173. return state.lastStringValue !== ""
  19174. };
  19175. function isUnicodePropertyNameCharacter(ch) {
  19176. return isControlLetter(ch) || ch === 0x5F /* _ */
  19177. }
  19178. // UnicodePropertyValue ::
  19179. // UnicodePropertyValueCharacters
  19180. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  19181. var ch = 0;
  19182. state.lastStringValue = "";
  19183. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  19184. state.lastStringValue += codePointToString(ch);
  19185. state.advance();
  19186. }
  19187. return state.lastStringValue !== ""
  19188. };
  19189. function isUnicodePropertyValueCharacter(ch) {
  19190. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  19191. }
  19192. // LoneUnicodePropertyNameOrValue ::
  19193. // UnicodePropertyValueCharacters
  19194. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  19195. return this.regexp_eatUnicodePropertyValue(state)
  19196. };
  19197. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  19198. pp$1.regexp_eatCharacterClass = function(state) {
  19199. if (state.eat(0x5B /* [ */)) {
  19200. state.eat(0x5E /* ^ */);
  19201. this.regexp_classRanges(state);
  19202. if (state.eat(0x5D /* ] */)) {
  19203. return true
  19204. }
  19205. // Unreachable since it threw "unterminated regular expression" error before.
  19206. state.raise("Unterminated character class");
  19207. }
  19208. return false
  19209. };
  19210. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  19211. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  19212. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  19213. pp$1.regexp_classRanges = function(state) {
  19214. while (this.regexp_eatClassAtom(state)) {
  19215. var left = state.lastIntValue;
  19216. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  19217. var right = state.lastIntValue;
  19218. if (state.switchU && (left === -1 || right === -1)) {
  19219. state.raise("Invalid character class");
  19220. }
  19221. if (left !== -1 && right !== -1 && left > right) {
  19222. state.raise("Range out of order in character class");
  19223. }
  19224. }
  19225. }
  19226. };
  19227. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  19228. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  19229. pp$1.regexp_eatClassAtom = function(state) {
  19230. var start = state.pos;
  19231. if (state.eat(0x5C /* \ */)) {
  19232. if (this.regexp_eatClassEscape(state)) {
  19233. return true
  19234. }
  19235. if (state.switchU) {
  19236. // Make the same message as V8.
  19237. var ch$1 = state.current();
  19238. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  19239. state.raise("Invalid class escape");
  19240. }
  19241. state.raise("Invalid escape");
  19242. }
  19243. state.pos = start;
  19244. }
  19245. var ch = state.current();
  19246. if (ch !== 0x5D /* ] */) {
  19247. state.lastIntValue = ch;
  19248. state.advance();
  19249. return true
  19250. }
  19251. return false
  19252. };
  19253. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  19254. pp$1.regexp_eatClassEscape = function(state) {
  19255. var start = state.pos;
  19256. if (state.eat(0x62 /* b */)) {
  19257. state.lastIntValue = 0x08; /* <BS> */
  19258. return true
  19259. }
  19260. if (state.switchU && state.eat(0x2D /* - */)) {
  19261. state.lastIntValue = 0x2D; /* - */
  19262. return true
  19263. }
  19264. if (!state.switchU && state.eat(0x63 /* c */)) {
  19265. if (this.regexp_eatClassControlLetter(state)) {
  19266. return true
  19267. }
  19268. state.pos = start;
  19269. }
  19270. return (
  19271. this.regexp_eatCharacterClassEscape(state) ||
  19272. this.regexp_eatCharacterEscape(state)
  19273. )
  19274. };
  19275. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  19276. pp$1.regexp_eatClassControlLetter = function(state) {
  19277. var ch = state.current();
  19278. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  19279. state.lastIntValue = ch % 0x20;
  19280. state.advance();
  19281. return true
  19282. }
  19283. return false
  19284. };
  19285. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19286. pp$1.regexp_eatHexEscapeSequence = function(state) {
  19287. var start = state.pos;
  19288. if (state.eat(0x78 /* x */)) {
  19289. if (this.regexp_eatFixedHexDigits(state, 2)) {
  19290. return true
  19291. }
  19292. if (state.switchU) {
  19293. state.raise("Invalid escape");
  19294. }
  19295. state.pos = start;
  19296. }
  19297. return false
  19298. };
  19299. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  19300. pp$1.regexp_eatDecimalDigits = function(state) {
  19301. var start = state.pos;
  19302. var ch = 0;
  19303. state.lastIntValue = 0;
  19304. while (isDecimalDigit(ch = state.current())) {
  19305. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19306. state.advance();
  19307. }
  19308. return state.pos !== start
  19309. };
  19310. function isDecimalDigit(ch) {
  19311. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  19312. }
  19313. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  19314. pp$1.regexp_eatHexDigits = function(state) {
  19315. var start = state.pos;
  19316. var ch = 0;
  19317. state.lastIntValue = 0;
  19318. while (isHexDigit(ch = state.current())) {
  19319. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19320. state.advance();
  19321. }
  19322. return state.pos !== start
  19323. };
  19324. function isHexDigit(ch) {
  19325. return (
  19326. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  19327. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  19328. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  19329. )
  19330. }
  19331. function hexToInt(ch) {
  19332. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  19333. return 10 + (ch - 0x41 /* A */)
  19334. }
  19335. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  19336. return 10 + (ch - 0x61 /* a */)
  19337. }
  19338. return ch - 0x30 /* 0 */
  19339. }
  19340. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  19341. // Allows only 0-377(octal) i.e. 0-255(decimal).
  19342. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  19343. if (this.regexp_eatOctalDigit(state)) {
  19344. var n1 = state.lastIntValue;
  19345. if (this.regexp_eatOctalDigit(state)) {
  19346. var n2 = state.lastIntValue;
  19347. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  19348. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  19349. } else {
  19350. state.lastIntValue = n1 * 8 + n2;
  19351. }
  19352. } else {
  19353. state.lastIntValue = n1;
  19354. }
  19355. return true
  19356. }
  19357. return false
  19358. };
  19359. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  19360. pp$1.regexp_eatOctalDigit = function(state) {
  19361. var ch = state.current();
  19362. if (isOctalDigit(ch)) {
  19363. state.lastIntValue = ch - 0x30; /* 0 */
  19364. state.advance();
  19365. return true
  19366. }
  19367. state.lastIntValue = 0;
  19368. return false
  19369. };
  19370. function isOctalDigit(ch) {
  19371. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  19372. }
  19373. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  19374. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  19375. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19376. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  19377. var start = state.pos;
  19378. state.lastIntValue = 0;
  19379. for (var i = 0; i < length; ++i) {
  19380. var ch = state.current();
  19381. if (!isHexDigit(ch)) {
  19382. state.pos = start;
  19383. return false
  19384. }
  19385. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19386. state.advance();
  19387. }
  19388. return true
  19389. };
  19390. // Object type used to represent tokens. Note that normally, tokens
  19391. // simply exist as properties on the parser object. This is only
  19392. // used for the onToken callback and the external tokenizer.
  19393. var Token = function Token(p) {
  19394. this.type = p.type;
  19395. this.value = p.value;
  19396. this.start = p.start;
  19397. this.end = p.end;
  19398. if (p.options.locations)
  19399. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  19400. if (p.options.ranges)
  19401. { this.range = [p.start, p.end]; }
  19402. };
  19403. // ## Tokenizer
  19404. var pp = Parser.prototype;
  19405. // Move to the next token
  19406. pp.next = function(ignoreEscapeSequenceInKeyword) {
  19407. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  19408. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  19409. if (this.options.onToken)
  19410. { this.options.onToken(new Token(this)); }
  19411. this.lastTokEnd = this.end;
  19412. this.lastTokStart = this.start;
  19413. this.lastTokEndLoc = this.endLoc;
  19414. this.lastTokStartLoc = this.startLoc;
  19415. this.nextToken();
  19416. };
  19417. pp.getToken = function() {
  19418. this.next();
  19419. return new Token(this)
  19420. };
  19421. // If we're in an ES6 environment, make parsers iterable
  19422. if (typeof Symbol !== "undefined")
  19423. { pp[Symbol.iterator] = function() {
  19424. var this$1$1 = this;
  19425. return {
  19426. next: function () {
  19427. var token = this$1$1.getToken();
  19428. return {
  19429. done: token.type === types$1.eof,
  19430. value: token
  19431. }
  19432. }
  19433. }
  19434. }; }
  19435. // Toggle strict mode. Re-reads the next number or string to please
  19436. // pedantic tests (`"use strict"; 010;` should fail).
  19437. // Read a single token, updating the parser object's token-related
  19438. // properties.
  19439. pp.nextToken = function() {
  19440. var curContext = this.curContext();
  19441. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  19442. this.start = this.pos;
  19443. if (this.options.locations) { this.startLoc = this.curPosition(); }
  19444. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  19445. if (curContext.override) { return curContext.override(this) }
  19446. else { this.readToken(this.fullCharCodeAtPos()); }
  19447. };
  19448. pp.readToken = function(code) {
  19449. // Identifier or keyword. '\uXXXX' sequences are allowed in
  19450. // identifiers, so '\' also dispatches to that.
  19451. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  19452. { return this.readWord() }
  19453. return this.getTokenFromCode(code)
  19454. };
  19455. pp.fullCharCodeAtPos = function() {
  19456. var code = this.input.charCodeAt(this.pos);
  19457. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  19458. var next = this.input.charCodeAt(this.pos + 1);
  19459. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  19460. };
  19461. pp.skipBlockComment = function() {
  19462. var startLoc = this.options.onComment && this.curPosition();
  19463. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  19464. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  19465. this.pos = end + 2;
  19466. if (this.options.locations) {
  19467. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  19468. ++this.curLine;
  19469. pos = this.lineStart = nextBreak;
  19470. }
  19471. }
  19472. if (this.options.onComment)
  19473. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  19474. startLoc, this.curPosition()); }
  19475. };
  19476. pp.skipLineComment = function(startSkip) {
  19477. var start = this.pos;
  19478. var startLoc = this.options.onComment && this.curPosition();
  19479. var ch = this.input.charCodeAt(this.pos += startSkip);
  19480. while (this.pos < this.input.length && !isNewLine(ch)) {
  19481. ch = this.input.charCodeAt(++this.pos);
  19482. }
  19483. if (this.options.onComment)
  19484. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  19485. startLoc, this.curPosition()); }
  19486. };
  19487. // Called at the start of the parse and after every token. Skips
  19488. // whitespace and comments, and.
  19489. pp.skipSpace = function() {
  19490. loop: while (this.pos < this.input.length) {
  19491. var ch = this.input.charCodeAt(this.pos);
  19492. switch (ch) {
  19493. case 32: case 160: // ' '
  19494. ++this.pos;
  19495. break
  19496. case 13:
  19497. if (this.input.charCodeAt(this.pos + 1) === 10) {
  19498. ++this.pos;
  19499. }
  19500. case 10: case 8232: case 8233:
  19501. ++this.pos;
  19502. if (this.options.locations) {
  19503. ++this.curLine;
  19504. this.lineStart = this.pos;
  19505. }
  19506. break
  19507. case 47: // '/'
  19508. switch (this.input.charCodeAt(this.pos + 1)) {
  19509. case 42: // '*'
  19510. this.skipBlockComment();
  19511. break
  19512. case 47:
  19513. this.skipLineComment(2);
  19514. break
  19515. default:
  19516. break loop
  19517. }
  19518. break
  19519. default:
  19520. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  19521. ++this.pos;
  19522. } else {
  19523. break loop
  19524. }
  19525. }
  19526. }
  19527. };
  19528. // Called at the end of every token. Sets `end`, `val`, and
  19529. // maintains `context` and `exprAllowed`, and skips the space after
  19530. // the token, so that the next one's `start` will point at the
  19531. // right position.
  19532. pp.finishToken = function(type, val) {
  19533. this.end = this.pos;
  19534. if (this.options.locations) { this.endLoc = this.curPosition(); }
  19535. var prevType = this.type;
  19536. this.type = type;
  19537. this.value = val;
  19538. this.updateContext(prevType);
  19539. };
  19540. // ### Token reading
  19541. // This is the function that is called to fetch the next token. It
  19542. // is somewhat obscure, because it works in character codes rather
  19543. // than characters, and because operator parsing has been inlined
  19544. // into it.
  19545. //
  19546. // All in the name of speed.
  19547. //
  19548. pp.readToken_dot = function() {
  19549. var next = this.input.charCodeAt(this.pos + 1);
  19550. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  19551. var next2 = this.input.charCodeAt(this.pos + 2);
  19552. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  19553. this.pos += 3;
  19554. return this.finishToken(types$1.ellipsis)
  19555. } else {
  19556. ++this.pos;
  19557. return this.finishToken(types$1.dot)
  19558. }
  19559. };
  19560. pp.readToken_slash = function() { // '/'
  19561. var next = this.input.charCodeAt(this.pos + 1);
  19562. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  19563. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19564. return this.finishOp(types$1.slash, 1)
  19565. };
  19566. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  19567. var next = this.input.charCodeAt(this.pos + 1);
  19568. var size = 1;
  19569. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  19570. // exponentiation operator ** and **=
  19571. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  19572. ++size;
  19573. tokentype = types$1.starstar;
  19574. next = this.input.charCodeAt(this.pos + 2);
  19575. }
  19576. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  19577. return this.finishOp(tokentype, size)
  19578. };
  19579. pp.readToken_pipe_amp = function(code) { // '|&'
  19580. var next = this.input.charCodeAt(this.pos + 1);
  19581. if (next === code) {
  19582. if (this.options.ecmaVersion >= 12) {
  19583. var next2 = this.input.charCodeAt(this.pos + 2);
  19584. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  19585. }
  19586. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  19587. }
  19588. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19589. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  19590. };
  19591. pp.readToken_caret = function() { // '^'
  19592. var next = this.input.charCodeAt(this.pos + 1);
  19593. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19594. return this.finishOp(types$1.bitwiseXOR, 1)
  19595. };
  19596. pp.readToken_plus_min = function(code) { // '+-'
  19597. var next = this.input.charCodeAt(this.pos + 1);
  19598. if (next === code) {
  19599. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  19600. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  19601. // A `-->` line comment
  19602. this.skipLineComment(3);
  19603. this.skipSpace();
  19604. return this.nextToken()
  19605. }
  19606. return this.finishOp(types$1.incDec, 2)
  19607. }
  19608. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19609. return this.finishOp(types$1.plusMin, 1)
  19610. };
  19611. pp.readToken_lt_gt = function(code) { // '<>'
  19612. var next = this.input.charCodeAt(this.pos + 1);
  19613. var size = 1;
  19614. if (next === code) {
  19615. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  19616. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  19617. return this.finishOp(types$1.bitShift, size)
  19618. }
  19619. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  19620. this.input.charCodeAt(this.pos + 3) === 45) {
  19621. // `<!--`, an XML-style comment that should be interpreted as a line comment
  19622. this.skipLineComment(4);
  19623. this.skipSpace();
  19624. return this.nextToken()
  19625. }
  19626. if (next === 61) { size = 2; }
  19627. return this.finishOp(types$1.relational, size)
  19628. };
  19629. pp.readToken_eq_excl = function(code) { // '=!'
  19630. var next = this.input.charCodeAt(this.pos + 1);
  19631. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  19632. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  19633. this.pos += 2;
  19634. return this.finishToken(types$1.arrow)
  19635. }
  19636. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  19637. };
  19638. pp.readToken_question = function() { // '?'
  19639. var ecmaVersion = this.options.ecmaVersion;
  19640. if (ecmaVersion >= 11) {
  19641. var next = this.input.charCodeAt(this.pos + 1);
  19642. if (next === 46) {
  19643. var next2 = this.input.charCodeAt(this.pos + 2);
  19644. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  19645. }
  19646. if (next === 63) {
  19647. if (ecmaVersion >= 12) {
  19648. var next2$1 = this.input.charCodeAt(this.pos + 2);
  19649. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  19650. }
  19651. return this.finishOp(types$1.coalesce, 2)
  19652. }
  19653. }
  19654. return this.finishOp(types$1.question, 1)
  19655. };
  19656. pp.readToken_numberSign = function() { // '#'
  19657. var ecmaVersion = this.options.ecmaVersion;
  19658. var code = 35; // '#'
  19659. if (ecmaVersion >= 13) {
  19660. ++this.pos;
  19661. code = this.fullCharCodeAtPos();
  19662. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  19663. return this.finishToken(types$1.privateId, this.readWord1())
  19664. }
  19665. }
  19666. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19667. };
  19668. pp.getTokenFromCode = function(code) {
  19669. switch (code) {
  19670. // The interpretation of a dot depends on whether it is followed
  19671. // by a digit or another two dots.
  19672. case 46: // '.'
  19673. return this.readToken_dot()
  19674. // Punctuation tokens.
  19675. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  19676. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  19677. case 59: ++this.pos; return this.finishToken(types$1.semi)
  19678. case 44: ++this.pos; return this.finishToken(types$1.comma)
  19679. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  19680. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  19681. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  19682. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  19683. case 58: ++this.pos; return this.finishToken(types$1.colon)
  19684. case 96: // '`'
  19685. if (this.options.ecmaVersion < 6) { break }
  19686. ++this.pos;
  19687. return this.finishToken(types$1.backQuote)
  19688. case 48: // '0'
  19689. var next = this.input.charCodeAt(this.pos + 1);
  19690. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  19691. if (this.options.ecmaVersion >= 6) {
  19692. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  19693. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  19694. }
  19695. // Anything else beginning with a digit is an integer, octal
  19696. // number, or float.
  19697. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  19698. return this.readNumber(false)
  19699. // Quotes produce strings.
  19700. case 34: case 39: // '"', "'"
  19701. return this.readString(code)
  19702. // Operators are parsed inline in tiny state machines. '=' (61) is
  19703. // often referred to. `finishOp` simply skips the amount of
  19704. // characters it is given as second argument, and returns a token
  19705. // of the type given by its first argument.
  19706. case 47: // '/'
  19707. return this.readToken_slash()
  19708. case 37: case 42: // '%*'
  19709. return this.readToken_mult_modulo_exp(code)
  19710. case 124: case 38: // '|&'
  19711. return this.readToken_pipe_amp(code)
  19712. case 94: // '^'
  19713. return this.readToken_caret()
  19714. case 43: case 45: // '+-'
  19715. return this.readToken_plus_min(code)
  19716. case 60: case 62: // '<>'
  19717. return this.readToken_lt_gt(code)
  19718. case 61: case 33: // '=!'
  19719. return this.readToken_eq_excl(code)
  19720. case 63: // '?'
  19721. return this.readToken_question()
  19722. case 126: // '~'
  19723. return this.finishOp(types$1.prefix, 1)
  19724. case 35: // '#'
  19725. return this.readToken_numberSign()
  19726. }
  19727. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19728. };
  19729. pp.finishOp = function(type, size) {
  19730. var str = this.input.slice(this.pos, this.pos + size);
  19731. this.pos += size;
  19732. return this.finishToken(type, str)
  19733. };
  19734. pp.readRegexp = function() {
  19735. var escaped, inClass, start = this.pos;
  19736. for (;;) {
  19737. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  19738. var ch = this.input.charAt(this.pos);
  19739. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  19740. if (!escaped) {
  19741. if (ch === "[") { inClass = true; }
  19742. else if (ch === "]" && inClass) { inClass = false; }
  19743. else if (ch === "/" && !inClass) { break }
  19744. escaped = ch === "\\";
  19745. } else { escaped = false; }
  19746. ++this.pos;
  19747. }
  19748. var pattern = this.input.slice(start, this.pos);
  19749. ++this.pos;
  19750. var flagsStart = this.pos;
  19751. var flags = this.readWord1();
  19752. if (this.containsEsc) { this.unexpected(flagsStart); }
  19753. // Validate pattern
  19754. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  19755. state.reset(start, pattern, flags);
  19756. this.validateRegExpFlags(state);
  19757. this.validateRegExpPattern(state);
  19758. // Create Literal#value property value.
  19759. var value = null;
  19760. try {
  19761. value = new RegExp(pattern, flags);
  19762. } catch (e) {
  19763. // ESTree requires null if it failed to instantiate RegExp object.
  19764. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  19765. }
  19766. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  19767. };
  19768. // Read an integer in the given radix. Return null if zero digits
  19769. // were read, the integer value otherwise. When `len` is given, this
  19770. // will return `null` unless the integer has exactly `len` digits.
  19771. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  19772. // `len` is used for character escape sequences. In that case, disallow separators.
  19773. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  19774. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  19775. // and isn't fraction part nor exponent part. In that case, if the first digit
  19776. // is zero then disallow separators.
  19777. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  19778. var start = this.pos, total = 0, lastCode = 0;
  19779. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  19780. var code = this.input.charCodeAt(this.pos), val = (void 0);
  19781. if (allowSeparators && code === 95) {
  19782. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  19783. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  19784. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  19785. lastCode = code;
  19786. continue
  19787. }
  19788. if (code >= 97) { val = code - 97 + 10; } // a
  19789. else if (code >= 65) { val = code - 65 + 10; } // A
  19790. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  19791. else { val = Infinity; }
  19792. if (val >= radix) { break }
  19793. lastCode = code;
  19794. total = total * radix + val;
  19795. }
  19796. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  19797. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  19798. return total
  19799. };
  19800. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  19801. if (isLegacyOctalNumericLiteral) {
  19802. return parseInt(str, 8)
  19803. }
  19804. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  19805. return parseFloat(str.replace(/_/g, ""))
  19806. }
  19807. function stringToBigInt(str) {
  19808. if (typeof BigInt !== "function") {
  19809. return null
  19810. }
  19811. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  19812. return BigInt(str.replace(/_/g, ""))
  19813. }
  19814. pp.readRadixNumber = function(radix) {
  19815. var start = this.pos;
  19816. this.pos += 2; // 0x
  19817. var val = this.readInt(radix);
  19818. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  19819. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  19820. val = stringToBigInt(this.input.slice(start, this.pos));
  19821. ++this.pos;
  19822. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19823. return this.finishToken(types$1.num, val)
  19824. };
  19825. // Read an integer, octal integer, or floating-point number.
  19826. pp.readNumber = function(startsWithDot) {
  19827. var start = this.pos;
  19828. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  19829. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  19830. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  19831. var next = this.input.charCodeAt(this.pos);
  19832. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  19833. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  19834. ++this.pos;
  19835. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19836. return this.finishToken(types$1.num, val$1)
  19837. }
  19838. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  19839. if (next === 46 && !octal) { // '.'
  19840. ++this.pos;
  19841. this.readInt(10);
  19842. next = this.input.charCodeAt(this.pos);
  19843. }
  19844. if ((next === 69 || next === 101) && !octal) { // 'eE'
  19845. next = this.input.charCodeAt(++this.pos);
  19846. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  19847. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  19848. }
  19849. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19850. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  19851. return this.finishToken(types$1.num, val)
  19852. };
  19853. // Read a string value, interpreting backslash-escapes.
  19854. pp.readCodePoint = function() {
  19855. var ch = this.input.charCodeAt(this.pos), code;
  19856. if (ch === 123) { // '{'
  19857. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  19858. var codePos = ++this.pos;
  19859. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  19860. ++this.pos;
  19861. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  19862. } else {
  19863. code = this.readHexChar(4);
  19864. }
  19865. return code
  19866. };
  19867. pp.readString = function(quote) {
  19868. var out = "", chunkStart = ++this.pos;
  19869. for (;;) {
  19870. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  19871. var ch = this.input.charCodeAt(this.pos);
  19872. if (ch === quote) { break }
  19873. if (ch === 92) { // '\'
  19874. out += this.input.slice(chunkStart, this.pos);
  19875. out += this.readEscapedChar(false);
  19876. chunkStart = this.pos;
  19877. } else if (ch === 0x2028 || ch === 0x2029) {
  19878. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  19879. ++this.pos;
  19880. if (this.options.locations) {
  19881. this.curLine++;
  19882. this.lineStart = this.pos;
  19883. }
  19884. } else {
  19885. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  19886. ++this.pos;
  19887. }
  19888. }
  19889. out += this.input.slice(chunkStart, this.pos++);
  19890. return this.finishToken(types$1.string, out)
  19891. };
  19892. // Reads template string tokens.
  19893. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  19894. pp.tryReadTemplateToken = function() {
  19895. this.inTemplateElement = true;
  19896. try {
  19897. this.readTmplToken();
  19898. } catch (err) {
  19899. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  19900. this.readInvalidTemplateToken();
  19901. } else {
  19902. throw err
  19903. }
  19904. }
  19905. this.inTemplateElement = false;
  19906. };
  19907. pp.invalidStringToken = function(position, message) {
  19908. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  19909. throw INVALID_TEMPLATE_ESCAPE_ERROR
  19910. } else {
  19911. this.raise(position, message);
  19912. }
  19913. };
  19914. pp.readTmplToken = function() {
  19915. var out = "", chunkStart = this.pos;
  19916. for (;;) {
  19917. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  19918. var ch = this.input.charCodeAt(this.pos);
  19919. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  19920. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  19921. if (ch === 36) {
  19922. this.pos += 2;
  19923. return this.finishToken(types$1.dollarBraceL)
  19924. } else {
  19925. ++this.pos;
  19926. return this.finishToken(types$1.backQuote)
  19927. }
  19928. }
  19929. out += this.input.slice(chunkStart, this.pos);
  19930. return this.finishToken(types$1.template, out)
  19931. }
  19932. if (ch === 92) { // '\'
  19933. out += this.input.slice(chunkStart, this.pos);
  19934. out += this.readEscapedChar(true);
  19935. chunkStart = this.pos;
  19936. } else if (isNewLine(ch)) {
  19937. out += this.input.slice(chunkStart, this.pos);
  19938. ++this.pos;
  19939. switch (ch) {
  19940. case 13:
  19941. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  19942. case 10:
  19943. out += "\n";
  19944. break
  19945. default:
  19946. out += String.fromCharCode(ch);
  19947. break
  19948. }
  19949. if (this.options.locations) {
  19950. ++this.curLine;
  19951. this.lineStart = this.pos;
  19952. }
  19953. chunkStart = this.pos;
  19954. } else {
  19955. ++this.pos;
  19956. }
  19957. }
  19958. };
  19959. // Reads a template token to search for the end, without validating any escape sequences
  19960. pp.readInvalidTemplateToken = function() {
  19961. for (; this.pos < this.input.length; this.pos++) {
  19962. switch (this.input[this.pos]) {
  19963. case "\\":
  19964. ++this.pos;
  19965. break
  19966. case "$":
  19967. if (this.input[this.pos + 1] !== "{") {
  19968. break
  19969. }
  19970. // falls through
  19971. case "`":
  19972. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  19973. // no default
  19974. }
  19975. }
  19976. this.raise(this.start, "Unterminated template");
  19977. };
  19978. // Used to read escaped characters
  19979. pp.readEscapedChar = function(inTemplate) {
  19980. var ch = this.input.charCodeAt(++this.pos);
  19981. ++this.pos;
  19982. switch (ch) {
  19983. case 110: return "\n" // 'n' -> '\n'
  19984. case 114: return "\r" // 'r' -> '\r'
  19985. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  19986. case 117: return codePointToString(this.readCodePoint()) // 'u'
  19987. case 116: return "\t" // 't' -> '\t'
  19988. case 98: return "\b" // 'b' -> '\b'
  19989. case 118: return "\u000b" // 'v' -> '\u000b'
  19990. case 102: return "\f" // 'f' -> '\f'
  19991. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  19992. case 10: // ' \n'
  19993. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  19994. return ""
  19995. case 56:
  19996. case 57:
  19997. if (this.strict) {
  19998. this.invalidStringToken(
  19999. this.pos - 1,
  20000. "Invalid escape sequence"
  20001. );
  20002. }
  20003. if (inTemplate) {
  20004. var codePos = this.pos - 1;
  20005. this.invalidStringToken(
  20006. codePos,
  20007. "Invalid escape sequence in template string"
  20008. );
  20009. return null
  20010. }
  20011. default:
  20012. if (ch >= 48 && ch <= 55) {
  20013. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  20014. var octal = parseInt(octalStr, 8);
  20015. if (octal > 255) {
  20016. octalStr = octalStr.slice(0, -1);
  20017. octal = parseInt(octalStr, 8);
  20018. }
  20019. this.pos += octalStr.length - 1;
  20020. ch = this.input.charCodeAt(this.pos);
  20021. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  20022. this.invalidStringToken(
  20023. this.pos - 1 - octalStr.length,
  20024. inTemplate
  20025. ? "Octal literal in template string"
  20026. : "Octal literal in strict mode"
  20027. );
  20028. }
  20029. return String.fromCharCode(octal)
  20030. }
  20031. if (isNewLine(ch)) {
  20032. // Unicode new line characters after \ get removed from output in both
  20033. // template literals and strings
  20034. return ""
  20035. }
  20036. return String.fromCharCode(ch)
  20037. }
  20038. };
  20039. // Used to read character escape sequences ('\x', '\u', '\U').
  20040. pp.readHexChar = function(len) {
  20041. var codePos = this.pos;
  20042. var n = this.readInt(16, len);
  20043. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  20044. return n
  20045. };
  20046. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  20047. // to whether the word contained a '\u' escape.
  20048. //
  20049. // Incrementally adds only escaped chars, adding other chunks as-is
  20050. // as a micro-optimization.
  20051. pp.readWord1 = function() {
  20052. this.containsEsc = false;
  20053. var word = "", first = true, chunkStart = this.pos;
  20054. var astral = this.options.ecmaVersion >= 6;
  20055. while (this.pos < this.input.length) {
  20056. var ch = this.fullCharCodeAtPos();
  20057. if (isIdentifierChar(ch, astral)) {
  20058. this.pos += ch <= 0xffff ? 1 : 2;
  20059. } else if (ch === 92) { // "\"
  20060. this.containsEsc = true;
  20061. word += this.input.slice(chunkStart, this.pos);
  20062. var escStart = this.pos;
  20063. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  20064. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  20065. ++this.pos;
  20066. var esc = this.readCodePoint();
  20067. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  20068. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  20069. word += codePointToString(esc);
  20070. chunkStart = this.pos;
  20071. } else {
  20072. break
  20073. }
  20074. first = false;
  20075. }
  20076. return word + this.input.slice(chunkStart, this.pos)
  20077. };
  20078. // Read an identifier or keyword token. Will check for reserved
  20079. // words when necessary.
  20080. pp.readWord = function() {
  20081. var word = this.readWord1();
  20082. var type = types$1.name;
  20083. if (this.keywords.test(word)) {
  20084. type = keywords[word];
  20085. }
  20086. return this.finishToken(type, word)
  20087. };
  20088. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  20089. var version = "8.7.1";
  20090. Parser.acorn = {
  20091. Parser: Parser,
  20092. version: version,
  20093. defaultOptions: defaultOptions,
  20094. Position: Position,
  20095. SourceLocation: SourceLocation,
  20096. getLineInfo: getLineInfo,
  20097. Node: Node,
  20098. TokenType: TokenType,
  20099. tokTypes: types$1,
  20100. keywordTypes: keywords,
  20101. TokContext: TokContext,
  20102. tokContexts: types,
  20103. isIdentifierChar: isIdentifierChar,
  20104. isIdentifierStart: isIdentifierStart,
  20105. Token: Token,
  20106. isNewLine: isNewLine,
  20107. lineBreak: lineBreak,
  20108. lineBreakG: lineBreakG,
  20109. nonASCIIwhitespace: nonASCIIwhitespace
  20110. };
  20111. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20112. let skipped = null;
  20113. let replaceContext = null;
  20114. if (skip) {
  20115. skipped = new Set();
  20116. for (const skippedCall of skip) {
  20117. if (source === skippedCall.source && importer === skippedCall.importer) {
  20118. skipped.add(skippedCall.plugin);
  20119. }
  20120. }
  20121. replaceContext = (pluginContext, plugin) => ({
  20122. ...pluginContext,
  20123. resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
  20124. return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20125. }
  20126. });
  20127. }
  20128. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
  20129. }
  20130. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20131. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
  20132. if (pluginResult != null)
  20133. return pluginResult;
  20134. // external modules (non-entry modules that start with neither '.' or '/')
  20135. // are skipped at this stage.
  20136. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  20137. return null;
  20138. // `resolve` processes paths from right to left, prepending them until an
  20139. // absolute path is created. Absolute importees therefore shortcircuit the
  20140. // resolve call and require no special handing on our part.
  20141. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20142. return addJsExtensionIfNecessary(importer ? require$$0.resolve(require$$0.dirname(importer), source) : require$$0.resolve(source), preserveSymlinks);
  20143. }
  20144. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  20145. var _a, _b;
  20146. 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)));
  20147. }
  20148. async function findFile(file, preserveSymlinks) {
  20149. try {
  20150. const stats = await require$$0$1.promises.lstat(file);
  20151. if (!preserveSymlinks && stats.isSymbolicLink())
  20152. return await findFile(await require$$0$1.promises.realpath(file), preserveSymlinks);
  20153. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20154. // check case
  20155. const name = require$$0.basename(file);
  20156. const files = await require$$0$1.promises.readdir(require$$0.dirname(file));
  20157. if (files.includes(name))
  20158. return file;
  20159. }
  20160. }
  20161. catch (_a) {
  20162. // suppress
  20163. }
  20164. }
  20165. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  20166. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  20167. function throwPluginError(err, plugin, { hook, id } = {}) {
  20168. if (typeof err === 'string')
  20169. err = { message: err };
  20170. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  20171. err.pluginCode = err.code;
  20172. }
  20173. err.code = Errors.PLUGIN_ERROR;
  20174. err.plugin = plugin;
  20175. if (hook) {
  20176. err.hook = hook;
  20177. }
  20178. if (id) {
  20179. err.id = id;
  20180. }
  20181. return error(err);
  20182. }
  20183. const deprecatedHooks = [
  20184. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  20185. ];
  20186. function warnDeprecatedHooks(plugins, options) {
  20187. for (const { active, deprecated, replacement } of deprecatedHooks) {
  20188. for (const plugin of plugins) {
  20189. if (deprecated in plugin) {
  20190. warnDeprecation({
  20191. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  20192. plugin: plugin.name
  20193. }, active, options);
  20194. }
  20195. }
  20196. }
  20197. }
  20198. function createPluginCache(cache) {
  20199. return {
  20200. delete(id) {
  20201. return delete cache[id];
  20202. },
  20203. get(id) {
  20204. const item = cache[id];
  20205. if (!item)
  20206. return undefined;
  20207. item[0] = 0;
  20208. return item[1];
  20209. },
  20210. has(id) {
  20211. const item = cache[id];
  20212. if (!item)
  20213. return false;
  20214. item[0] = 0;
  20215. return true;
  20216. },
  20217. set(id, value) {
  20218. cache[id] = [0, value];
  20219. }
  20220. };
  20221. }
  20222. function getTrackedPluginCache(pluginCache, onUse) {
  20223. return {
  20224. delete(id) {
  20225. onUse();
  20226. return pluginCache.delete(id);
  20227. },
  20228. get(id) {
  20229. onUse();
  20230. return pluginCache.get(id);
  20231. },
  20232. has(id) {
  20233. onUse();
  20234. return pluginCache.has(id);
  20235. },
  20236. set(id, value) {
  20237. onUse();
  20238. return pluginCache.set(id, value);
  20239. }
  20240. };
  20241. }
  20242. const NO_CACHE = {
  20243. delete() {
  20244. return false;
  20245. },
  20246. get() {
  20247. return undefined;
  20248. },
  20249. has() {
  20250. return false;
  20251. },
  20252. set() { }
  20253. };
  20254. function uncacheablePluginError(pluginName) {
  20255. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20256. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  20257. return error({
  20258. code: 'ANONYMOUS_PLUGIN_CACHE',
  20259. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  20260. });
  20261. }
  20262. return error({
  20263. code: 'DUPLICATE_PLUGIN_NAME',
  20264. 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).`
  20265. });
  20266. }
  20267. function getCacheForUncacheablePlugin(pluginName) {
  20268. return {
  20269. delete() {
  20270. return uncacheablePluginError(pluginName);
  20271. },
  20272. get() {
  20273. return uncacheablePluginError(pluginName);
  20274. },
  20275. has() {
  20276. return uncacheablePluginError(pluginName);
  20277. },
  20278. set() {
  20279. return uncacheablePluginError(pluginName);
  20280. }
  20281. };
  20282. }
  20283. async function transform(source, module, pluginDriver, warn) {
  20284. const id = module.id;
  20285. const sourcemapChain = [];
  20286. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20287. const originalCode = source.code;
  20288. let ast = source.ast;
  20289. const transformDependencies = [];
  20290. const emittedFiles = [];
  20291. let customTransformCache = false;
  20292. const useCustomTransformCache = () => (customTransformCache = true);
  20293. let pluginName = '';
  20294. const curSource = source.code;
  20295. function transformReducer(previousCode, result, plugin) {
  20296. let code;
  20297. let map;
  20298. if (typeof result === 'string') {
  20299. code = result;
  20300. }
  20301. else if (result && typeof result === 'object') {
  20302. module.updateOptions(result);
  20303. if (result.code == null) {
  20304. if (result.map || result.ast) {
  20305. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  20306. }
  20307. return previousCode;
  20308. }
  20309. ({ code, map, ast } = result);
  20310. }
  20311. else {
  20312. return previousCode;
  20313. }
  20314. // strict null check allows 'null' maps to not be pushed to the chain,
  20315. // while 'undefined' gets the missing map warning
  20316. if (map !== null) {
  20317. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20318. missing: true,
  20319. plugin: plugin.name
  20320. });
  20321. }
  20322. return code;
  20323. }
  20324. let code;
  20325. try {
  20326. code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  20327. pluginName = plugin.name;
  20328. return {
  20329. ...pluginContext,
  20330. addWatchFile(id) {
  20331. transformDependencies.push(id);
  20332. pluginContext.addWatchFile(id);
  20333. },
  20334. cache: customTransformCache
  20335. ? pluginContext.cache
  20336. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20337. emitAsset(name, source) {
  20338. emittedFiles.push({ name, source, type: 'asset' });
  20339. return pluginContext.emitAsset(name, source);
  20340. },
  20341. emitChunk(id, options) {
  20342. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  20343. return pluginContext.emitChunk(id, options);
  20344. },
  20345. emitFile(emittedFile) {
  20346. emittedFiles.push(emittedFile);
  20347. return pluginDriver.emitFile(emittedFile);
  20348. },
  20349. error(err, pos) {
  20350. if (typeof err === 'string')
  20351. err = { message: err };
  20352. if (pos)
  20353. augmentCodeLocation(err, pos, curSource, id);
  20354. err.id = id;
  20355. err.hook = 'transform';
  20356. return pluginContext.error(err);
  20357. },
  20358. getCombinedSourcemap() {
  20359. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  20360. if (!combinedMap) {
  20361. const magicString = new MagicString(originalCode);
  20362. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20363. }
  20364. if (originalSourcemap !== combinedMap) {
  20365. originalSourcemap = combinedMap;
  20366. sourcemapChain.length = 0;
  20367. }
  20368. return new SourceMap({
  20369. ...combinedMap,
  20370. file: null,
  20371. sourcesContent: combinedMap.sourcesContent
  20372. });
  20373. },
  20374. setAssetSource() {
  20375. return this.error({
  20376. code: 'INVALID_SETASSETSOURCE',
  20377. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  20378. });
  20379. },
  20380. warn(warning, pos) {
  20381. if (typeof warning === 'string')
  20382. warning = { message: warning };
  20383. if (pos)
  20384. augmentCodeLocation(warning, pos, curSource, id);
  20385. warning.id = id;
  20386. warning.hook = 'transform';
  20387. pluginContext.warn(warning);
  20388. }
  20389. };
  20390. });
  20391. }
  20392. catch (err) {
  20393. throwPluginError(err, pluginName, { hook: 'transform', id });
  20394. }
  20395. if (!customTransformCache) {
  20396. // files emitted by a transform hook need to be emitted again if the hook is skipped
  20397. if (emittedFiles.length)
  20398. module.transformFiles = emittedFiles;
  20399. }
  20400. return {
  20401. ast,
  20402. code,
  20403. customTransformCache,
  20404. originalCode,
  20405. originalSourcemap,
  20406. sourcemapChain,
  20407. transformDependencies
  20408. };
  20409. }
  20410. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20411. class ModuleLoader {
  20412. constructor(graph, modulesById, options, pluginDriver) {
  20413. this.graph = graph;
  20414. this.modulesById = modulesById;
  20415. this.options = options;
  20416. this.pluginDriver = pluginDriver;
  20417. this.implicitEntryModules = new Set();
  20418. this.indexedEntryModules = [];
  20419. this.latestLoadModulesPromise = Promise.resolve();
  20420. this.moduleLoadPromises = new Map();
  20421. this.modulesWithLoadedDependencies = new Set();
  20422. this.nextChunkNamePriority = 0;
  20423. this.nextEntryModuleIndex = 0;
  20424. this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
  20425. return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20426. ? false
  20427. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
  20428. };
  20429. this.hasModuleSideEffects = options.treeshake
  20430. ? options.treeshake.moduleSideEffects
  20431. : () => true;
  20432. }
  20433. async addAdditionalModules(unresolvedModules) {
  20434. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  20435. await this.awaitLoadModulesPromise();
  20436. return result;
  20437. }
  20438. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20439. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20440. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20441. const firstChunkNamePriority = this.nextChunkNamePriority;
  20442. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20443. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20444. for (let index = 0; index < entryModules.length; index++) {
  20445. const entryModule = entryModules[index];
  20446. entryModule.isUserDefinedEntryPoint =
  20447. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20448. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20449. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20450. if (!existingIndexedModule) {
  20451. this.indexedEntryModules.push({
  20452. index: firstEntryModuleIndex + index,
  20453. module: entryModule
  20454. });
  20455. }
  20456. else {
  20457. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20458. }
  20459. }
  20460. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20461. return entryModules;
  20462. }));
  20463. await this.awaitLoadModulesPromise();
  20464. return {
  20465. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20466. implicitEntryModules: [...this.implicitEntryModules],
  20467. newEntryModules
  20468. };
  20469. }
  20470. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20471. const unresolvedModule = {
  20472. fileName: fileName || null,
  20473. id,
  20474. importer,
  20475. name: name || null
  20476. };
  20477. const module = implicitlyLoadedAfterOneOf
  20478. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20479. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20480. if (preserveSignature != null) {
  20481. module.preserveSignature = preserveSignature;
  20482. }
  20483. return module;
  20484. }
  20485. async preloadModule(resolvedId) {
  20486. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20487. return module.info;
  20488. }
  20489. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20490. const chunkNamePriority = this.nextChunkNamePriority++;
  20491. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20492. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20493. if (!entryModule.info.isEntry) {
  20494. this.implicitEntryModules.add(entryModule);
  20495. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20496. for (const module of implicitlyLoadedAfterModules) {
  20497. entryModule.implicitlyLoadedAfter.add(module);
  20498. }
  20499. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20500. dependant.implicitlyLoadedBefore.add(entryModule);
  20501. }
  20502. }
  20503. return entryModule;
  20504. }));
  20505. }
  20506. async addModuleSource(id, importer, module) {
  20507. timeStart('load modules', 3);
  20508. let source;
  20509. try {
  20510. source = await this.graph.fileOperationQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await require$$0$1.promises.readFile(id, 'utf8')); });
  20511. }
  20512. catch (err) {
  20513. timeEnd('load modules', 3);
  20514. let msg = `Could not load ${id}`;
  20515. if (importer)
  20516. msg += ` (imported by ${relativeId(importer)})`;
  20517. msg += `: ${err.message}`;
  20518. err.message = msg;
  20519. throw err;
  20520. }
  20521. timeEnd('load modules', 3);
  20522. const sourceDescription = typeof source === 'string'
  20523. ? { code: source }
  20524. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20525. ? source
  20526. : error(errBadLoader(id));
  20527. const cachedModule = this.graph.cachedModules.get(id);
  20528. if (cachedModule &&
  20529. !cachedModule.customTransformCache &&
  20530. cachedModule.originalCode === sourceDescription.code &&
  20531. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20532. {
  20533. ast: cachedModule.ast,
  20534. code: cachedModule.code,
  20535. id: cachedModule.id,
  20536. meta: cachedModule.meta,
  20537. moduleSideEffects: cachedModule.moduleSideEffects,
  20538. resolvedSources: cachedModule.resolvedIds,
  20539. syntheticNamedExports: cachedModule.syntheticNamedExports
  20540. }
  20541. ]))) {
  20542. if (cachedModule.transformFiles) {
  20543. for (const emittedFile of cachedModule.transformFiles)
  20544. this.pluginDriver.emitFile(emittedFile);
  20545. }
  20546. module.setSource(cachedModule);
  20547. }
  20548. else {
  20549. module.updateOptions(sourceDescription);
  20550. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  20551. }
  20552. }
  20553. async awaitLoadModulesPromise() {
  20554. let startingPromise;
  20555. do {
  20556. startingPromise = this.latestLoadModulesPromise;
  20557. await startingPromise;
  20558. } while (startingPromise !== this.latestLoadModulesPromise);
  20559. }
  20560. extendLoadModulesPromise(loadNewModulesPromise) {
  20561. this.latestLoadModulesPromise = Promise.all([
  20562. loadNewModulesPromise,
  20563. this.latestLoadModulesPromise
  20564. ]);
  20565. this.latestLoadModulesPromise.catch(() => {
  20566. /* Avoid unhandled Promise rejections */
  20567. });
  20568. return loadNewModulesPromise;
  20569. }
  20570. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20571. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20572. if (resolvedId === null)
  20573. return null;
  20574. if (typeof resolvedId === 'string') {
  20575. dynamicImport.resolution = resolvedId;
  20576. return null;
  20577. }
  20578. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20579. })));
  20580. for (const dependency of dependencies) {
  20581. if (dependency) {
  20582. module.dynamicDependencies.add(dependency);
  20583. dependency.dynamicImporters.push(module.id);
  20584. }
  20585. }
  20586. }
  20587. // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
  20588. // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
  20589. // Otherwise it returns immediately.
  20590. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20591. const existingModule = this.modulesById.get(id);
  20592. if (existingModule instanceof Module) {
  20593. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20594. return existingModule;
  20595. }
  20596. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  20597. this.modulesById.set(id, module);
  20598. this.graph.watchFiles[id] = true;
  20599. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20600. this.getResolveStaticDependencyPromises(module),
  20601. this.getResolveDynamicImportPromises(module),
  20602. loadAndResolveDependenciesPromise
  20603. ]);
  20604. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20605. loadAndResolveDependenciesPromise.catch(() => {
  20606. /* avoid unhandled promise rejections */
  20607. });
  20608. this.moduleLoadPromises.set(module, loadPromise);
  20609. const resolveDependencyPromises = await loadPromise;
  20610. if (!isPreload) {
  20611. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20612. }
  20613. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20614. await loadAndResolveDependenciesPromise;
  20615. }
  20616. return module;
  20617. }
  20618. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20619. if (this.modulesWithLoadedDependencies.has(module)) {
  20620. return;
  20621. }
  20622. this.modulesWithLoadedDependencies.add(module);
  20623. await Promise.all([
  20624. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20625. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20626. ]);
  20627. module.linkImports();
  20628. // To handle errors when resolving dependencies or in moduleParsed
  20629. await loadAndResolveDependenciesPromise;
  20630. }
  20631. fetchResolvedDependency(source, importer, resolvedId) {
  20632. if (resolvedId.external) {
  20633. const { external, id, moduleSideEffects, meta } = resolvedId;
  20634. if (!this.modulesById.has(id)) {
  20635. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  20636. }
  20637. const externalModule = this.modulesById.get(id);
  20638. if (!(externalModule instanceof ExternalModule)) {
  20639. return error(errInternalIdCannotBeExternal(source, importer));
  20640. }
  20641. return Promise.resolve(externalModule);
  20642. }
  20643. return this.fetchModule(resolvedId, importer, false, false);
  20644. }
  20645. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20646. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20647. module.dependencies.add(dependency);
  20648. dependency.importers.push(module.id);
  20649. }
  20650. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20651. for (const dependency of module.dependencies) {
  20652. if (dependency instanceof Module) {
  20653. dependency.importedFromNotTreeshaken = true;
  20654. }
  20655. }
  20656. }
  20657. }
  20658. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20659. const { makeAbsoluteExternalsRelative } = this.options;
  20660. if (resolveIdResult) {
  20661. if (typeof resolveIdResult === 'object') {
  20662. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20663. return {
  20664. ...resolveIdResult,
  20665. external: external &&
  20666. (external === 'relative' ||
  20667. !isAbsolute(resolveIdResult.id) ||
  20668. (external === true &&
  20669. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20670. 'absolute')
  20671. };
  20672. }
  20673. const external = this.options.external(resolveIdResult, importer, true);
  20674. return {
  20675. external: external &&
  20676. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20677. 'absolute'),
  20678. id: external && makeAbsoluteExternalsRelative
  20679. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20680. : resolveIdResult
  20681. };
  20682. }
  20683. const id = makeAbsoluteExternalsRelative
  20684. ? normalizeRelativeExternalId(source, importer)
  20685. : source;
  20686. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20687. return null;
  20688. }
  20689. return {
  20690. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20691. id
  20692. };
  20693. }
  20694. getResolveDynamicImportPromises(module) {
  20695. return module.dynamicImports.map(async (dynamicImport) => {
  20696. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  20697. ? dynamicImport.argument
  20698. : dynamicImport.argument.esTreeNode, module.id);
  20699. if (resolvedId && typeof resolvedId === 'object') {
  20700. dynamicImport.id = resolvedId.id;
  20701. }
  20702. return [dynamicImport, resolvedId];
  20703. });
  20704. }
  20705. getResolveStaticDependencyPromises(module) {
  20706. return Array.from(module.sources, async (source) => [
  20707. source,
  20708. (module.resolvedIds[source] =
  20709. module.resolvedIds[source] ||
  20710. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
  20711. ]);
  20712. }
  20713. getResolvedIdWithDefaults(resolvedId) {
  20714. var _a, _b;
  20715. if (!resolvedId) {
  20716. return null;
  20717. }
  20718. const external = resolvedId.external || false;
  20719. return {
  20720. external,
  20721. id: resolvedId.id,
  20722. meta: resolvedId.meta || {},
  20723. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  20724. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  20725. };
  20726. }
  20727. async handleExistingModule(module, isEntry, isPreload) {
  20728. const loadPromise = this.moduleLoadPromises.get(module);
  20729. if (isPreload) {
  20730. return isPreload === RESOLVE_DEPENDENCIES
  20731. ? waitForDependencyResolution(loadPromise)
  20732. : loadPromise;
  20733. }
  20734. if (isEntry) {
  20735. module.info.isEntry = true;
  20736. this.implicitEntryModules.delete(module);
  20737. for (const dependant of module.implicitlyLoadedAfter) {
  20738. dependant.implicitlyLoadedBefore.delete(module);
  20739. }
  20740. module.implicitlyLoadedAfter.clear();
  20741. }
  20742. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20743. }
  20744. handleResolveId(resolvedId, source, importer) {
  20745. if (resolvedId === null) {
  20746. if (isRelative(source)) {
  20747. return error(errUnresolvedImport(source, importer));
  20748. }
  20749. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  20750. return {
  20751. external: true,
  20752. id: source,
  20753. meta: {},
  20754. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20755. syntheticNamedExports: false
  20756. };
  20757. }
  20758. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20759. this.options.onwarn(errExternalSyntheticExports(source, importer));
  20760. }
  20761. return resolvedId;
  20762. }
  20763. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  20764. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
  20765. if (resolveIdResult == null) {
  20766. return error(implicitlyLoadedBefore === null
  20767. ? errUnresolvedEntry(unresolvedId)
  20768. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20769. }
  20770. if (resolveIdResult === false ||
  20771. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  20772. return error(implicitlyLoadedBefore === null
  20773. ? errEntryCannotBeExternal(unresolvedId)
  20774. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20775. }
  20776. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20777. ? resolveIdResult
  20778. : { id: resolveIdResult }), undefined, isEntry, false);
  20779. }
  20780. async resolveDynamicImport(module, specifier, importer) {
  20781. var _a;
  20782. var _b;
  20783. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20784. specifier,
  20785. importer
  20786. ]);
  20787. if (typeof specifier !== 'string') {
  20788. if (typeof resolution === 'string') {
  20789. return resolution;
  20790. }
  20791. if (!resolution) {
  20792. return null;
  20793. }
  20794. return {
  20795. external: false,
  20796. moduleSideEffects: true,
  20797. ...resolution
  20798. };
  20799. }
  20800. if (resolution == null) {
  20801. 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)));
  20802. }
  20803. return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  20804. }
  20805. }
  20806. function normalizeRelativeExternalId(source, importer) {
  20807. return isRelative(source)
  20808. ? importer
  20809. ? require$$0.resolve(importer, '..', source)
  20810. : require$$0.resolve(source)
  20811. : source;
  20812. }
  20813. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20814. var _a;
  20815. if (fileName !== null) {
  20816. module.chunkFileNames.add(fileName);
  20817. }
  20818. else if (name !== null) {
  20819. // Always keep chunkNames sorted by priority
  20820. let namePosition = 0;
  20821. while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
  20822. namePosition++;
  20823. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20824. }
  20825. }
  20826. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20827. return (makeAbsoluteExternalsRelative === true ||
  20828. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20829. !isAbsolute(id));
  20830. }
  20831. async function waitForDependencyResolution(loadPromise) {
  20832. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20833. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20834. }
  20835. class GlobalScope extends Scope$1 {
  20836. constructor() {
  20837. super();
  20838. this.parent = null;
  20839. this.variables.set('undefined', new UndefinedVariable());
  20840. }
  20841. findVariable(name) {
  20842. let variable = this.variables.get(name);
  20843. if (!variable) {
  20844. variable = new GlobalVariable(name);
  20845. this.variables.set(name, variable);
  20846. }
  20847. return variable;
  20848. }
  20849. }
  20850. function generateAssetFileName(name, source, outputOptions, bundle) {
  20851. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  20852. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  20853. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  20854. : outputOptions.assetFileNames, 'output.assetFileNames', {
  20855. ext: () => require$$0.extname(emittedName).substring(1),
  20856. extname: () => require$$0.extname(emittedName),
  20857. hash() {
  20858. return createHash()
  20859. .update(emittedName)
  20860. .update(':')
  20861. .update(source)
  20862. .digest('hex')
  20863. .substring(0, 8);
  20864. },
  20865. name: () => emittedName.substring(0, emittedName.length - require$$0.extname(emittedName).length)
  20866. }), bundle);
  20867. }
  20868. function reserveFileNameInBundle(fileName, bundle, warn) {
  20869. const lowercaseFileName = fileName.toLowerCase();
  20870. if (bundle[lowercaseBundleKeys].has(lowercaseFileName)) {
  20871. warn(errFileNameConflict(fileName));
  20872. }
  20873. else {
  20874. bundle[fileName] = FILE_PLACEHOLDER;
  20875. }
  20876. }
  20877. function hasValidType(emittedFile) {
  20878. return Boolean(emittedFile &&
  20879. (emittedFile.type === 'asset' ||
  20880. emittedFile.type === 'chunk'));
  20881. }
  20882. function hasValidName(emittedFile) {
  20883. const validatedName = emittedFile.fileName || emittedFile.name;
  20884. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  20885. }
  20886. function getValidSource(source, emittedFile, fileReferenceId) {
  20887. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  20888. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  20889. 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.`));
  20890. }
  20891. return source;
  20892. }
  20893. function getAssetFileName(file, referenceId) {
  20894. if (typeof file.fileName !== 'string') {
  20895. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  20896. }
  20897. return file.fileName;
  20898. }
  20899. function getChunkFileName(file, facadeChunkByModule) {
  20900. var _a;
  20901. 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));
  20902. if (!fileName)
  20903. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  20904. return fileName;
  20905. }
  20906. class FileEmitter {
  20907. constructor(graph, options, baseFileEmitter) {
  20908. this.graph = graph;
  20909. this.options = options;
  20910. this.bundle = null;
  20911. this.facadeChunkByModule = null;
  20912. this.outputOptions = null;
  20913. this.assertAssetsFinalized = () => {
  20914. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  20915. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  20916. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  20917. }
  20918. };
  20919. this.emitFile = (emittedFile) => {
  20920. if (!hasValidType(emittedFile)) {
  20921. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  20922. }
  20923. if (!hasValidName(emittedFile)) {
  20924. 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}".`));
  20925. }
  20926. if (emittedFile.type === 'chunk') {
  20927. return this.emitChunk(emittedFile);
  20928. }
  20929. return this.emitAsset(emittedFile);
  20930. };
  20931. this.getFileName = (fileReferenceId) => {
  20932. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  20933. if (!emittedFile)
  20934. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  20935. if (emittedFile.type === 'chunk') {
  20936. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  20937. }
  20938. return getAssetFileName(emittedFile, fileReferenceId);
  20939. };
  20940. this.setAssetSource = (referenceId, requestedSource) => {
  20941. const consumedFile = this.filesByReferenceId.get(referenceId);
  20942. if (!consumedFile)
  20943. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  20944. if (consumedFile.type !== 'asset') {
  20945. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  20946. }
  20947. if (consumedFile.source !== undefined) {
  20948. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  20949. }
  20950. const source = getValidSource(requestedSource, consumedFile, referenceId);
  20951. if (this.bundle) {
  20952. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  20953. }
  20954. else {
  20955. consumedFile.source = source;
  20956. }
  20957. };
  20958. this.setOutputBundle = (bundle, outputOptions, facadeChunkByModule) => {
  20959. this.outputOptions = outputOptions;
  20960. this.bundle = bundle;
  20961. this.facadeChunkByModule = facadeChunkByModule;
  20962. for (const { fileName } of this.filesByReferenceId.values()) {
  20963. if (fileName) {
  20964. reserveFileNameInBundle(fileName, bundle, this.options.onwarn);
  20965. }
  20966. }
  20967. for (const [referenceId, consumedFile] of this.filesByReferenceId) {
  20968. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  20969. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, bundle);
  20970. }
  20971. }
  20972. };
  20973. this.filesByReferenceId = baseFileEmitter
  20974. ? new Map(baseFileEmitter.filesByReferenceId)
  20975. : new Map();
  20976. }
  20977. assignReferenceId(file, idBase) {
  20978. let referenceId;
  20979. do {
  20980. referenceId = createHash()
  20981. .update(referenceId || idBase)
  20982. .digest('hex')
  20983. .substring(0, 8);
  20984. } while (this.filesByReferenceId.has(referenceId));
  20985. this.filesByReferenceId.set(referenceId, file);
  20986. return referenceId;
  20987. }
  20988. emitAsset(emittedAsset) {
  20989. const source = typeof emittedAsset.source !== 'undefined'
  20990. ? getValidSource(emittedAsset.source, emittedAsset, null)
  20991. : undefined;
  20992. const consumedAsset = {
  20993. fileName: emittedAsset.fileName,
  20994. name: emittedAsset.name,
  20995. source,
  20996. type: 'asset'
  20997. };
  20998. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  20999. if (this.bundle) {
  21000. if (emittedAsset.fileName) {
  21001. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  21002. }
  21003. if (source !== undefined) {
  21004. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  21005. }
  21006. }
  21007. return referenceId;
  21008. }
  21009. emitChunk(emittedChunk) {
  21010. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  21011. return error(errInvalidRollupPhaseForChunkEmission());
  21012. }
  21013. if (typeof emittedChunk.id !== 'string') {
  21014. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  21015. }
  21016. const consumedChunk = {
  21017. fileName: emittedChunk.fileName,
  21018. module: null,
  21019. name: emittedChunk.name || emittedChunk.id,
  21020. type: 'chunk'
  21021. };
  21022. this.graph.moduleLoader
  21023. .emitChunk(emittedChunk)
  21024. .then(module => (consumedChunk.module = module))
  21025. .catch(() => {
  21026. // Avoid unhandled Promise rejection as the error will be thrown later
  21027. // once module loading has finished
  21028. });
  21029. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  21030. }
  21031. finalizeAsset(consumedFile, source, referenceId, bundle) {
  21032. const fileName = consumedFile.fileName ||
  21033. findExistingAssetFileNameWithSource(bundle, source) ||
  21034. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  21035. // We must not modify the original assets to avoid interaction between outputs
  21036. const assetWithFileName = { ...consumedFile, fileName, source };
  21037. this.filesByReferenceId.set(referenceId, assetWithFileName);
  21038. const { options } = this;
  21039. bundle[fileName] = {
  21040. fileName,
  21041. get isAsset() {
  21042. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  21043. return true;
  21044. },
  21045. name: consumedFile.name,
  21046. source,
  21047. type: 'asset'
  21048. };
  21049. }
  21050. }
  21051. // TODO This can lead to a performance problem when many assets are emitted.
  21052. // Instead, we should only deduplicate string assets and use their sources as
  21053. // object keys for better performance.
  21054. function findExistingAssetFileNameWithSource(bundle, source) {
  21055. for (const [fileName, outputFile] of Object.entries(bundle)) {
  21056. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  21057. return fileName;
  21058. }
  21059. return null;
  21060. }
  21061. function areSourcesEqual(sourceA, sourceB) {
  21062. if (typeof sourceA === 'string') {
  21063. return sourceA === sourceB;
  21064. }
  21065. if (typeof sourceB === 'string') {
  21066. return false;
  21067. }
  21068. if ('equals' in sourceA) {
  21069. return sourceA.equals(sourceB);
  21070. }
  21071. if (sourceA.length !== sourceB.length) {
  21072. return false;
  21073. }
  21074. for (let index = 0; index < sourceA.length; index++) {
  21075. if (sourceA[index] !== sourceB[index]) {
  21076. return false;
  21077. }
  21078. }
  21079. return true;
  21080. }
  21081. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  21082. let deprecationWarningShown = false;
  21083. return ((...args) => {
  21084. if (!deprecationWarningShown) {
  21085. deprecationWarningShown = true;
  21086. warnDeprecation({
  21087. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  21088. plugin: pluginName
  21089. }, activeDeprecation, options);
  21090. }
  21091. return handler(...args);
  21092. });
  21093. }
  21094. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  21095. let cacheable = true;
  21096. if (typeof plugin.cacheKey !== 'string') {
  21097. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  21098. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  21099. existingPluginNames.has(plugin.name)) {
  21100. cacheable = false;
  21101. }
  21102. else {
  21103. existingPluginNames.add(plugin.name);
  21104. }
  21105. }
  21106. let cacheInstance;
  21107. if (!pluginCache) {
  21108. cacheInstance = NO_CACHE;
  21109. }
  21110. else if (cacheable) {
  21111. const cacheKey = plugin.cacheKey || plugin.name;
  21112. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  21113. }
  21114. else {
  21115. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  21116. }
  21117. return {
  21118. addWatchFile(id) {
  21119. if (graph.phase >= BuildPhase.GENERATE) {
  21120. return this.error(errInvalidRollupPhaseForAddWatchFile());
  21121. }
  21122. graph.watchFiles[id] = true;
  21123. },
  21124. cache: cacheInstance,
  21125. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  21126. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  21127. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  21128. error(err) {
  21129. return throwPluginError(err, plugin.name);
  21130. },
  21131. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  21132. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  21133. getFileName: fileEmitter.getFileName,
  21134. getModuleIds: () => graph.modulesById.keys(),
  21135. getModuleInfo: graph.getModuleInfo,
  21136. getWatchFiles: () => Object.keys(graph.watchFiles),
  21137. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  21138. load(resolvedId) {
  21139. return graph.moduleLoader.preloadModule(resolvedId);
  21140. },
  21141. meta: {
  21142. rollupVersion: version$1,
  21143. watchMode: graph.watchMode
  21144. },
  21145. get moduleIds() {
  21146. function* wrappedModuleIds() {
  21147. // We are wrapping this in a generator to only show the message once we are actually iterating
  21148. warnDeprecation({
  21149. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  21150. plugin: plugin.name
  21151. }, false, options);
  21152. yield* moduleIds;
  21153. }
  21154. const moduleIds = graph.modulesById.keys();
  21155. return wrappedModuleIds();
  21156. },
  21157. parse: graph.contextParse.bind(graph),
  21158. resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
  21159. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
  21160. },
  21161. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  21162. .resolveId(source, importer, BLANK, undefined)
  21163. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  21164. setAssetSource: fileEmitter.setAssetSource,
  21165. warn(warning) {
  21166. if (typeof warning === 'string')
  21167. warning = { message: warning };
  21168. if (warning.code)
  21169. warning.pluginCode = warning.code;
  21170. warning.code = 'PLUGIN_WARNING';
  21171. warning.plugin = plugin.name;
  21172. options.onwarn(warning);
  21173. }
  21174. };
  21175. }
  21176. // This will make sure no input hook is omitted
  21177. const inputHookNames = {
  21178. buildEnd: 1,
  21179. buildStart: 1,
  21180. closeBundle: 1,
  21181. closeWatcher: 1,
  21182. load: 1,
  21183. moduleParsed: 1,
  21184. options: 1,
  21185. resolveDynamicImport: 1,
  21186. resolveId: 1,
  21187. shouldTransformCachedModule: 1,
  21188. transform: 1,
  21189. watchChange: 1
  21190. };
  21191. const inputHooks = Object.keys(inputHookNames);
  21192. class PluginDriver {
  21193. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21194. this.graph = graph;
  21195. this.options = options;
  21196. this.pluginCache = pluginCache;
  21197. this.sortedPlugins = new Map();
  21198. this.unfulfilledActions = new Set();
  21199. warnDeprecatedHooks(userPlugins, options);
  21200. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21201. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21202. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21203. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  21204. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21205. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  21206. const existingPluginNames = new Set();
  21207. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21208. plugin,
  21209. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21210. ]));
  21211. if (basePluginDriver) {
  21212. for (const plugin of userPlugins) {
  21213. for (const hook of inputHooks) {
  21214. if (hook in plugin) {
  21215. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  21216. }
  21217. }
  21218. }
  21219. }
  21220. }
  21221. createOutputPluginDriver(plugins) {
  21222. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21223. }
  21224. getUnfulfilledHookActions() {
  21225. return this.unfulfilledActions;
  21226. }
  21227. // chains, first non-null result stops and returns
  21228. hookFirst(hookName, args, replaceContext, skipped) {
  21229. let promise = Promise.resolve(null);
  21230. for (const plugin of this.getSortedPlugins(hookName)) {
  21231. if (skipped && skipped.has(plugin))
  21232. continue;
  21233. promise = promise.then(result => {
  21234. if (result != null)
  21235. return result;
  21236. return this.runHook(hookName, args, plugin, replaceContext);
  21237. });
  21238. }
  21239. return promise;
  21240. }
  21241. // chains synchronously, first non-null result stops and returns
  21242. hookFirstSync(hookName, args, replaceContext) {
  21243. for (const plugin of this.getSortedPlugins(hookName)) {
  21244. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21245. if (result != null)
  21246. return result;
  21247. }
  21248. return null;
  21249. }
  21250. // parallel, ignores returns
  21251. async hookParallel(hookName, args, replaceContext) {
  21252. const parallelPromises = [];
  21253. for (const plugin of this.getSortedPlugins(hookName)) {
  21254. if (plugin[hookName].sequential) {
  21255. await Promise.all(parallelPromises);
  21256. parallelPromises.length = 0;
  21257. await this.runHook(hookName, args, plugin, replaceContext);
  21258. }
  21259. else {
  21260. parallelPromises.push(this.runHook(hookName, args, plugin, replaceContext));
  21261. }
  21262. }
  21263. await Promise.all(parallelPromises);
  21264. }
  21265. // chains, reduces returned value, handling the reduced value as the first hook argument
  21266. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  21267. let promise = Promise.resolve(arg0);
  21268. for (const plugin of this.getSortedPlugins(hookName)) {
  21269. promise = promise.then(arg0 => this.runHook(hookName, [arg0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)));
  21270. }
  21271. return promise;
  21272. }
  21273. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21274. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  21275. for (const plugin of this.getSortedPlugins(hookName)) {
  21276. const args = [arg0, ...rest];
  21277. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21278. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  21279. }
  21280. return arg0;
  21281. }
  21282. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21283. async hookReduceValue(hookName, initialValue, args, reducer) {
  21284. const results = [];
  21285. const parallelResults = [];
  21286. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21287. if (plugin[hookName].sequential) {
  21288. results.push(...(await Promise.all(parallelResults)));
  21289. parallelResults.length = 0;
  21290. results.push(await this.runHook(hookName, args, plugin));
  21291. }
  21292. else {
  21293. parallelResults.push(this.runHook(hookName, args, plugin));
  21294. }
  21295. }
  21296. results.push(...(await Promise.all(parallelResults)));
  21297. return results.reduce(reducer, await initialValue);
  21298. }
  21299. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21300. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  21301. let acc = initialValue;
  21302. for (const plugin of this.getSortedPlugins(hookName)) {
  21303. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21304. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  21305. }
  21306. return acc;
  21307. }
  21308. // chains, ignores returns
  21309. hookSeq(hookName, args, replaceContext) {
  21310. let promise = Promise.resolve();
  21311. for (const plugin of this.getSortedPlugins(hookName)) {
  21312. promise = promise.then(() => this.runHook(hookName, args, plugin, replaceContext));
  21313. }
  21314. return promise.then(noReturn);
  21315. }
  21316. getSortedPlugins(hookName, validateHandler) {
  21317. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21318. }
  21319. // Implementation signature
  21320. runHook(hookName, args, plugin, replaceContext) {
  21321. // We always filter for plugins that support the hook before running it
  21322. const hook = plugin[hookName];
  21323. const handler = typeof hook === 'object' ? hook.handler : hook;
  21324. let context = this.pluginContexts.get(plugin);
  21325. if (replaceContext) {
  21326. context = replaceContext(context, plugin);
  21327. }
  21328. let action = null;
  21329. return Promise.resolve()
  21330. .then(() => {
  21331. if (typeof handler !== 'function') {
  21332. return handler;
  21333. }
  21334. // eslint-disable-next-line @typescript-eslint/ban-types
  21335. const hookResult = handler.apply(context, args);
  21336. if (!(hookResult === null || hookResult === void 0 ? void 0 : hookResult.then)) {
  21337. // short circuit for non-thenables and non-Promises
  21338. return hookResult;
  21339. }
  21340. // Track pending hook actions to properly error out when
  21341. // unfulfilled promises cause rollup to abruptly and confusingly
  21342. // exit with a successful 0 return code but without producing any
  21343. // output, errors or warnings.
  21344. action = [plugin.name, hookName, args];
  21345. this.unfulfilledActions.add(action);
  21346. // Although it would be more elegant to just return hookResult here
  21347. // and put the .then() handler just above the .catch() handler below,
  21348. // doing so would subtly change the defacto async event dispatch order
  21349. // which at least one test and some plugins in the wild may depend on.
  21350. return Promise.resolve(hookResult).then(result => {
  21351. // action was fulfilled
  21352. this.unfulfilledActions.delete(action);
  21353. return result;
  21354. });
  21355. })
  21356. .catch(err => {
  21357. if (action !== null) {
  21358. // action considered to be fulfilled since error being handled
  21359. this.unfulfilledActions.delete(action);
  21360. }
  21361. return throwPluginError(err, plugin.name, { hook: hookName });
  21362. });
  21363. }
  21364. /**
  21365. * Run a sync plugin hook and return the result.
  21366. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21367. * @param args Arguments passed to the plugin hook.
  21368. * @param plugin The acutal plugin
  21369. * @param replaceContext When passed, the plugin context can be overridden.
  21370. */
  21371. runHookSync(hookName, args, plugin, replaceContext) {
  21372. const hook = plugin[hookName];
  21373. const handler = typeof hook === 'object' ? hook.handler : hook;
  21374. let context = this.pluginContexts.get(plugin);
  21375. if (replaceContext) {
  21376. context = replaceContext(context, plugin);
  21377. }
  21378. try {
  21379. // eslint-disable-next-line @typescript-eslint/ban-types
  21380. return handler.apply(context, args);
  21381. }
  21382. catch (err) {
  21383. return throwPluginError(err, plugin.name, { hook: hookName });
  21384. }
  21385. }
  21386. }
  21387. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  21388. const pre = [];
  21389. const normal = [];
  21390. const post = [];
  21391. for (const plugin of plugins) {
  21392. const hook = plugin[hookName];
  21393. if (hook) {
  21394. if (typeof hook === 'object') {
  21395. validateHandler(hook.handler, hookName, plugin);
  21396. if (hook.order === 'pre') {
  21397. pre.push(plugin);
  21398. continue;
  21399. }
  21400. if (hook.order === 'post') {
  21401. post.push(plugin);
  21402. continue;
  21403. }
  21404. }
  21405. else {
  21406. validateHandler(hook, hookName, plugin);
  21407. }
  21408. normal.push(plugin);
  21409. }
  21410. }
  21411. return [...pre, ...normal, ...post];
  21412. }
  21413. function validateFunctionPluginHandler(handler, hookName, plugin) {
  21414. if (typeof handler !== 'function') {
  21415. error(errInvalidFunctionPluginHook(hookName, plugin.name));
  21416. }
  21417. }
  21418. function validateAddonPluginHandler(handler, hookName, plugin) {
  21419. if (typeof handler !== 'string' && typeof handler !== 'function') {
  21420. return error(errInvalidAddonPluginHook(hookName, plugin.name));
  21421. }
  21422. }
  21423. function noReturn() { }
  21424. class Queue {
  21425. constructor(maxParallel) {
  21426. this.maxParallel = maxParallel;
  21427. this.queue = [];
  21428. this.workerCount = 0;
  21429. }
  21430. run(task) {
  21431. return new Promise((resolve, reject) => {
  21432. this.queue.push({ reject, resolve, task });
  21433. this.work();
  21434. });
  21435. }
  21436. async work() {
  21437. if (this.workerCount >= this.maxParallel)
  21438. return;
  21439. this.workerCount++;
  21440. let entry;
  21441. while ((entry = this.queue.shift())) {
  21442. const { reject, resolve, task } = entry;
  21443. try {
  21444. const result = await task();
  21445. resolve(result);
  21446. }
  21447. catch (err) {
  21448. reject(err);
  21449. }
  21450. }
  21451. this.workerCount--;
  21452. }
  21453. }
  21454. function normalizeEntryModules(entryModules) {
  21455. if (Array.isArray(entryModules)) {
  21456. return entryModules.map(id => ({
  21457. fileName: null,
  21458. id,
  21459. implicitlyLoadedAfter: [],
  21460. importer: undefined,
  21461. name: null
  21462. }));
  21463. }
  21464. return Object.entries(entryModules).map(([name, id]) => ({
  21465. fileName: null,
  21466. id,
  21467. implicitlyLoadedAfter: [],
  21468. importer: undefined,
  21469. name
  21470. }));
  21471. }
  21472. class Graph {
  21473. constructor(options, watcher) {
  21474. var _a, _b;
  21475. this.options = options;
  21476. this.cachedModules = new Map();
  21477. this.deoptimizationTracker = new PathTracker();
  21478. this.entryModules = [];
  21479. this.modulesById = new Map();
  21480. this.needsTreeshakingPass = false;
  21481. this.phase = BuildPhase.LOAD_AND_PARSE;
  21482. this.scope = new GlobalScope();
  21483. this.watchFiles = Object.create(null);
  21484. this.watchMode = false;
  21485. this.externalModules = [];
  21486. this.implicitEntryModules = [];
  21487. this.modules = [];
  21488. this.getModuleInfo = (moduleId) => {
  21489. const foundModule = this.modulesById.get(moduleId);
  21490. if (!foundModule)
  21491. return null;
  21492. return foundModule.info;
  21493. };
  21494. if (options.cache !== false) {
  21495. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  21496. for (const module of options.cache.modules)
  21497. this.cachedModules.set(module.id, module);
  21498. }
  21499. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  21500. // increment access counter
  21501. for (const name in this.pluginCache) {
  21502. const cache = this.pluginCache[name];
  21503. for (const value of Object.values(cache))
  21504. value[0]++;
  21505. }
  21506. }
  21507. if (watcher) {
  21508. this.watchMode = true;
  21509. const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
  21510. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21511. watcher.onCurrentAwaited('change', handleChange);
  21512. watcher.onCurrentAwaited('close', handleClose);
  21513. }
  21514. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21515. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  21516. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21517. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21518. }
  21519. async build() {
  21520. timeStart('generate module graph', 2);
  21521. await this.generateModuleGraph();
  21522. timeEnd('generate module graph', 2);
  21523. timeStart('sort modules', 2);
  21524. this.phase = BuildPhase.ANALYSE;
  21525. this.sortModules();
  21526. timeEnd('sort modules', 2);
  21527. timeStart('mark included statements', 2);
  21528. this.includeStatements();
  21529. timeEnd('mark included statements', 2);
  21530. this.phase = BuildPhase.GENERATE;
  21531. }
  21532. contextParse(code, options = {}) {
  21533. const onCommentOrig = options.onComment;
  21534. const comments = [];
  21535. if (onCommentOrig && typeof onCommentOrig == 'function') {
  21536. options.onComment = (block, text, start, end, ...args) => {
  21537. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  21538. return onCommentOrig.call(options, block, text, start, end, ...args);
  21539. };
  21540. }
  21541. else {
  21542. options.onComment = comments;
  21543. }
  21544. const ast = this.acornParser.parse(code, {
  21545. ...this.options.acorn,
  21546. ...options
  21547. });
  21548. if (typeof onCommentOrig == 'object') {
  21549. onCommentOrig.push(...comments);
  21550. }
  21551. options.onComment = onCommentOrig;
  21552. addAnnotations(comments, ast, code);
  21553. return ast;
  21554. }
  21555. getCache() {
  21556. // handle plugin cache eviction
  21557. for (const name in this.pluginCache) {
  21558. const cache = this.pluginCache[name];
  21559. let allDeleted = true;
  21560. for (const [key, value] of Object.entries(cache)) {
  21561. if (value[0] >= this.options.experimentalCacheExpiry)
  21562. delete cache[key];
  21563. else
  21564. allDeleted = false;
  21565. }
  21566. if (allDeleted)
  21567. delete this.pluginCache[name];
  21568. }
  21569. return {
  21570. modules: this.modules.map(module => module.toJSON()),
  21571. plugins: this.pluginCache
  21572. };
  21573. }
  21574. async generateModuleGraph() {
  21575. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21576. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21577. if (this.entryModules.length === 0) {
  21578. throw new Error('You must supply options.input to rollup');
  21579. }
  21580. for (const module of this.modulesById.values()) {
  21581. if (module instanceof Module) {
  21582. this.modules.push(module);
  21583. }
  21584. else {
  21585. this.externalModules.push(module);
  21586. }
  21587. }
  21588. }
  21589. includeStatements() {
  21590. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21591. markModuleAndImpureDependenciesAsExecuted(module);
  21592. }
  21593. if (this.options.treeshake) {
  21594. let treeshakingPass = 1;
  21595. do {
  21596. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21597. this.needsTreeshakingPass = false;
  21598. for (const module of this.modules) {
  21599. if (module.isExecuted) {
  21600. if (module.info.moduleSideEffects === 'no-treeshake') {
  21601. module.includeAllInBundle();
  21602. }
  21603. else {
  21604. module.include();
  21605. }
  21606. }
  21607. }
  21608. if (treeshakingPass === 1) {
  21609. // We only include exports after the first pass to avoid issues with
  21610. // the TDZ detection logic
  21611. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21612. if (module.preserveSignature !== false) {
  21613. module.includeAllExports(false);
  21614. this.needsTreeshakingPass = true;
  21615. }
  21616. }
  21617. }
  21618. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21619. } while (this.needsTreeshakingPass);
  21620. }
  21621. else {
  21622. for (const module of this.modules)
  21623. module.includeAllInBundle();
  21624. }
  21625. for (const externalModule of this.externalModules)
  21626. externalModule.warnUnusedImports();
  21627. for (const module of this.implicitEntryModules) {
  21628. for (const dependant of module.implicitlyLoadedAfter) {
  21629. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21630. error(errImplicitDependantIsNotIncluded(dependant));
  21631. }
  21632. }
  21633. }
  21634. }
  21635. sortModules() {
  21636. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21637. for (const cyclePath of cyclePaths) {
  21638. this.options.onwarn({
  21639. code: 'CIRCULAR_DEPENDENCY',
  21640. cycle: cyclePath,
  21641. importer: cyclePath[0],
  21642. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  21643. });
  21644. }
  21645. this.modules = orderedModules;
  21646. for (const module of this.modules) {
  21647. module.bindReferences();
  21648. }
  21649. this.warnForMissingExports();
  21650. }
  21651. warnForMissingExports() {
  21652. for (const module of this.modules) {
  21653. for (const importDescription of module.importDescriptions.values()) {
  21654. if (importDescription.name !== '*' &&
  21655. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21656. module.warn({
  21657. code: 'NON_EXISTENT_EXPORT',
  21658. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  21659. name: importDescription.name,
  21660. source: importDescription.module.id
  21661. }, importDescription.start);
  21662. }
  21663. }
  21664. }
  21665. }
  21666. }
  21667. function formatAction([pluginName, hookName, args]) {
  21668. const action = `(${pluginName}) ${hookName}`;
  21669. const s = JSON.stringify;
  21670. switch (hookName) {
  21671. case 'resolveId':
  21672. return `${action} ${s(args[0])} ${s(args[1])}`;
  21673. case 'load':
  21674. return `${action} ${s(args[0])}`;
  21675. case 'transform':
  21676. return `${action} ${s(args[1])}`;
  21677. case 'shouldTransformCachedModule':
  21678. return `${action} ${s(args[0].id)}`;
  21679. case 'moduleParsed':
  21680. return `${action} ${s(args[0].id)}`;
  21681. }
  21682. return action;
  21683. }
  21684. // We do not directly listen on process to avoid max listeners warnings for
  21685. // complicated build processes
  21686. const beforeExitEvent = 'beforeExit';
  21687. const beforeExitEmitter = new require$$0$2.EventEmitter();
  21688. beforeExitEmitter.setMaxListeners(0);
  21689. process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
  21690. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21691. let handleEmptyEventLoop;
  21692. const emptyEventLoopPromise = new Promise((_, reject) => {
  21693. handleEmptyEventLoop = () => {
  21694. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21695. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21696. [...unfulfilledActions].map(formatAction).join('\n')));
  21697. };
  21698. beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
  21699. });
  21700. const result = await Promise.race([callback(), emptyEventLoopPromise]);
  21701. beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
  21702. return result;
  21703. }
  21704. function normalizeInputOptions(config) {
  21705. var _a, _b, _c;
  21706. // These are options that may trigger special warnings or behaviour later
  21707. // if the user did not select an explicit value
  21708. const unsetOptions = new Set();
  21709. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  21710. const onwarn = getOnwarn(config);
  21711. const strictDeprecations = config.strictDeprecations || false;
  21712. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  21713. const options = {
  21714. acorn: getAcorn(config),
  21715. acornInjectPlugins: getAcornInjectPlugins(config),
  21716. cache: getCache(config),
  21717. context,
  21718. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  21719. external: getIdMatcher(config.external),
  21720. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  21721. input: getInput(config),
  21722. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  21723. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  21724. maxParallelFileOps,
  21725. maxParallelFileReads: maxParallelFileOps,
  21726. moduleContext: getModuleContext(config, context),
  21727. onwarn,
  21728. perf: config.perf || false,
  21729. plugins: ensureArray$1(config.plugins),
  21730. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  21731. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  21732. preserveSymlinks: config.preserveSymlinks || false,
  21733. shimMissingExports: config.shimMissingExports || false,
  21734. strictDeprecations,
  21735. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  21736. };
  21737. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  21738. return { options, unsetOptions };
  21739. }
  21740. const getOnwarn = (config) => {
  21741. const { onwarn } = config;
  21742. return onwarn
  21743. ? warning => {
  21744. warning.toString = () => {
  21745. let str = '';
  21746. if (warning.plugin)
  21747. str += `(${warning.plugin} plugin) `;
  21748. if (warning.loc)
  21749. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  21750. str += warning.message;
  21751. return str;
  21752. };
  21753. onwarn(warning, defaultOnWarn);
  21754. }
  21755. : defaultOnWarn;
  21756. };
  21757. const getAcorn = (config) => ({
  21758. allowAwaitOutsideFunction: true,
  21759. ecmaVersion: 'latest',
  21760. preserveParens: false,
  21761. sourceType: 'module',
  21762. ...config.acorn
  21763. });
  21764. const getAcornInjectPlugins = (config) => ensureArray$1(config.acornInjectPlugins);
  21765. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  21766. const getIdMatcher = (option) => {
  21767. if (option === true) {
  21768. return () => true;
  21769. }
  21770. if (typeof option === 'function') {
  21771. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  21772. }
  21773. if (option) {
  21774. const ids = new Set();
  21775. const matchers = [];
  21776. for (const value of ensureArray$1(option)) {
  21777. if (value instanceof RegExp) {
  21778. matchers.push(value);
  21779. }
  21780. else {
  21781. ids.add(value);
  21782. }
  21783. }
  21784. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21785. }
  21786. return () => false;
  21787. };
  21788. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  21789. const configInlineDynamicImports = config.inlineDynamicImports;
  21790. if (configInlineDynamicImports) {
  21791. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  21792. }
  21793. return configInlineDynamicImports;
  21794. };
  21795. const getInput = (config) => {
  21796. const configInput = config.input;
  21797. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21798. };
  21799. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  21800. const configManualChunks = config.manualChunks;
  21801. if (configManualChunks) {
  21802. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  21803. }
  21804. return configManualChunks;
  21805. };
  21806. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  21807. var _a;
  21808. const maxParallelFileReads = config.maxParallelFileReads;
  21809. if (typeof maxParallelFileReads === 'number') {
  21810. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
  21811. }
  21812. const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
  21813. if (typeof maxParallelFileOps === 'number') {
  21814. if (maxParallelFileOps <= 0)
  21815. return Infinity;
  21816. return maxParallelFileOps;
  21817. }
  21818. return 20;
  21819. };
  21820. const getModuleContext = (config, context) => {
  21821. const configModuleContext = config.moduleContext;
  21822. if (typeof configModuleContext === 'function') {
  21823. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  21824. }
  21825. if (configModuleContext) {
  21826. const contextByModuleId = Object.create(null);
  21827. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21828. contextByModuleId[require$$0.resolve(key)] = moduleContext;
  21829. }
  21830. return id => contextByModuleId[id] || context;
  21831. }
  21832. return () => context;
  21833. };
  21834. const getPreserveEntrySignatures = (config, unsetOptions) => {
  21835. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  21836. if (configPreserveEntrySignatures == null) {
  21837. unsetOptions.add('preserveEntrySignatures');
  21838. }
  21839. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  21840. };
  21841. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  21842. const configPreserveModules = config.preserveModules;
  21843. if (configPreserveModules) {
  21844. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  21845. }
  21846. return configPreserveModules;
  21847. };
  21848. const getTreeshake = (config, warn, strictDeprecations) => {
  21849. const configTreeshake = config.treeshake;
  21850. if (configTreeshake === false) {
  21851. return false;
  21852. }
  21853. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
  21854. if (typeof configWithPreset.pureExternalModules !== 'undefined') {
  21855. 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);
  21856. }
  21857. return {
  21858. annotations: configWithPreset.annotations !== false,
  21859. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21860. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  21861. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  21862. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  21863. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21864. ? 'always'
  21865. : configWithPreset.propertyReadSideEffects !== false,
  21866. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21867. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21868. };
  21869. };
  21870. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  21871. if (typeof moduleSideEffectsOption === 'boolean') {
  21872. return () => moduleSideEffectsOption;
  21873. }
  21874. if (moduleSideEffectsOption === 'no-external') {
  21875. return (_id, external) => !external;
  21876. }
  21877. if (typeof moduleSideEffectsOption === 'function') {
  21878. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  21879. }
  21880. if (Array.isArray(moduleSideEffectsOption)) {
  21881. const ids = new Set(moduleSideEffectsOption);
  21882. return id => ids.has(id);
  21883. }
  21884. if (moduleSideEffectsOption) {
  21885. error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
  21886. }
  21887. const isPureExternalModule = getIdMatcher(pureExternalModules);
  21888. return (id, external) => !(external && isPureExternalModule(id));
  21889. };
  21890. // https://datatracker.ietf.org/doc/html/rfc2396
  21891. // eslint-disable-next-line no-control-regex
  21892. const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
  21893. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21894. function sanitizeFileName(name) {
  21895. const match = DRIVE_LETTER_REGEX.exec(name);
  21896. const driveLetter = match ? match[0] : '';
  21897. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21898. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21899. return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21900. }
  21901. function isValidUrl(url) {
  21902. try {
  21903. new URL(url);
  21904. }
  21905. catch (_) {
  21906. return false;
  21907. }
  21908. return true;
  21909. }
  21910. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21911. var _a, _b, _c, _d, _e, _f, _g;
  21912. // These are options that may trigger special warnings or behaviour later
  21913. // if the user did not select an explicit value
  21914. const unsetOptions = new Set(unsetInputOptions);
  21915. const compact = config.compact || false;
  21916. const format = getFormat(config);
  21917. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21918. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21919. const file = getFile(config, preserveModules, inputOptions);
  21920. const preferConst = getPreferConst(config, inputOptions);
  21921. const generatedCode = getGeneratedCode(config, preferConst);
  21922. const outputOptions = {
  21923. amd: getAmd(config),
  21924. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  21925. banner: getAddon(config, 'banner'),
  21926. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  21927. compact,
  21928. dir: getDir(config, file),
  21929. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  21930. entryFileNames: getEntryFileNames(config, unsetOptions),
  21931. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  21932. exports: getExports(config, unsetOptions),
  21933. extend: config.extend || false,
  21934. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  21935. file,
  21936. footer: getAddon(config, 'footer'),
  21937. format,
  21938. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  21939. generatedCode,
  21940. globals: config.globals || {},
  21941. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  21942. indent: getIndent(config, compact),
  21943. inlineDynamicImports,
  21944. interop: getInterop(config, inputOptions),
  21945. intro: getAddon(config, 'intro'),
  21946. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  21947. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21948. name: config.name,
  21949. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  21950. noConflict: config.noConflict || false,
  21951. outro: getAddon(config, 'outro'),
  21952. paths: config.paths || {},
  21953. plugins: ensureArray$1(config.plugins),
  21954. preferConst,
  21955. preserveModules,
  21956. preserveModulesRoot: getPreserveModulesRoot(config),
  21957. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21958. ? config.sanitizeFileName
  21959. : config.sanitizeFileName === false
  21960. ? id => id
  21961. : sanitizeFileName,
  21962. sourcemap: config.sourcemap || false,
  21963. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21964. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21965. sourcemapFile: config.sourcemapFile,
  21966. sourcemapPathTransform: config.sourcemapPathTransform,
  21967. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  21968. systemNullSetters: config.systemNullSetters || false,
  21969. validate: config.validate || false
  21970. };
  21971. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  21972. return { options: outputOptions, unsetOptions };
  21973. }
  21974. const getFile = (config, preserveModules, inputOptions) => {
  21975. const { file } = config;
  21976. if (typeof file === 'string') {
  21977. if (preserveModules) {
  21978. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21979. }
  21980. if (!Array.isArray(inputOptions.input))
  21981. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21982. }
  21983. return file;
  21984. };
  21985. const getFormat = (config) => {
  21986. const configFormat = config.format;
  21987. switch (configFormat) {
  21988. case undefined:
  21989. case 'es':
  21990. case 'esm':
  21991. case 'module':
  21992. return 'es';
  21993. case 'cjs':
  21994. case 'commonjs':
  21995. return 'cjs';
  21996. case 'system':
  21997. case 'systemjs':
  21998. return 'system';
  21999. case 'amd':
  22000. case 'iife':
  22001. case 'umd':
  22002. return configFormat;
  22003. default:
  22004. return error({
  22005. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  22006. url: `https://rollupjs.org/guide/en/#outputformat`
  22007. });
  22008. }
  22009. };
  22010. const getInlineDynamicImports = (config, inputOptions) => {
  22011. var _a;
  22012. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  22013. const { input } = inputOptions;
  22014. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  22015. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  22016. }
  22017. return inlineDynamicImports;
  22018. };
  22019. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  22020. var _a;
  22021. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  22022. if (preserveModules) {
  22023. if (inlineDynamicImports) {
  22024. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
  22025. }
  22026. if (inputOptions.preserveEntrySignatures === false) {
  22027. return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
  22028. }
  22029. }
  22030. return preserveModules;
  22031. };
  22032. const getPreferConst = (config, inputOptions) => {
  22033. const configPreferConst = config.preferConst;
  22034. if (configPreferConst != null) {
  22035. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
  22036. }
  22037. return !!configPreferConst;
  22038. };
  22039. const getPreserveModulesRoot = (config) => {
  22040. const { preserveModulesRoot } = config;
  22041. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22042. return undefined;
  22043. }
  22044. return require$$0.resolve(preserveModulesRoot);
  22045. };
  22046. const getAmd = (config) => {
  22047. const mergedOption = {
  22048. autoId: false,
  22049. basePath: '',
  22050. define: 'define',
  22051. forceJsExtensionForImports: false,
  22052. ...config.amd
  22053. };
  22054. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22055. return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  22056. }
  22057. if (mergedOption.basePath && !mergedOption.autoId) {
  22058. return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
  22059. }
  22060. let normalized;
  22061. if (mergedOption.autoId) {
  22062. normalized = {
  22063. autoId: true,
  22064. basePath: mergedOption.basePath,
  22065. define: mergedOption.define,
  22066. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22067. };
  22068. }
  22069. else {
  22070. normalized = {
  22071. autoId: false,
  22072. define: mergedOption.define,
  22073. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22074. id: mergedOption.id
  22075. };
  22076. }
  22077. return normalized;
  22078. };
  22079. const getAddon = (config, name) => {
  22080. const configAddon = config[name];
  22081. if (typeof configAddon === 'function') {
  22082. return configAddon;
  22083. }
  22084. return () => configAddon || '';
  22085. };
  22086. const getDir = (config, file) => {
  22087. const { dir } = config;
  22088. if (typeof dir === 'string' && typeof file === 'string') {
  22089. return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  22090. }
  22091. return dir;
  22092. };
  22093. const getDynamicImportFunction = (config, inputOptions) => {
  22094. const configDynamicImportFunction = config.dynamicImportFunction;
  22095. if (configDynamicImportFunction) {
  22096. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  22097. }
  22098. return configDynamicImportFunction;
  22099. };
  22100. const getEntryFileNames = (config, unsetOptions) => {
  22101. const configEntryFileNames = config.entryFileNames;
  22102. if (configEntryFileNames == null) {
  22103. unsetOptions.add('entryFileNames');
  22104. }
  22105. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  22106. };
  22107. function getExports(config, unsetOptions) {
  22108. const configExports = config.exports;
  22109. if (configExports == null) {
  22110. unsetOptions.add('exports');
  22111. }
  22112. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22113. return error(errInvalidExportOptionValue(configExports));
  22114. }
  22115. return configExports || 'auto';
  22116. }
  22117. const getGeneratedCode = (config, preferConst) => {
  22118. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
  22119. return {
  22120. arrowFunctions: configWithPreset.arrowFunctions === true,
  22121. constBindings: configWithPreset.constBindings === true || preferConst,
  22122. objectShorthand: configWithPreset.objectShorthand === true,
  22123. reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
  22124. symbols: configWithPreset.symbols === true
  22125. };
  22126. };
  22127. const getIndent = (config, compact) => {
  22128. if (compact) {
  22129. return '';
  22130. }
  22131. const configIndent = config.indent;
  22132. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  22133. };
  22134. const ALLOWED_INTEROP_TYPES = new Set([
  22135. 'auto',
  22136. 'esModule',
  22137. 'default',
  22138. 'defaultOnly',
  22139. true,
  22140. false
  22141. ]);
  22142. const getInterop = (config, inputOptions) => {
  22143. const configInterop = config.interop;
  22144. const validatedInteropTypes = new Set();
  22145. const validateInterop = (interop) => {
  22146. if (!validatedInteropTypes.has(interop)) {
  22147. validatedInteropTypes.add(interop);
  22148. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22149. return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22150. }
  22151. if (typeof interop === 'boolean') {
  22152. warnDeprecation({
  22153. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  22154. url: 'https://rollupjs.org/guide/en/#outputinterop'
  22155. }, false, inputOptions);
  22156. }
  22157. }
  22158. return interop;
  22159. };
  22160. if (typeof configInterop === 'function') {
  22161. const interopPerId = Object.create(null);
  22162. let defaultInterop = null;
  22163. return id => id === null
  22164. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22165. : id in interopPerId
  22166. ? interopPerId[id]
  22167. : validateInterop((interopPerId[id] = configInterop(id)));
  22168. }
  22169. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  22170. };
  22171. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  22172. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  22173. if (configManualChunks) {
  22174. if (inlineDynamicImports) {
  22175. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
  22176. }
  22177. if (preserveModules) {
  22178. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
  22179. }
  22180. }
  22181. return configManualChunks || {};
  22182. };
  22183. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  22184. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  22185. const configNamespaceToStringTag = config.namespaceToStringTag;
  22186. if (configNamespaceToStringTag != null) {
  22187. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
  22188. return configNamespaceToStringTag;
  22189. }
  22190. return generatedCode.symbols || false;
  22191. };
  22192. const getSourcemapBaseUrl = (config) => {
  22193. const { sourcemapBaseUrl } = config;
  22194. if (sourcemapBaseUrl) {
  22195. if (isValidUrl(sourcemapBaseUrl)) {
  22196. return sourcemapBaseUrl;
  22197. }
  22198. return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22199. }
  22200. };
  22201. function rollup(rawInputOptions) {
  22202. return rollupInternal(rawInputOptions, null);
  22203. }
  22204. async function rollupInternal(rawInputOptions, watcher) {
  22205. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22206. initialiseTimers(inputOptions);
  22207. const graph = new Graph(inputOptions, watcher);
  22208. // remove the cache option from the memory after graph creation (cache is not used anymore)
  22209. const useCache = rawInputOptions.cache !== false;
  22210. delete inputOptions.cache;
  22211. delete rawInputOptions.cache;
  22212. timeStart('BUILD', 1);
  22213. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22214. try {
  22215. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22216. await graph.build();
  22217. }
  22218. catch (err) {
  22219. const watchFiles = Object.keys(graph.watchFiles);
  22220. if (watchFiles.length > 0) {
  22221. err.watchFiles = watchFiles;
  22222. }
  22223. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  22224. await graph.pluginDriver.hookParallel('closeBundle', []);
  22225. throw err;
  22226. }
  22227. await graph.pluginDriver.hookParallel('buildEnd', []);
  22228. });
  22229. timeEnd('BUILD', 1);
  22230. const result = {
  22231. cache: useCache ? graph.getCache() : undefined,
  22232. async close() {
  22233. if (result.closed)
  22234. return;
  22235. result.closed = true;
  22236. await graph.pluginDriver.hookParallel('closeBundle', []);
  22237. },
  22238. closed: false,
  22239. async generate(rawOutputOptions) {
  22240. if (result.closed)
  22241. return error(errAlreadyClosed());
  22242. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22243. },
  22244. watchFiles: Object.keys(graph.watchFiles),
  22245. async write(rawOutputOptions) {
  22246. if (result.closed)
  22247. return error(errAlreadyClosed());
  22248. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22249. }
  22250. };
  22251. if (inputOptions.perf)
  22252. result.getTimings = getTimings;
  22253. return result;
  22254. }
  22255. async function getInputOptions(rawInputOptions, watchMode) {
  22256. if (!rawInputOptions) {
  22257. throw new Error('You must supply an options object to rollup');
  22258. }
  22259. const rawPlugins = getSortedValidatedPlugins('options', ensureArray$1(rawInputOptions.plugins));
  22260. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  22261. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22262. return { options, unsetOptions };
  22263. }
  22264. function applyOptionHook(watchMode) {
  22265. return async (inputOptions, plugin) => {
  22266. const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
  22267. return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  22268. };
  22269. }
  22270. function normalizePlugins(plugins, anonymousPrefix) {
  22271. plugins.forEach((plugin, index) => {
  22272. if (!plugin.name) {
  22273. plugin.name = `${anonymousPrefix}${index + 1}`;
  22274. }
  22275. });
  22276. }
  22277. function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22278. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22279. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22280. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22281. const generated = await bundle.generate(isWrite);
  22282. if (isWrite) {
  22283. if (!outputOptions.dir && !outputOptions.file) {
  22284. return error({
  22285. code: 'MISSING_OPTION',
  22286. message: 'You must specify "output.file" or "output.dir" for the build.'
  22287. });
  22288. }
  22289. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22290. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22291. }
  22292. return createOutput(generated);
  22293. });
  22294. }
  22295. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22296. if (!rawOutputOptions) {
  22297. throw new Error('You must supply an options object');
  22298. }
  22299. const rawPlugins = ensureArray$1(rawOutputOptions.plugins);
  22300. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22301. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22302. return {
  22303. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  22304. outputPluginDriver
  22305. };
  22306. }
  22307. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22308. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22309. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  22310. return {
  22311. ...pluginContext,
  22312. emitFile: emitError,
  22313. setAssetSource: emitError
  22314. };
  22315. }), inputOptions, unsetInputOptions);
  22316. }
  22317. function createOutput(outputBundle) {
  22318. return {
  22319. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22320. };
  22321. }
  22322. var SortingFileType;
  22323. (function (SortingFileType) {
  22324. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22325. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22326. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22327. })(SortingFileType || (SortingFileType = {}));
  22328. function getSortingFileType(file) {
  22329. if (file.type === 'asset') {
  22330. return SortingFileType.ASSET;
  22331. }
  22332. if (file.isEntry) {
  22333. return SortingFileType.ENTRY_CHUNK;
  22334. }
  22335. return SortingFileType.SECONDARY_CHUNK;
  22336. }
  22337. async function writeOutputFile(outputFile, outputOptions) {
  22338. const fileName = require$$0.resolve(outputOptions.dir || require$$0.dirname(outputOptions.file), outputFile.fileName);
  22339. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22340. await require$$0$1.promises.mkdir(require$$0.dirname(fileName), { recursive: true });
  22341. let writeSourceMapPromise;
  22342. let source;
  22343. if (outputFile.type === 'asset') {
  22344. source = outputFile.source;
  22345. }
  22346. else {
  22347. source = outputFile.code;
  22348. if (outputOptions.sourcemap && outputFile.map) {
  22349. let url;
  22350. if (outputOptions.sourcemap === 'inline') {
  22351. url = outputFile.map.toUrl();
  22352. }
  22353. else {
  22354. const { sourcemapBaseUrl } = outputOptions;
  22355. const sourcemapFileName = `${require$$0.basename(outputFile.fileName)}.map`;
  22356. url = sourcemapBaseUrl
  22357. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  22358. : sourcemapFileName;
  22359. writeSourceMapPromise = require$$0$1.promises.writeFile(`${fileName}.map`, outputFile.map.toString());
  22360. }
  22361. if (outputOptions.sourcemap !== 'hidden') {
  22362. source += `//# ${exports.SOURCEMAPPING_URL}=${url}\n`;
  22363. }
  22364. }
  22365. }
  22366. return Promise.all([require$$0$1.promises.writeFile(fileName, source), writeSourceMapPromise]);
  22367. }
  22368. /**
  22369. * Auxiliary function for defining rollup configuration
  22370. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  22371. * @param options
  22372. */
  22373. function defineConfig(options) {
  22374. return options;
  22375. }
  22376. class WatchEmitter extends require$$0$2.EventEmitter {
  22377. constructor() {
  22378. super();
  22379. this.awaitedHandlers = Object.create(null);
  22380. // Allows more than 10 bundles to be watched without
  22381. // showing the `MaxListenersExceededWarning` to the user.
  22382. this.setMaxListeners(Infinity);
  22383. }
  22384. // Will be overwritten by Rollup
  22385. async close() { }
  22386. emitAndAwait(event, ...args) {
  22387. this.emit(event, ...args);
  22388. return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
  22389. }
  22390. onCurrentAwaited(event, listener) {
  22391. this.getHandlers(event).push(listener);
  22392. return this;
  22393. }
  22394. removeAwaited() {
  22395. this.awaitedHandlers = {};
  22396. return this;
  22397. }
  22398. getHandlers(event) {
  22399. return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
  22400. }
  22401. }
  22402. function watch(configs) {
  22403. const emitter = new WatchEmitter();
  22404. const configArray = ensureArray$1(configs);
  22405. const watchConfigs = configArray.filter(config => config.watch !== false);
  22406. if (watchConfigs.length === 0) {
  22407. return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
  22408. }
  22409. loadFsEvents()
  22410. .then(() => Promise.resolve().then(() => require('./watch.js')))
  22411. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  22412. return emitter;
  22413. }
  22414. exports.commonjsGlobal = commonjsGlobal;
  22415. exports.createFilter = createFilter;
  22416. exports.defaultOnWarn = defaultOnWarn;
  22417. exports.defineConfig = defineConfig;
  22418. exports.ensureArray = ensureArray$1;
  22419. exports.error = error;
  22420. exports.fseventsImporter = fseventsImporter;
  22421. exports.generatedCodePresets = generatedCodePresets;
  22422. exports.getAliasName = getAliasName;
  22423. exports.getAugmentedNamespace = getAugmentedNamespace;
  22424. exports.getOrCreate = getOrCreate;
  22425. exports.loadFsEvents = loadFsEvents;
  22426. exports.objectifyOption = objectifyOption;
  22427. exports.objectifyOptionWithPresets = objectifyOptionWithPresets;
  22428. exports.picomatch = picomatch$1;
  22429. exports.printQuotedStringList = printQuotedStringList;
  22430. exports.relativeId = relativeId;
  22431. exports.rollup = rollup;
  22432. exports.rollupInternal = rollupInternal;
  22433. exports.treeshakePresets = treeshakePresets;
  22434. exports.version = version$1;
  22435. exports.warnUnknownOptions = warnUnknownOptions;
  22436. exports.watch = watch;
  22437. //# sourceMappingURL=rollup.js.map