rollup.js 782 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168
  1. /*
  2. @license
  3. Rollup.js v2.56.3
  4. Mon, 23 Aug 2021 05:06:39 GMT - commit c41d17ceedfa6c1d7430da70c6c80d86a91e9434
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. var path = require('path');
  10. var crypto = require('crypto');
  11. var fs = require('fs');
  12. var require$$0 = require('events');
  13. function _interopNamespaceDefaultOnly(e) {
  14. return {__proto__: null, 'default': e};
  15. }
  16. var version$1 = "2.56.3";
  17. function ensureArray(items) {
  18. if (Array.isArray(items)) {
  19. return items.filter(Boolean);
  20. }
  21. if (items) {
  22. return [items];
  23. }
  24. return [];
  25. }
  26. function getLocator$1(source, options) {
  27. if (options === void 0) { options = {}; }
  28. var offsetLine = options.offsetLine || 0;
  29. var offsetColumn = options.offsetColumn || 0;
  30. var originalLines = source.split('\n');
  31. var start = 0;
  32. var lineRanges = originalLines.map(function (line, i) {
  33. var end = start + line.length + 1;
  34. var range = { start: start, end: end, line: i };
  35. start = end;
  36. return range;
  37. });
  38. var i = 0;
  39. function rangeContains(range, index) {
  40. return range.start <= index && index < range.end;
  41. }
  42. function getLocation(range, index) {
  43. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  44. }
  45. function locate(search, startIndex) {
  46. if (typeof search === 'string') {
  47. search = source.indexOf(search, startIndex || 0);
  48. }
  49. var range = lineRanges[i];
  50. var d = search >= range.end ? 1 : -1;
  51. while (range) {
  52. if (rangeContains(range, search))
  53. return getLocation(range, search);
  54. i += d;
  55. range = lineRanges[i];
  56. }
  57. }
  58. return locate;
  59. }
  60. function locate(source, search, options) {
  61. if (typeof options === 'number') {
  62. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  63. }
  64. return getLocator$1(source, options)(search, options && options.startIndex);
  65. }
  66. function spaces(i) {
  67. let result = '';
  68. while (i--)
  69. result += ' ';
  70. return result;
  71. }
  72. function tabsToSpaces(str) {
  73. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  74. }
  75. function getCodeFrame(source, line, column) {
  76. let lines = source.split('\n');
  77. const frameStart = Math.max(0, line - 3);
  78. let frameEnd = Math.min(line + 2, lines.length);
  79. lines = lines.slice(frameStart, frameEnd);
  80. while (!/\S/.test(lines[lines.length - 1])) {
  81. lines.pop();
  82. frameEnd -= 1;
  83. }
  84. const digits = String(frameEnd).length;
  85. return lines
  86. .map((str, i) => {
  87. const isErrorLine = frameStart + i + 1 === line;
  88. let lineNum = String(i + frameStart + 1);
  89. while (lineNum.length < digits)
  90. lineNum = ` ${lineNum}`;
  91. if (isErrorLine) {
  92. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  93. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  94. }
  95. return `${lineNum}: ${tabsToSpaces(str)}`;
  96. })
  97. .join('\n');
  98. }
  99. function printQuotedStringList(list, verbs) {
  100. const isSingleItem = list.length <= 1;
  101. const quotedList = list.map(item => `"${item}"`);
  102. let output = isSingleItem
  103. ? quotedList[0]
  104. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  105. if (verbs) {
  106. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  107. }
  108. return output;
  109. }
  110. const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  111. const relativePath = /^\.?\.\//;
  112. function isAbsolute(path) {
  113. return absolutePath.test(path);
  114. }
  115. function isRelative(path) {
  116. return relativePath.test(path);
  117. }
  118. function normalize(path) {
  119. if (path.indexOf('\\') == -1)
  120. return path;
  121. return path.replace(/\\/g, '/');
  122. }
  123. function getAliasName(id) {
  124. const base = path.basename(id);
  125. return base.substr(0, base.length - path.extname(id).length);
  126. }
  127. function relativeId(id) {
  128. if (!isAbsolute(id))
  129. return id;
  130. return path.relative(path.resolve(), id);
  131. }
  132. function isPathFragment(name) {
  133. // starting with "/", "./", "../", "C:/"
  134. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  135. }
  136. function error(base) {
  137. if (!(base instanceof Error))
  138. base = Object.assign(new Error(base.message), base);
  139. throw base;
  140. }
  141. function augmentCodeLocation(props, pos, source, id) {
  142. if (typeof pos === 'object') {
  143. const { line, column } = pos;
  144. props.loc = { column, file: id, line };
  145. }
  146. else {
  147. props.pos = pos;
  148. const { line, column } = locate(source, pos, { offsetLine: 1 });
  149. props.loc = { column, file: id, line };
  150. }
  151. if (props.frame === undefined) {
  152. const { line, column } = props.loc;
  153. props.frame = getCodeFrame(source, line, column);
  154. }
  155. }
  156. var Errors;
  157. (function (Errors) {
  158. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  159. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  160. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  161. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  162. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  163. Errors["BAD_LOADER"] = "BAD_LOADER";
  164. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  165. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  166. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  167. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  168. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  169. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  170. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  171. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  172. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  173. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  174. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  175. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  176. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  177. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  178. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  179. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  180. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  181. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  182. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  183. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  184. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  185. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  186. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  187. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  188. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  189. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  190. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  191. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  192. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  193. })(Errors || (Errors = {}));
  194. function errAssetNotFinalisedForFileName(name) {
  195. return {
  196. code: Errors.ASSET_NOT_FINALISED,
  197. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  198. };
  199. }
  200. function errCannotEmitFromOptionsHook() {
  201. return {
  202. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  203. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  204. };
  205. }
  206. function errChunkNotGeneratedForFileName(name) {
  207. return {
  208. code: Errors.CHUNK_NOT_GENERATED,
  209. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  210. };
  211. }
  212. function errChunkInvalid({ fileName, code }, exception) {
  213. const errorProps = {
  214. code: Errors.CHUNK_INVALID,
  215. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  216. };
  217. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  218. return errorProps;
  219. }
  220. function errCircularReexport(exportName, importedModule) {
  221. return {
  222. code: Errors.CIRCULAR_REEXPORT,
  223. id: importedModule,
  224. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  225. };
  226. }
  227. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  228. return {
  229. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  230. exporter,
  231. importer,
  232. 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.`,
  233. reexporter
  234. };
  235. }
  236. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  237. return {
  238. code: Errors.ASSET_NOT_FOUND,
  239. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  240. };
  241. }
  242. function errAssetSourceAlreadySet(name) {
  243. return {
  244. code: Errors.ASSET_SOURCE_ALREADY_SET,
  245. message: `Unable to set the source for asset "${name}", source already set.`
  246. };
  247. }
  248. function errNoAssetSourceSet(assetName) {
  249. return {
  250. code: Errors.ASSET_SOURCE_MISSING,
  251. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  252. };
  253. }
  254. function errBadLoader(id) {
  255. return {
  256. code: Errors.BAD_LOADER,
  257. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  258. };
  259. }
  260. function errDeprecation(deprecation) {
  261. return {
  262. code: Errors.DEPRECATED_FEATURE,
  263. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  264. };
  265. }
  266. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  267. return {
  268. code: Errors.FILE_NOT_FOUND,
  269. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  270. };
  271. }
  272. function errFileNameConflict(fileName) {
  273. return {
  274. code: Errors.FILE_NAME_CONFLICT,
  275. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  276. };
  277. }
  278. function errInputHookInOutputPlugin(pluginName, hookName) {
  279. return {
  280. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  281. 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.`
  282. };
  283. }
  284. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  285. return {
  286. code: Errors.INVALID_CHUNK,
  287. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  288. };
  289. }
  290. function errInvalidExportOptionValue(optionValue) {
  291. return {
  292. code: Errors.INVALID_EXPORT_OPTION,
  293. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  294. url: `https://rollupjs.org/guide/en/#outputexports`
  295. };
  296. }
  297. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  298. return {
  299. code: 'INVALID_EXPORT_OPTION',
  300. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  301. };
  302. }
  303. function errInternalIdCannotBeExternal(source, importer) {
  304. return {
  305. code: Errors.INVALID_EXTERNAL_ID,
  306. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  307. };
  308. }
  309. function errInvalidOption(option, explanation) {
  310. return {
  311. code: Errors.INVALID_OPTION,
  312. message: `Invalid value for option "${option}" - ${explanation}.`
  313. };
  314. }
  315. function errInvalidRollupPhaseForAddWatchFile() {
  316. return {
  317. code: Errors.INVALID_ROLLUP_PHASE,
  318. message: `Cannot call addWatchFile after the build has finished.`
  319. };
  320. }
  321. function errInvalidRollupPhaseForChunkEmission() {
  322. return {
  323. code: Errors.INVALID_ROLLUP_PHASE,
  324. message: `Cannot emit chunks after module loading has finished.`
  325. };
  326. }
  327. function errMissingExport(exportName, importingModule, importedModule) {
  328. return {
  329. code: Errors.MISSING_EXPORT,
  330. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  331. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  332. };
  333. }
  334. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  335. return {
  336. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  337. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  338. };
  339. }
  340. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  341. return {
  342. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  343. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  344. };
  345. }
  346. function errImplicitDependantIsNotIncluded(module) {
  347. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  348. return {
  349. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  350. 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.`
  351. };
  352. }
  353. function errMixedExport(facadeModuleId, name) {
  354. return {
  355. code: Errors.MIXED_EXPORTS,
  356. id: facadeModuleId,
  357. 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`,
  358. url: `https://rollupjs.org/guide/en/#outputexports`
  359. };
  360. }
  361. function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
  362. return {
  363. code: Errors.NAMESPACE_CONFLICT,
  364. message: `Conflicting namespaces: "${relativeId(reexportingModule.id)}" re-exports "${name}" from both "${relativeId(reexportingModule.exportsAll[name])}" and "${relativeId(additionalExportAllModule.exportsAll[name])}" (will be ignored)`,
  365. name,
  366. reexporter: reexportingModule.id,
  367. sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
  368. };
  369. }
  370. function errAmbiguousExternalNamespaces(name, reexportingModule, usedExternalModule, externalModules) {
  371. return {
  372. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  373. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(externalModules.map(module => relativeId(module)))}, guessing "${relativeId(usedExternalModule)}".`,
  374. name,
  375. reexporter: reexportingModule,
  376. sources: externalModules
  377. };
  378. }
  379. function errNoTransformMapOrAstWithoutCode(pluginName) {
  380. return {
  381. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  382. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  383. 'a "code". This will be ignored.'
  384. };
  385. }
  386. function errPreferNamedExports(facadeModuleId) {
  387. const file = relativeId(facadeModuleId);
  388. return {
  389. code: Errors.PREFER_NAMED_EXPORTS,
  390. id: facadeModuleId,
  391. 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.`,
  392. url: `https://rollupjs.org/guide/en/#outputexports`
  393. };
  394. }
  395. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  396. return {
  397. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  398. id,
  399. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  400. ? `an export named "${syntheticNamedExportsOption}"`
  401. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  402. };
  403. }
  404. function errUnexpectedNamedImport(id, imported, isReexport) {
  405. const importType = isReexport ? 'reexport' : 'import';
  406. return {
  407. code: Errors.UNEXPECTED_NAMED_IMPORT,
  408. id,
  409. 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.`,
  410. url: 'https://rollupjs.org/guide/en/#outputinterop'
  411. };
  412. }
  413. function errUnexpectedNamespaceReexport(id) {
  414. return {
  415. code: Errors.UNEXPECTED_NAMED_IMPORT,
  416. id,
  417. 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.`,
  418. url: 'https://rollupjs.org/guide/en/#outputinterop'
  419. };
  420. }
  421. function errEntryCannotBeExternal(unresolvedId) {
  422. return {
  423. code: Errors.UNRESOLVED_ENTRY,
  424. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  425. };
  426. }
  427. function errUnresolvedEntry(unresolvedId) {
  428. return {
  429. code: Errors.UNRESOLVED_ENTRY,
  430. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  431. };
  432. }
  433. function errUnresolvedImport(source, importer) {
  434. return {
  435. code: Errors.UNRESOLVED_IMPORT,
  436. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  437. };
  438. }
  439. function errUnresolvedImportTreatedAsExternal(source, importer) {
  440. return {
  441. code: Errors.UNRESOLVED_IMPORT,
  442. importer: relativeId(importer),
  443. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  444. source,
  445. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  446. };
  447. }
  448. function errExternalSyntheticExports(source, importer) {
  449. return {
  450. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  451. importer: relativeId(importer),
  452. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  453. source
  454. };
  455. }
  456. function errFailedValidation(message) {
  457. return {
  458. code: Errors.VALIDATION_ERROR,
  459. message
  460. };
  461. }
  462. function errAlreadyClosed() {
  463. return {
  464. code: Errors.ALREADY_CLOSED,
  465. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  466. };
  467. }
  468. function warnDeprecation(deprecation, activeDeprecation, options) {
  469. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  470. }
  471. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  472. if (activeDeprecation || strictDeprecations) {
  473. const warning = errDeprecation(deprecation);
  474. if (strictDeprecations) {
  475. return error(warning);
  476. }
  477. warn(warning);
  478. }
  479. }
  480. const defaultOnWarn = warning => console.warn(warning.message || warning);
  481. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  482. const validOptionSet = new Set(validOptions);
  483. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  484. if (unknownOptions.length > 0) {
  485. warn({
  486. code: 'UNKNOWN_OPTION',
  487. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  488. ...validOptionSet
  489. ]
  490. .sort()
  491. .join(', ')}`
  492. });
  493. }
  494. }
  495. const treeshakePresets = {
  496. recommended: {
  497. annotations: true,
  498. correctVarValueBeforeDeclaration: false,
  499. moduleSideEffects: () => true,
  500. propertyReadSideEffects: true,
  501. tryCatchDeoptimization: true,
  502. unknownGlobalSideEffects: false
  503. },
  504. safest: {
  505. annotations: true,
  506. correctVarValueBeforeDeclaration: true,
  507. moduleSideEffects: () => true,
  508. propertyReadSideEffects: true,
  509. tryCatchDeoptimization: true,
  510. unknownGlobalSideEffects: true
  511. },
  512. smallest: {
  513. annotations: true,
  514. correctVarValueBeforeDeclaration: false,
  515. moduleSideEffects: () => false,
  516. propertyReadSideEffects: false,
  517. tryCatchDeoptimization: false,
  518. unknownGlobalSideEffects: false
  519. }
  520. };
  521. let fsEvents;
  522. let fsEventsImportError;
  523. function loadFsEvents() {
  524. return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespaceDefaultOnly(require('fsevents')); })
  525. .then(namespace => {
  526. fsEvents = namespace.default;
  527. })
  528. .catch(err => {
  529. fsEventsImportError = err;
  530. });
  531. }
  532. // A call to this function will be injected into the chokidar code
  533. function getFsEvents() {
  534. if (fsEventsImportError)
  535. throw fsEventsImportError;
  536. return fsEvents;
  537. }
  538. var fseventsImporter = {
  539. __proto__: null,
  540. loadFsEvents: loadFsEvents,
  541. getFsEvents: getFsEvents
  542. };
  543. var charToInteger = {};
  544. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  545. for (var i = 0; i < chars$1.length; i++) {
  546. charToInteger[chars$1.charCodeAt(i)] = i;
  547. }
  548. function decode(mappings) {
  549. var decoded = [];
  550. var line = [];
  551. var segment = [
  552. 0,
  553. 0,
  554. 0,
  555. 0,
  556. 0,
  557. ];
  558. var j = 0;
  559. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  560. var c = mappings.charCodeAt(i);
  561. if (c === 44) { // ","
  562. segmentify(line, segment, j);
  563. j = 0;
  564. }
  565. else if (c === 59) { // ";"
  566. segmentify(line, segment, j);
  567. j = 0;
  568. decoded.push(line);
  569. line = [];
  570. segment[0] = 0;
  571. }
  572. else {
  573. var integer = charToInteger[c];
  574. if (integer === undefined) {
  575. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  576. }
  577. var hasContinuationBit = integer & 32;
  578. integer &= 31;
  579. value += integer << shift;
  580. if (hasContinuationBit) {
  581. shift += 5;
  582. }
  583. else {
  584. var shouldNegate = value & 1;
  585. value >>>= 1;
  586. if (shouldNegate) {
  587. value = value === 0 ? -0x80000000 : -value;
  588. }
  589. segment[j] += value;
  590. j++;
  591. value = shift = 0; // reset
  592. }
  593. }
  594. }
  595. segmentify(line, segment, j);
  596. decoded.push(line);
  597. return decoded;
  598. }
  599. function segmentify(line, segment, j) {
  600. // This looks ugly, but we're creating specialized arrays with a specific
  601. // length. This is much faster than creating a new array (which v8 expands to
  602. // a capacity of 17 after pushing the first item), or slicing out a subarray
  603. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  604. // length 5 (since not everything will have an associated name), followed by
  605. // length 1 (it's probably rare for a source substring to not have an
  606. // associated segment data).
  607. if (j === 4)
  608. line.push([segment[0], segment[1], segment[2], segment[3]]);
  609. else if (j === 5)
  610. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  611. else if (j === 1)
  612. line.push([segment[0]]);
  613. }
  614. function encode(decoded) {
  615. var sourceFileIndex = 0; // second field
  616. var sourceCodeLine = 0; // third field
  617. var sourceCodeColumn = 0; // fourth field
  618. var nameIndex = 0; // fifth field
  619. var mappings = '';
  620. for (var i = 0; i < decoded.length; i++) {
  621. var line = decoded[i];
  622. if (i > 0)
  623. mappings += ';';
  624. if (line.length === 0)
  625. continue;
  626. var generatedCodeColumn = 0; // first field
  627. var lineMappings = [];
  628. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  629. var segment = line_1[_i];
  630. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  631. generatedCodeColumn = segment[0];
  632. if (segment.length > 1) {
  633. segmentMappings +=
  634. encodeInteger(segment[1] - sourceFileIndex) +
  635. encodeInteger(segment[2] - sourceCodeLine) +
  636. encodeInteger(segment[3] - sourceCodeColumn);
  637. sourceFileIndex = segment[1];
  638. sourceCodeLine = segment[2];
  639. sourceCodeColumn = segment[3];
  640. }
  641. if (segment.length === 5) {
  642. segmentMappings += encodeInteger(segment[4] - nameIndex);
  643. nameIndex = segment[4];
  644. }
  645. lineMappings.push(segmentMappings);
  646. }
  647. mappings += lineMappings.join(',');
  648. }
  649. return mappings;
  650. }
  651. function encodeInteger(num) {
  652. var result = '';
  653. num = num < 0 ? (-num << 1) | 1 : num << 1;
  654. do {
  655. var clamped = num & 31;
  656. num >>>= 5;
  657. if (num > 0) {
  658. clamped |= 32;
  659. }
  660. result += chars$1[clamped];
  661. } while (num > 0);
  662. return result;
  663. }
  664. var BitSet = function BitSet(arg) {
  665. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  666. };
  667. BitSet.prototype.add = function add (n) {
  668. this.bits[n >> 5] |= 1 << (n & 31);
  669. };
  670. BitSet.prototype.has = function has (n) {
  671. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  672. };
  673. var Chunk$1 = function Chunk(start, end, content) {
  674. this.start = start;
  675. this.end = end;
  676. this.original = content;
  677. this.intro = '';
  678. this.outro = '';
  679. this.content = content;
  680. this.storeName = false;
  681. this.edited = false;
  682. // we make these non-enumerable, for sanity while debugging
  683. Object.defineProperties(this, {
  684. previous: { writable: true, value: null },
  685. next: { writable: true, value: null }
  686. });
  687. };
  688. Chunk$1.prototype.appendLeft = function appendLeft (content) {
  689. this.outro += content;
  690. };
  691. Chunk$1.prototype.appendRight = function appendRight (content) {
  692. this.intro = this.intro + content;
  693. };
  694. Chunk$1.prototype.clone = function clone () {
  695. var chunk = new Chunk$1(this.start, this.end, this.original);
  696. chunk.intro = this.intro;
  697. chunk.outro = this.outro;
  698. chunk.content = this.content;
  699. chunk.storeName = this.storeName;
  700. chunk.edited = this.edited;
  701. return chunk;
  702. };
  703. Chunk$1.prototype.contains = function contains (index) {
  704. return this.start < index && index < this.end;
  705. };
  706. Chunk$1.prototype.eachNext = function eachNext (fn) {
  707. var chunk = this;
  708. while (chunk) {
  709. fn(chunk);
  710. chunk = chunk.next;
  711. }
  712. };
  713. Chunk$1.prototype.eachPrevious = function eachPrevious (fn) {
  714. var chunk = this;
  715. while (chunk) {
  716. fn(chunk);
  717. chunk = chunk.previous;
  718. }
  719. };
  720. Chunk$1.prototype.edit = function edit (content, storeName, contentOnly) {
  721. this.content = content;
  722. if (!contentOnly) {
  723. this.intro = '';
  724. this.outro = '';
  725. }
  726. this.storeName = storeName;
  727. this.edited = true;
  728. return this;
  729. };
  730. Chunk$1.prototype.prependLeft = function prependLeft (content) {
  731. this.outro = content + this.outro;
  732. };
  733. Chunk$1.prototype.prependRight = function prependRight (content) {
  734. this.intro = content + this.intro;
  735. };
  736. Chunk$1.prototype.split = function split (index) {
  737. var sliceIndex = index - this.start;
  738. var originalBefore = this.original.slice(0, sliceIndex);
  739. var originalAfter = this.original.slice(sliceIndex);
  740. this.original = originalBefore;
  741. var newChunk = new Chunk$1(index, this.end, originalAfter);
  742. newChunk.outro = this.outro;
  743. this.outro = '';
  744. this.end = index;
  745. if (this.edited) {
  746. // TODO is this block necessary?...
  747. newChunk.edit('', false);
  748. this.content = '';
  749. } else {
  750. this.content = originalBefore;
  751. }
  752. newChunk.next = this.next;
  753. if (newChunk.next) { newChunk.next.previous = newChunk; }
  754. newChunk.previous = this;
  755. this.next = newChunk;
  756. return newChunk;
  757. };
  758. Chunk$1.prototype.toString = function toString () {
  759. return this.intro + this.content + this.outro;
  760. };
  761. Chunk$1.prototype.trimEnd = function trimEnd (rx) {
  762. this.outro = this.outro.replace(rx, '');
  763. if (this.outro.length) { return true; }
  764. var trimmed = this.content.replace(rx, '');
  765. if (trimmed.length) {
  766. if (trimmed !== this.content) {
  767. this.split(this.start + trimmed.length).edit('', undefined, true);
  768. }
  769. return true;
  770. } else {
  771. this.edit('', undefined, true);
  772. this.intro = this.intro.replace(rx, '');
  773. if (this.intro.length) { return true; }
  774. }
  775. };
  776. Chunk$1.prototype.trimStart = function trimStart (rx) {
  777. this.intro = this.intro.replace(rx, '');
  778. if (this.intro.length) { return true; }
  779. var trimmed = this.content.replace(rx, '');
  780. if (trimmed.length) {
  781. if (trimmed !== this.content) {
  782. this.split(this.end - trimmed.length);
  783. this.edit('', undefined, true);
  784. }
  785. return true;
  786. } else {
  787. this.edit('', undefined, true);
  788. this.outro = this.outro.replace(rx, '');
  789. if (this.outro.length) { return true; }
  790. }
  791. };
  792. var btoa = function () {
  793. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  794. };
  795. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  796. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  797. } else if (typeof Buffer === 'function') {
  798. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  799. }
  800. var SourceMap = function SourceMap(properties) {
  801. this.version = 3;
  802. this.file = properties.file;
  803. this.sources = properties.sources;
  804. this.sourcesContent = properties.sourcesContent;
  805. this.names = properties.names;
  806. this.mappings = encode(properties.mappings);
  807. };
  808. SourceMap.prototype.toString = function toString () {
  809. return JSON.stringify(this);
  810. };
  811. SourceMap.prototype.toUrl = function toUrl () {
  812. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  813. };
  814. function guessIndent(code) {
  815. var lines = code.split('\n');
  816. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  817. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  818. if (tabbed.length === 0 && spaced.length === 0) {
  819. return null;
  820. }
  821. // More lines tabbed than spaced? Assume tabs, and
  822. // default to tabs in the case of a tie (or nothing
  823. // to go on)
  824. if (tabbed.length >= spaced.length) {
  825. return '\t';
  826. }
  827. // Otherwise, we need to guess the multiple
  828. var min = spaced.reduce(function (previous, current) {
  829. var numSpaces = /^ +/.exec(current)[0].length;
  830. return Math.min(numSpaces, previous);
  831. }, Infinity);
  832. return new Array(min + 1).join(' ');
  833. }
  834. function getRelativePath(from, to) {
  835. var fromParts = from.split(/[/\\]/);
  836. var toParts = to.split(/[/\\]/);
  837. fromParts.pop(); // get dirname
  838. while (fromParts[0] === toParts[0]) {
  839. fromParts.shift();
  840. toParts.shift();
  841. }
  842. if (fromParts.length) {
  843. var i = fromParts.length;
  844. while (i--) { fromParts[i] = '..'; }
  845. }
  846. return fromParts.concat(toParts).join('/');
  847. }
  848. var toString$1 = Object.prototype.toString;
  849. function isObject(thing) {
  850. return toString$1.call(thing) === '[object Object]';
  851. }
  852. function getLocator(source) {
  853. var originalLines = source.split('\n');
  854. var lineOffsets = [];
  855. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  856. lineOffsets.push(pos);
  857. pos += originalLines[i].length + 1;
  858. }
  859. return function locate(index) {
  860. var i = 0;
  861. var j = lineOffsets.length;
  862. while (i < j) {
  863. var m = (i + j) >> 1;
  864. if (index < lineOffsets[m]) {
  865. j = m;
  866. } else {
  867. i = m + 1;
  868. }
  869. }
  870. var line = i - 1;
  871. var column = index - lineOffsets[line];
  872. return { line: line, column: column };
  873. };
  874. }
  875. var Mappings = function Mappings(hires) {
  876. this.hires = hires;
  877. this.generatedCodeLine = 0;
  878. this.generatedCodeColumn = 0;
  879. this.raw = [];
  880. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  881. this.pending = null;
  882. };
  883. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  884. if (content.length) {
  885. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  886. if (nameIndex >= 0) {
  887. segment.push(nameIndex);
  888. }
  889. this.rawSegments.push(segment);
  890. } else if (this.pending) {
  891. this.rawSegments.push(this.pending);
  892. }
  893. this.advance(content);
  894. this.pending = null;
  895. };
  896. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  897. var originalCharIndex = chunk.start;
  898. var first = true;
  899. while (originalCharIndex < chunk.end) {
  900. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  901. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  902. }
  903. if (original[originalCharIndex] === '\n') {
  904. loc.line += 1;
  905. loc.column = 0;
  906. this.generatedCodeLine += 1;
  907. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  908. this.generatedCodeColumn = 0;
  909. first = true;
  910. } else {
  911. loc.column += 1;
  912. this.generatedCodeColumn += 1;
  913. first = false;
  914. }
  915. originalCharIndex += 1;
  916. }
  917. this.pending = null;
  918. };
  919. Mappings.prototype.advance = function advance (str) {
  920. if (!str) { return; }
  921. var lines = str.split('\n');
  922. if (lines.length > 1) {
  923. for (var i = 0; i < lines.length - 1; i++) {
  924. this.generatedCodeLine++;
  925. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  926. }
  927. this.generatedCodeColumn = 0;
  928. }
  929. this.generatedCodeColumn += lines[lines.length - 1].length;
  930. };
  931. var n = '\n';
  932. var warned = {
  933. insertLeft: false,
  934. insertRight: false,
  935. storeName: false
  936. };
  937. var MagicString = function MagicString(string, options) {
  938. if ( options === void 0 ) options = {};
  939. var chunk = new Chunk$1(0, string.length, string);
  940. Object.defineProperties(this, {
  941. original: { writable: true, value: string },
  942. outro: { writable: true, value: '' },
  943. intro: { writable: true, value: '' },
  944. firstChunk: { writable: true, value: chunk },
  945. lastChunk: { writable: true, value: chunk },
  946. lastSearchedChunk: { writable: true, value: chunk },
  947. byStart: { writable: true, value: {} },
  948. byEnd: { writable: true, value: {} },
  949. filename: { writable: true, value: options.filename },
  950. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  951. sourcemapLocations: { writable: true, value: new BitSet() },
  952. storedNames: { writable: true, value: {} },
  953. indentStr: { writable: true, value: guessIndent(string) }
  954. });
  955. this.byStart[0] = chunk;
  956. this.byEnd[string.length] = chunk;
  957. };
  958. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  959. this.sourcemapLocations.add(char);
  960. };
  961. MagicString.prototype.append = function append (content) {
  962. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  963. this.outro += content;
  964. return this;
  965. };
  966. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  967. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  968. this._split(index);
  969. var chunk = this.byEnd[index];
  970. if (chunk) {
  971. chunk.appendLeft(content);
  972. } else {
  973. this.intro += content;
  974. }
  975. return this;
  976. };
  977. MagicString.prototype.appendRight = function appendRight (index, content) {
  978. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  979. this._split(index);
  980. var chunk = this.byStart[index];
  981. if (chunk) {
  982. chunk.appendRight(content);
  983. } else {
  984. this.outro += content;
  985. }
  986. return this;
  987. };
  988. MagicString.prototype.clone = function clone () {
  989. var cloned = new MagicString(this.original, { filename: this.filename });
  990. var originalChunk = this.firstChunk;
  991. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  992. while (originalChunk) {
  993. cloned.byStart[clonedChunk.start] = clonedChunk;
  994. cloned.byEnd[clonedChunk.end] = clonedChunk;
  995. var nextOriginalChunk = originalChunk.next;
  996. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  997. if (nextClonedChunk) {
  998. clonedChunk.next = nextClonedChunk;
  999. nextClonedChunk.previous = clonedChunk;
  1000. clonedChunk = nextClonedChunk;
  1001. }
  1002. originalChunk = nextOriginalChunk;
  1003. }
  1004. cloned.lastChunk = clonedChunk;
  1005. if (this.indentExclusionRanges) {
  1006. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  1007. }
  1008. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  1009. cloned.intro = this.intro;
  1010. cloned.outro = this.outro;
  1011. return cloned;
  1012. };
  1013. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  1014. var this$1$1 = this;
  1015. options = options || {};
  1016. var sourceIndex = 0;
  1017. var names = Object.keys(this.storedNames);
  1018. var mappings = new Mappings(options.hires);
  1019. var locate = getLocator(this.original);
  1020. if (this.intro) {
  1021. mappings.advance(this.intro);
  1022. }
  1023. this.firstChunk.eachNext(function (chunk) {
  1024. var loc = locate(chunk.start);
  1025. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  1026. if (chunk.edited) {
  1027. mappings.addEdit(
  1028. sourceIndex,
  1029. chunk.content,
  1030. loc,
  1031. chunk.storeName ? names.indexOf(chunk.original) : -1
  1032. );
  1033. } else {
  1034. mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
  1035. }
  1036. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  1037. });
  1038. return {
  1039. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1040. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  1041. sourcesContent: options.includeContent ? [this.original] : [null],
  1042. names: names,
  1043. mappings: mappings.raw
  1044. };
  1045. };
  1046. MagicString.prototype.generateMap = function generateMap (options) {
  1047. return new SourceMap(this.generateDecodedMap(options));
  1048. };
  1049. MagicString.prototype.getIndentString = function getIndentString () {
  1050. return this.indentStr === null ? '\t' : this.indentStr;
  1051. };
  1052. MagicString.prototype.indent = function indent (indentStr, options) {
  1053. var pattern = /^[^\r\n]/gm;
  1054. if (isObject(indentStr)) {
  1055. options = indentStr;
  1056. indentStr = undefined;
  1057. }
  1058. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  1059. if (indentStr === '') { return this; } // noop
  1060. options = options || {};
  1061. // Process exclusion ranges
  1062. var isExcluded = {};
  1063. if (options.exclude) {
  1064. var exclusions =
  1065. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  1066. exclusions.forEach(function (exclusion) {
  1067. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  1068. isExcluded[i] = true;
  1069. }
  1070. });
  1071. }
  1072. var shouldIndentNextCharacter = options.indentStart !== false;
  1073. var replacer = function (match) {
  1074. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  1075. shouldIndentNextCharacter = true;
  1076. return match;
  1077. };
  1078. this.intro = this.intro.replace(pattern, replacer);
  1079. var charIndex = 0;
  1080. var chunk = this.firstChunk;
  1081. while (chunk) {
  1082. var end = chunk.end;
  1083. if (chunk.edited) {
  1084. if (!isExcluded[charIndex]) {
  1085. chunk.content = chunk.content.replace(pattern, replacer);
  1086. if (chunk.content.length) {
  1087. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  1088. }
  1089. }
  1090. } else {
  1091. charIndex = chunk.start;
  1092. while (charIndex < end) {
  1093. if (!isExcluded[charIndex]) {
  1094. var char = this.original[charIndex];
  1095. if (char === '\n') {
  1096. shouldIndentNextCharacter = true;
  1097. } else if (char !== '\r' && shouldIndentNextCharacter) {
  1098. shouldIndentNextCharacter = false;
  1099. if (charIndex === chunk.start) {
  1100. chunk.prependRight(indentStr);
  1101. } else {
  1102. this._splitChunk(chunk, charIndex);
  1103. chunk = chunk.next;
  1104. chunk.prependRight(indentStr);
  1105. }
  1106. }
  1107. }
  1108. charIndex += 1;
  1109. }
  1110. }
  1111. charIndex = chunk.end;
  1112. chunk = chunk.next;
  1113. }
  1114. this.outro = this.outro.replace(pattern, replacer);
  1115. return this;
  1116. };
  1117. MagicString.prototype.insert = function insert () {
  1118. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  1119. };
  1120. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  1121. if (!warned.insertLeft) {
  1122. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  1123. warned.insertLeft = true;
  1124. }
  1125. return this.appendLeft(index, content);
  1126. };
  1127. MagicString.prototype.insertRight = function insertRight (index, content) {
  1128. if (!warned.insertRight) {
  1129. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  1130. warned.insertRight = true;
  1131. }
  1132. return this.prependRight(index, content);
  1133. };
  1134. MagicString.prototype.move = function move (start, end, index) {
  1135. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  1136. this._split(start);
  1137. this._split(end);
  1138. this._split(index);
  1139. var first = this.byStart[start];
  1140. var last = this.byEnd[end];
  1141. var oldLeft = first.previous;
  1142. var oldRight = last.next;
  1143. var newRight = this.byStart[index];
  1144. if (!newRight && last === this.lastChunk) { return this; }
  1145. var newLeft = newRight ? newRight.previous : this.lastChunk;
  1146. if (oldLeft) { oldLeft.next = oldRight; }
  1147. if (oldRight) { oldRight.previous = oldLeft; }
  1148. if (newLeft) { newLeft.next = first; }
  1149. if (newRight) { newRight.previous = last; }
  1150. if (!first.previous) { this.firstChunk = last.next; }
  1151. if (!last.next) {
  1152. this.lastChunk = first.previous;
  1153. this.lastChunk.next = null;
  1154. }
  1155. first.previous = newLeft;
  1156. last.next = newRight || null;
  1157. if (!newLeft) { this.firstChunk = first; }
  1158. if (!newRight) { this.lastChunk = last; }
  1159. return this;
  1160. };
  1161. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  1162. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  1163. while (start < 0) { start += this.original.length; }
  1164. while (end < 0) { end += this.original.length; }
  1165. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  1166. if (start === end)
  1167. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  1168. this._split(start);
  1169. this._split(end);
  1170. if (options === true) {
  1171. if (!warned.storeName) {
  1172. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  1173. warned.storeName = true;
  1174. }
  1175. options = { storeName: true };
  1176. }
  1177. var storeName = options !== undefined ? options.storeName : false;
  1178. var contentOnly = options !== undefined ? options.contentOnly : false;
  1179. if (storeName) {
  1180. var original = this.original.slice(start, end);
  1181. this.storedNames[original] = true;
  1182. }
  1183. var first = this.byStart[start];
  1184. var last = this.byEnd[end];
  1185. if (first) {
  1186. if (end > first.end && first.next !== this.byStart[first.end]) {
  1187. throw new Error('Cannot overwrite across a split point');
  1188. }
  1189. first.edit(content, storeName, contentOnly);
  1190. if (first !== last) {
  1191. var chunk = first.next;
  1192. while (chunk !== last) {
  1193. chunk.edit('', false);
  1194. chunk = chunk.next;
  1195. }
  1196. chunk.edit('', false);
  1197. }
  1198. } else {
  1199. // must be inserting at the end
  1200. var newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  1201. // TODO last chunk in the array may not be the last chunk, if it's moved...
  1202. last.next = newChunk;
  1203. newChunk.previous = last;
  1204. }
  1205. return this;
  1206. };
  1207. MagicString.prototype.prepend = function prepend (content) {
  1208. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  1209. this.intro = content + this.intro;
  1210. return this;
  1211. };
  1212. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  1213. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  1214. this._split(index);
  1215. var chunk = this.byEnd[index];
  1216. if (chunk) {
  1217. chunk.prependLeft(content);
  1218. } else {
  1219. this.intro = content + this.intro;
  1220. }
  1221. return this;
  1222. };
  1223. MagicString.prototype.prependRight = function prependRight (index, content) {
  1224. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  1225. this._split(index);
  1226. var chunk = this.byStart[index];
  1227. if (chunk) {
  1228. chunk.prependRight(content);
  1229. } else {
  1230. this.outro = content + this.outro;
  1231. }
  1232. return this;
  1233. };
  1234. MagicString.prototype.remove = function remove (start, end) {
  1235. while (start < 0) { start += this.original.length; }
  1236. while (end < 0) { end += this.original.length; }
  1237. if (start === end) { return this; }
  1238. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  1239. if (start > end) { throw new Error('end must be greater than start'); }
  1240. this._split(start);
  1241. this._split(end);
  1242. var chunk = this.byStart[start];
  1243. while (chunk) {
  1244. chunk.intro = '';
  1245. chunk.outro = '';
  1246. chunk.edit('');
  1247. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  1248. }
  1249. return this;
  1250. };
  1251. MagicString.prototype.lastChar = function lastChar () {
  1252. if (this.outro.length)
  1253. { return this.outro[this.outro.length - 1]; }
  1254. var chunk = this.lastChunk;
  1255. do {
  1256. if (chunk.outro.length)
  1257. { return chunk.outro[chunk.outro.length - 1]; }
  1258. if (chunk.content.length)
  1259. { return chunk.content[chunk.content.length - 1]; }
  1260. if (chunk.intro.length)
  1261. { return chunk.intro[chunk.intro.length - 1]; }
  1262. } while (chunk = chunk.previous);
  1263. if (this.intro.length)
  1264. { return this.intro[this.intro.length - 1]; }
  1265. return '';
  1266. };
  1267. MagicString.prototype.lastLine = function lastLine () {
  1268. var lineIndex = this.outro.lastIndexOf(n);
  1269. if (lineIndex !== -1)
  1270. { return this.outro.substr(lineIndex + 1); }
  1271. var lineStr = this.outro;
  1272. var chunk = this.lastChunk;
  1273. do {
  1274. if (chunk.outro.length > 0) {
  1275. lineIndex = chunk.outro.lastIndexOf(n);
  1276. if (lineIndex !== -1)
  1277. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  1278. lineStr = chunk.outro + lineStr;
  1279. }
  1280. if (chunk.content.length > 0) {
  1281. lineIndex = chunk.content.lastIndexOf(n);
  1282. if (lineIndex !== -1)
  1283. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  1284. lineStr = chunk.content + lineStr;
  1285. }
  1286. if (chunk.intro.length > 0) {
  1287. lineIndex = chunk.intro.lastIndexOf(n);
  1288. if (lineIndex !== -1)
  1289. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  1290. lineStr = chunk.intro + lineStr;
  1291. }
  1292. } while (chunk = chunk.previous);
  1293. lineIndex = this.intro.lastIndexOf(n);
  1294. if (lineIndex !== -1)
  1295. { return this.intro.substr(lineIndex + 1) + lineStr; }
  1296. return this.intro + lineStr;
  1297. };
  1298. MagicString.prototype.slice = function slice (start, end) {
  1299. if ( start === void 0 ) start = 0;
  1300. if ( end === void 0 ) end = this.original.length;
  1301. while (start < 0) { start += this.original.length; }
  1302. while (end < 0) { end += this.original.length; }
  1303. var result = '';
  1304. // find start chunk
  1305. var chunk = this.firstChunk;
  1306. while (chunk && (chunk.start > start || chunk.end <= start)) {
  1307. // found end chunk before start
  1308. if (chunk.start < end && chunk.end >= end) {
  1309. return result;
  1310. }
  1311. chunk = chunk.next;
  1312. }
  1313. if (chunk && chunk.edited && chunk.start !== start)
  1314. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  1315. var startChunk = chunk;
  1316. while (chunk) {
  1317. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  1318. result += chunk.intro;
  1319. }
  1320. var containsEnd = chunk.start < end && chunk.end >= end;
  1321. if (containsEnd && chunk.edited && chunk.end !== end)
  1322. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  1323. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  1324. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  1325. result += chunk.content.slice(sliceStart, sliceEnd);
  1326. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  1327. result += chunk.outro;
  1328. }
  1329. if (containsEnd) {
  1330. break;
  1331. }
  1332. chunk = chunk.next;
  1333. }
  1334. return result;
  1335. };
  1336. // TODO deprecate this? not really very useful
  1337. MagicString.prototype.snip = function snip (start, end) {
  1338. var clone = this.clone();
  1339. clone.remove(0, start);
  1340. clone.remove(end, clone.original.length);
  1341. return clone;
  1342. };
  1343. MagicString.prototype._split = function _split (index) {
  1344. if (this.byStart[index] || this.byEnd[index]) { return; }
  1345. var chunk = this.lastSearchedChunk;
  1346. var searchForward = index > chunk.end;
  1347. while (chunk) {
  1348. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  1349. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1350. }
  1351. };
  1352. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  1353. if (chunk.edited && chunk.content.length) {
  1354. // zero-length edited chunks are a special case (overlapping replacements)
  1355. var loc = getLocator(this.original)(index);
  1356. throw new Error(
  1357. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  1358. );
  1359. }
  1360. var newChunk = chunk.split(index);
  1361. this.byEnd[index] = chunk;
  1362. this.byStart[index] = newChunk;
  1363. this.byEnd[newChunk.end] = newChunk;
  1364. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  1365. this.lastSearchedChunk = chunk;
  1366. return true;
  1367. };
  1368. MagicString.prototype.toString = function toString () {
  1369. var str = this.intro;
  1370. var chunk = this.firstChunk;
  1371. while (chunk) {
  1372. str += chunk.toString();
  1373. chunk = chunk.next;
  1374. }
  1375. return str + this.outro;
  1376. };
  1377. MagicString.prototype.isEmpty = function isEmpty () {
  1378. var chunk = this.firstChunk;
  1379. do {
  1380. if (chunk.intro.length && chunk.intro.trim() ||
  1381. chunk.content.length && chunk.content.trim() ||
  1382. chunk.outro.length && chunk.outro.trim())
  1383. { return false; }
  1384. } while (chunk = chunk.next);
  1385. return true;
  1386. };
  1387. MagicString.prototype.length = function length () {
  1388. var chunk = this.firstChunk;
  1389. var length = 0;
  1390. do {
  1391. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1392. } while (chunk = chunk.next);
  1393. return length;
  1394. };
  1395. MagicString.prototype.trimLines = function trimLines () {
  1396. return this.trim('[\\r\\n]');
  1397. };
  1398. MagicString.prototype.trim = function trim (charType) {
  1399. return this.trimStart(charType).trimEnd(charType);
  1400. };
  1401. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  1402. var rx = new RegExp((charType || '\\s') + '+$');
  1403. this.outro = this.outro.replace(rx, '');
  1404. if (this.outro.length) { return true; }
  1405. var chunk = this.lastChunk;
  1406. do {
  1407. var end = chunk.end;
  1408. var aborted = chunk.trimEnd(rx);
  1409. // if chunk was trimmed, we have a new lastChunk
  1410. if (chunk.end !== end) {
  1411. if (this.lastChunk === chunk) {
  1412. this.lastChunk = chunk.next;
  1413. }
  1414. this.byEnd[chunk.end] = chunk;
  1415. this.byStart[chunk.next.start] = chunk.next;
  1416. this.byEnd[chunk.next.end] = chunk.next;
  1417. }
  1418. if (aborted) { return true; }
  1419. chunk = chunk.previous;
  1420. } while (chunk);
  1421. return false;
  1422. };
  1423. MagicString.prototype.trimEnd = function trimEnd (charType) {
  1424. this.trimEndAborted(charType);
  1425. return this;
  1426. };
  1427. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  1428. var rx = new RegExp('^' + (charType || '\\s') + '+');
  1429. this.intro = this.intro.replace(rx, '');
  1430. if (this.intro.length) { return true; }
  1431. var chunk = this.firstChunk;
  1432. do {
  1433. var end = chunk.end;
  1434. var aborted = chunk.trimStart(rx);
  1435. if (chunk.end !== end) {
  1436. // special case...
  1437. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  1438. this.byEnd[chunk.end] = chunk;
  1439. this.byStart[chunk.next.start] = chunk.next;
  1440. this.byEnd[chunk.next.end] = chunk.next;
  1441. }
  1442. if (aborted) { return true; }
  1443. chunk = chunk.next;
  1444. } while (chunk);
  1445. return false;
  1446. };
  1447. MagicString.prototype.trimStart = function trimStart (charType) {
  1448. this.trimStartAborted(charType);
  1449. return this;
  1450. };
  1451. var hasOwnProp = Object.prototype.hasOwnProperty;
  1452. var Bundle$1 = function Bundle(options) {
  1453. if ( options === void 0 ) options = {};
  1454. this.intro = options.intro || '';
  1455. this.separator = options.separator !== undefined ? options.separator : '\n';
  1456. this.sources = [];
  1457. this.uniqueSources = [];
  1458. this.uniqueSourceIndexByFilename = {};
  1459. };
  1460. Bundle$1.prototype.addSource = function addSource (source) {
  1461. if (source instanceof MagicString) {
  1462. return this.addSource({
  1463. content: source,
  1464. filename: source.filename,
  1465. separator: this.separator
  1466. });
  1467. }
  1468. if (!isObject(source) || !source.content) {
  1469. throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
  1470. }
  1471. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  1472. if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
  1473. });
  1474. if (source.separator === undefined) {
  1475. // TODO there's a bunch of this sort of thing, needs cleaning up
  1476. source.separator = this.separator;
  1477. }
  1478. if (source.filename) {
  1479. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1480. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1481. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1482. } else {
  1483. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1484. if (source.content.original !== uniqueSource.content) {
  1485. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  1486. }
  1487. }
  1488. }
  1489. this.sources.push(source);
  1490. return this;
  1491. };
  1492. Bundle$1.prototype.append = function append (str, options) {
  1493. this.addSource({
  1494. content: new MagicString(str),
  1495. separator: (options && options.separator) || ''
  1496. });
  1497. return this;
  1498. };
  1499. Bundle$1.prototype.clone = function clone () {
  1500. var bundle = new Bundle$1({
  1501. intro: this.intro,
  1502. separator: this.separator
  1503. });
  1504. this.sources.forEach(function (source) {
  1505. bundle.addSource({
  1506. filename: source.filename,
  1507. content: source.content.clone(),
  1508. separator: source.separator
  1509. });
  1510. });
  1511. return bundle;
  1512. };
  1513. Bundle$1.prototype.generateDecodedMap = function generateDecodedMap (options) {
  1514. var this$1$1 = this;
  1515. if ( options === void 0 ) options = {};
  1516. var names = [];
  1517. this.sources.forEach(function (source) {
  1518. Object.keys(source.content.storedNames).forEach(function (name) {
  1519. if (!~names.indexOf(name)) { names.push(name); }
  1520. });
  1521. });
  1522. var mappings = new Mappings(options.hires);
  1523. if (this.intro) {
  1524. mappings.advance(this.intro);
  1525. }
  1526. this.sources.forEach(function (source, i) {
  1527. if (i > 0) {
  1528. mappings.advance(this$1$1.separator);
  1529. }
  1530. var sourceIndex = source.filename ? this$1$1.uniqueSourceIndexByFilename[source.filename] : -1;
  1531. var magicString = source.content;
  1532. var locate = getLocator(magicString.original);
  1533. if (magicString.intro) {
  1534. mappings.advance(magicString.intro);
  1535. }
  1536. magicString.firstChunk.eachNext(function (chunk) {
  1537. var loc = locate(chunk.start);
  1538. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  1539. if (source.filename) {
  1540. if (chunk.edited) {
  1541. mappings.addEdit(
  1542. sourceIndex,
  1543. chunk.content,
  1544. loc,
  1545. chunk.storeName ? names.indexOf(chunk.original) : -1
  1546. );
  1547. } else {
  1548. mappings.addUneditedChunk(
  1549. sourceIndex,
  1550. chunk,
  1551. magicString.original,
  1552. loc,
  1553. magicString.sourcemapLocations
  1554. );
  1555. }
  1556. } else {
  1557. mappings.advance(chunk.content);
  1558. }
  1559. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  1560. });
  1561. if (magicString.outro) {
  1562. mappings.advance(magicString.outro);
  1563. }
  1564. });
  1565. return {
  1566. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1567. sources: this.uniqueSources.map(function (source) {
  1568. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1569. }),
  1570. sourcesContent: this.uniqueSources.map(function (source) {
  1571. return options.includeContent ? source.content : null;
  1572. }),
  1573. names: names,
  1574. mappings: mappings.raw
  1575. };
  1576. };
  1577. Bundle$1.prototype.generateMap = function generateMap (options) {
  1578. return new SourceMap(this.generateDecodedMap(options));
  1579. };
  1580. Bundle$1.prototype.getIndentString = function getIndentString () {
  1581. var indentStringCounts = {};
  1582. this.sources.forEach(function (source) {
  1583. var indentStr = source.content.indentStr;
  1584. if (indentStr === null) { return; }
  1585. if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
  1586. indentStringCounts[indentStr] += 1;
  1587. });
  1588. return (
  1589. Object.keys(indentStringCounts).sort(function (a, b) {
  1590. return indentStringCounts[a] - indentStringCounts[b];
  1591. })[0] || '\t'
  1592. );
  1593. };
  1594. Bundle$1.prototype.indent = function indent (indentStr) {
  1595. var this$1$1 = this;
  1596. if (!arguments.length) {
  1597. indentStr = this.getIndentString();
  1598. }
  1599. if (indentStr === '') { return this; } // noop
  1600. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1601. this.sources.forEach(function (source, i) {
  1602. var separator = source.separator !== undefined ? source.separator : this$1$1.separator;
  1603. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1604. source.content.indent(indentStr, {
  1605. exclude: source.indentExclusionRanges,
  1606. indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1607. });
  1608. trailingNewline = source.content.lastChar() === '\n';
  1609. });
  1610. if (this.intro) {
  1611. this.intro =
  1612. indentStr +
  1613. this.intro.replace(/^[^\n]/gm, function (match, index) {
  1614. return index > 0 ? indentStr + match : match;
  1615. });
  1616. }
  1617. return this;
  1618. };
  1619. Bundle$1.prototype.prepend = function prepend (str) {
  1620. this.intro = str + this.intro;
  1621. return this;
  1622. };
  1623. Bundle$1.prototype.toString = function toString () {
  1624. var this$1$1 = this;
  1625. var body = this.sources
  1626. .map(function (source, i) {
  1627. var separator = source.separator !== undefined ? source.separator : this$1$1.separator;
  1628. var str = (i > 0 ? separator : '') + source.content.toString();
  1629. return str;
  1630. })
  1631. .join('');
  1632. return this.intro + body;
  1633. };
  1634. Bundle$1.prototype.isEmpty = function isEmpty () {
  1635. if (this.intro.length && this.intro.trim())
  1636. { return false; }
  1637. if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
  1638. { return false; }
  1639. return true;
  1640. };
  1641. Bundle$1.prototype.length = function length () {
  1642. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  1643. };
  1644. Bundle$1.prototype.trimLines = function trimLines () {
  1645. return this.trim('[\\r\\n]');
  1646. };
  1647. Bundle$1.prototype.trim = function trim (charType) {
  1648. return this.trimStart(charType).trimEnd(charType);
  1649. };
  1650. Bundle$1.prototype.trimStart = function trimStart (charType) {
  1651. var rx = new RegExp('^' + (charType || '\\s') + '+');
  1652. this.intro = this.intro.replace(rx, '');
  1653. if (!this.intro) {
  1654. var source;
  1655. var i = 0;
  1656. do {
  1657. source = this.sources[i++];
  1658. if (!source) {
  1659. break;
  1660. }
  1661. } while (!source.content.trimStartAborted(charType));
  1662. }
  1663. return this;
  1664. };
  1665. Bundle$1.prototype.trimEnd = function trimEnd (charType) {
  1666. var rx = new RegExp((charType || '\\s') + '+$');
  1667. var source;
  1668. var i = this.sources.length - 1;
  1669. do {
  1670. source = this.sources[i--];
  1671. if (!source) {
  1672. this.intro = this.intro.replace(rx, '');
  1673. break;
  1674. }
  1675. } while (!source.content.trimEndAborted(charType));
  1676. return this;
  1677. };
  1678. var MagicString$1 = MagicString;
  1679. function relative(from, to) {
  1680. const fromParts = from.split(/[/\\]/).filter(Boolean);
  1681. const toParts = to.split(/[/\\]/).filter(Boolean);
  1682. if (fromParts[0] === '.')
  1683. fromParts.shift();
  1684. if (toParts[0] === '.')
  1685. toParts.shift();
  1686. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1687. fromParts.shift();
  1688. toParts.shift();
  1689. }
  1690. while (toParts[0] === '..' && fromParts.length > 0) {
  1691. toParts.shift();
  1692. fromParts.pop();
  1693. }
  1694. while (fromParts.pop()) {
  1695. toParts.unshift('..');
  1696. }
  1697. return toParts.join('/');
  1698. }
  1699. const RESERVED_NAMES = {
  1700. __proto__: null,
  1701. await: true,
  1702. break: true,
  1703. case: true,
  1704. catch: true,
  1705. class: true,
  1706. const: true,
  1707. continue: true,
  1708. debugger: true,
  1709. default: true,
  1710. delete: true,
  1711. do: true,
  1712. else: true,
  1713. enum: true,
  1714. eval: true,
  1715. export: true,
  1716. extends: true,
  1717. false: true,
  1718. finally: true,
  1719. for: true,
  1720. function: true,
  1721. if: true,
  1722. implements: true,
  1723. import: true,
  1724. in: true,
  1725. instanceof: true,
  1726. interface: true,
  1727. let: true,
  1728. new: true,
  1729. null: true,
  1730. package: true,
  1731. private: true,
  1732. protected: true,
  1733. public: true,
  1734. return: true,
  1735. static: true,
  1736. super: true,
  1737. switch: true,
  1738. this: true,
  1739. throw: true,
  1740. true: true,
  1741. try: true,
  1742. typeof: true,
  1743. undefined: true,
  1744. var: true,
  1745. void: true,
  1746. while: true,
  1747. with: true,
  1748. yield: true
  1749. };
  1750. function getOrCreate(map, key, init) {
  1751. const existing = map.get(key);
  1752. if (existing) {
  1753. return existing;
  1754. }
  1755. const value = init();
  1756. map.set(key, value);
  1757. return value;
  1758. }
  1759. const UnknownKey = Symbol('Unknown Key');
  1760. const UnknownInteger = Symbol('Unknown Integer');
  1761. const EMPTY_PATH = [];
  1762. const UNKNOWN_PATH = [UnknownKey];
  1763. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1764. const EntitiesKey = Symbol('Entities');
  1765. class PathTracker {
  1766. constructor() {
  1767. this.entityPaths = Object.create(null, {
  1768. [EntitiesKey]: { value: new Set() }
  1769. });
  1770. }
  1771. trackEntityAtPathAndGetIfTracked(path, entity) {
  1772. const trackedEntities = this.getEntities(path);
  1773. if (trackedEntities.has(entity))
  1774. return true;
  1775. trackedEntities.add(entity);
  1776. return false;
  1777. }
  1778. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1779. const trackedEntities = this.getEntities(path);
  1780. if (trackedEntities.has(entity))
  1781. return returnIfTracked;
  1782. trackedEntities.add(entity);
  1783. const result = onUntracked();
  1784. trackedEntities.delete(entity);
  1785. return result;
  1786. }
  1787. getEntities(path) {
  1788. let currentPaths = this.entityPaths;
  1789. for (const pathSegment of path) {
  1790. currentPaths = currentPaths[pathSegment] =
  1791. currentPaths[pathSegment] ||
  1792. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1793. }
  1794. return currentPaths[EntitiesKey];
  1795. }
  1796. }
  1797. const SHARED_RECURSION_TRACKER = new PathTracker();
  1798. class DiscriminatedPathTracker {
  1799. constructor() {
  1800. this.entityPaths = Object.create(null, {
  1801. [EntitiesKey]: { value: new Map() }
  1802. });
  1803. }
  1804. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1805. let currentPaths = this.entityPaths;
  1806. for (const pathSegment of path) {
  1807. currentPaths = currentPaths[pathSegment] =
  1808. currentPaths[pathSegment] ||
  1809. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1810. }
  1811. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1812. if (trackedEntities.has(entity))
  1813. return true;
  1814. trackedEntities.add(entity);
  1815. return false;
  1816. }
  1817. }
  1818. const UnknownValue = Symbol('Unknown Value');
  1819. class ExpressionEntity {
  1820. constructor() {
  1821. this.included = false;
  1822. }
  1823. deoptimizePath(_path) { }
  1824. deoptimizeThisOnEventAtPath(_event, _path, thisParameter, _recursionTracker) {
  1825. thisParameter.deoptimizePath(UNKNOWN_PATH);
  1826. }
  1827. /**
  1828. * If possible it returns a stringifyable literal value for this node that can be used
  1829. * for inlining or comparing values.
  1830. * Otherwise it should return UnknownValue.
  1831. */
  1832. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1833. return UnknownValue;
  1834. }
  1835. getReturnExpressionWhenCalledAtPath(_path, _callOptions, _recursionTracker, _origin) {
  1836. return UNKNOWN_EXPRESSION;
  1837. }
  1838. hasEffectsWhenAccessedAtPath(_path, _context) {
  1839. return true;
  1840. }
  1841. hasEffectsWhenAssignedAtPath(_path, _context) {
  1842. return true;
  1843. }
  1844. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  1845. return true;
  1846. }
  1847. include(_context, _includeChildrenRecursively) {
  1848. this.included = true;
  1849. }
  1850. includeCallArguments(context, args) {
  1851. for (const arg of args) {
  1852. arg.include(context, false);
  1853. }
  1854. }
  1855. }
  1856. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1857. })();
  1858. class Variable extends ExpressionEntity {
  1859. constructor(name) {
  1860. super();
  1861. this.name = name;
  1862. this.alwaysRendered = false;
  1863. this.initReached = false;
  1864. this.isId = false;
  1865. this.isReassigned = false;
  1866. this.kind = null;
  1867. this.renderBaseName = null;
  1868. this.renderName = null;
  1869. }
  1870. /**
  1871. * Binds identifiers that reference this variable to this variable.
  1872. * Necessary to be able to change variable names.
  1873. */
  1874. addReference(_identifier) { }
  1875. getBaseVariableName() {
  1876. return this.renderBaseName || this.renderName || this.name;
  1877. }
  1878. getName() {
  1879. const name = this.renderName || this.name;
  1880. return this.renderBaseName
  1881. ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
  1882. : name;
  1883. }
  1884. hasEffectsWhenAccessedAtPath(path, _context) {
  1885. return path.length > 0;
  1886. }
  1887. /**
  1888. * Marks this variable as being part of the bundle, which is usually the case when one of
  1889. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1890. * previously.
  1891. * Once a variable is included, it should take care all its declarations are included.
  1892. */
  1893. include() {
  1894. this.included = true;
  1895. }
  1896. markCalledFromTryStatement() { }
  1897. setRenderNames(baseName, name) {
  1898. this.renderBaseName = baseName;
  1899. this.renderName = name;
  1900. }
  1901. }
  1902. class ExternalVariable extends Variable {
  1903. constructor(module, name) {
  1904. super(name);
  1905. this.module = module;
  1906. this.isNamespace = name === '*';
  1907. this.referenced = false;
  1908. }
  1909. addReference(identifier) {
  1910. this.referenced = true;
  1911. if (this.name === 'default' || this.name === '*') {
  1912. this.module.suggestName(identifier.name);
  1913. }
  1914. }
  1915. hasEffectsWhenAccessedAtPath(path) {
  1916. return path.length > (this.isNamespace ? 1 : 0);
  1917. }
  1918. include() {
  1919. if (!this.included) {
  1920. this.included = true;
  1921. this.module.used = true;
  1922. }
  1923. }
  1924. }
  1925. const BLANK = Object.freeze(Object.create(null));
  1926. const EMPTY_OBJECT = Object.freeze({});
  1927. const EMPTY_ARRAY = Object.freeze([]);
  1928. 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'.split(' ');
  1929. const builtins$1 = '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'.split(' ');
  1930. const blacklisted = new Set(reservedWords$1.concat(builtins$1));
  1931. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  1932. const startsWithDigit = (str) => /\d/.test(str[0]);
  1933. function isLegal(str) {
  1934. if (startsWithDigit(str) || blacklisted.has(str)) {
  1935. return false;
  1936. }
  1937. return !illegalCharacters.test(str);
  1938. }
  1939. function makeLegal(str) {
  1940. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  1941. if (startsWithDigit(str) || blacklisted.has(str))
  1942. str = `_${str}`;
  1943. return str || '_';
  1944. }
  1945. class ExternalModule {
  1946. constructor(options, id, hasModuleSideEffects, meta, renormalizeRenderPath) {
  1947. this.options = options;
  1948. this.id = id;
  1949. this.renormalizeRenderPath = renormalizeRenderPath;
  1950. this.defaultVariableName = '';
  1951. this.dynamicImporters = [];
  1952. this.importers = [];
  1953. this.mostCommonSuggestion = 0;
  1954. this.namespaceVariableName = '';
  1955. this.reexported = false;
  1956. this.renderPath = undefined;
  1957. this.used = false;
  1958. this.variableName = '';
  1959. this.execIndex = Infinity;
  1960. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  1961. this.nameSuggestions = Object.create(null);
  1962. this.declarations = Object.create(null);
  1963. this.exportedVariables = new Map();
  1964. const { importers, dynamicImporters } = this;
  1965. this.info = {
  1966. ast: null,
  1967. code: null,
  1968. dynamicallyImportedIds: EMPTY_ARRAY,
  1969. get dynamicImporters() {
  1970. return dynamicImporters.sort();
  1971. },
  1972. hasModuleSideEffects,
  1973. id,
  1974. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  1975. implicitlyLoadedBefore: EMPTY_ARRAY,
  1976. importedIds: EMPTY_ARRAY,
  1977. get importers() {
  1978. return importers.sort();
  1979. },
  1980. isEntry: false,
  1981. isExternal: true,
  1982. meta,
  1983. syntheticNamedExports: false
  1984. };
  1985. }
  1986. getVariableForExportName(name) {
  1987. let declaration = this.declarations[name];
  1988. if (declaration)
  1989. return declaration;
  1990. this.declarations[name] = declaration = new ExternalVariable(this, name);
  1991. this.exportedVariables.set(declaration, name);
  1992. return declaration;
  1993. }
  1994. setRenderPath(options, inputBase) {
  1995. this.renderPath =
  1996. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  1997. if (!this.renderPath) {
  1998. this.renderPath = this.renormalizeRenderPath
  1999. ? normalize(path.relative(inputBase, this.id))
  2000. : this.id;
  2001. }
  2002. return this.renderPath;
  2003. }
  2004. suggestName(name) {
  2005. if (!this.nameSuggestions[name])
  2006. this.nameSuggestions[name] = 0;
  2007. this.nameSuggestions[name] += 1;
  2008. if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
  2009. this.mostCommonSuggestion = this.nameSuggestions[name];
  2010. this.suggestedVariableName = name;
  2011. }
  2012. }
  2013. warnUnusedImports() {
  2014. const unused = Object.keys(this.declarations).filter(name => {
  2015. if (name === '*')
  2016. return false;
  2017. const declaration = this.declarations[name];
  2018. return !declaration.included && !this.reexported && !declaration.referenced;
  2019. });
  2020. if (unused.length === 0)
  2021. return;
  2022. const importersSet = new Set();
  2023. for (const name of unused) {
  2024. const { importers } = this.declarations[name].module;
  2025. for (const importer of importers) {
  2026. importersSet.add(importer);
  2027. }
  2028. }
  2029. const importersArray = [...importersSet];
  2030. this.options.onwarn({
  2031. code: 'UNUSED_EXTERNAL_IMPORT',
  2032. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  2033. names: unused,
  2034. source: this.id,
  2035. sources: importersArray
  2036. });
  2037. }
  2038. }
  2039. const extractors = {
  2040. ArrayPattern(names, param) {
  2041. for (const element of param.elements) {
  2042. if (element)
  2043. extractors[element.type](names, element);
  2044. }
  2045. },
  2046. AssignmentPattern(names, param) {
  2047. extractors[param.left.type](names, param.left);
  2048. },
  2049. Identifier(names, param) {
  2050. names.push(param.name);
  2051. },
  2052. MemberExpression() { },
  2053. ObjectPattern(names, param) {
  2054. for (const prop of param.properties) {
  2055. if (prop.type === 'RestElement') {
  2056. extractors.RestElement(names, prop);
  2057. }
  2058. else {
  2059. extractors[prop.value.type](names, prop.value);
  2060. }
  2061. }
  2062. },
  2063. RestElement(names, param) {
  2064. extractors[param.argument.type](names, param.argument);
  2065. }
  2066. };
  2067. const extractAssignedNames = function extractAssignedNames(param) {
  2068. const names = [];
  2069. extractors[param.type](names, param);
  2070. return names;
  2071. };
  2072. const BROKEN_FLOW_NONE = 0;
  2073. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  2074. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  2075. function createInclusionContext() {
  2076. return {
  2077. brokenFlow: BROKEN_FLOW_NONE,
  2078. includedCallArguments: new Set(),
  2079. includedLabels: new Set()
  2080. };
  2081. }
  2082. function createHasEffectsContext() {
  2083. return {
  2084. accessed: new PathTracker(),
  2085. assigned: new PathTracker(),
  2086. brokenFlow: BROKEN_FLOW_NONE,
  2087. called: new DiscriminatedPathTracker(),
  2088. ignore: {
  2089. breaks: false,
  2090. continues: false,
  2091. labels: new Set(),
  2092. returnYield: false
  2093. },
  2094. includedLabels: new Set(),
  2095. instantiated: new DiscriminatedPathTracker(),
  2096. replacedVariableInits: new Map()
  2097. };
  2098. }
  2099. // AST walker module for Mozilla Parser API compatible trees
  2100. function skipThrough(node, st, c) { c(node, st); }
  2101. function ignore(_node, _st, _c) {}
  2102. // Node walkers.
  2103. var base$1 = {};
  2104. base$1.Program = base$1.BlockStatement = function (node, st, c) {
  2105. for (var i = 0, list = node.body; i < list.length; i += 1)
  2106. {
  2107. var stmt = list[i];
  2108. c(stmt, st, "Statement");
  2109. }
  2110. };
  2111. base$1.Statement = skipThrough;
  2112. base$1.EmptyStatement = ignore;
  2113. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  2114. function (node, st, c) { return c(node.expression, st, "Expression"); };
  2115. base$1.IfStatement = function (node, st, c) {
  2116. c(node.test, st, "Expression");
  2117. c(node.consequent, st, "Statement");
  2118. if (node.alternate) { c(node.alternate, st, "Statement"); }
  2119. };
  2120. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  2121. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  2122. base$1.WithStatement = function (node, st, c) {
  2123. c(node.object, st, "Expression");
  2124. c(node.body, st, "Statement");
  2125. };
  2126. base$1.SwitchStatement = function (node, st, c) {
  2127. c(node.discriminant, st, "Expression");
  2128. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  2129. var cs = list$1[i$1];
  2130. if (cs.test) { c(cs.test, st, "Expression"); }
  2131. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  2132. {
  2133. var cons = list[i];
  2134. c(cons, st, "Statement");
  2135. }
  2136. }
  2137. };
  2138. base$1.SwitchCase = function (node, st, c) {
  2139. if (node.test) { c(node.test, st, "Expression"); }
  2140. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  2141. {
  2142. var cons = list[i];
  2143. c(cons, st, "Statement");
  2144. }
  2145. };
  2146. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  2147. if (node.argument) { c(node.argument, st, "Expression"); }
  2148. };
  2149. base$1.ThrowStatement = base$1.SpreadElement =
  2150. function (node, st, c) { return c(node.argument, st, "Expression"); };
  2151. base$1.TryStatement = function (node, st, c) {
  2152. c(node.block, st, "Statement");
  2153. if (node.handler) { c(node.handler, st); }
  2154. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  2155. };
  2156. base$1.CatchClause = function (node, st, c) {
  2157. if (node.param) { c(node.param, st, "Pattern"); }
  2158. c(node.body, st, "Statement");
  2159. };
  2160. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  2161. c(node.test, st, "Expression");
  2162. c(node.body, st, "Statement");
  2163. };
  2164. base$1.ForStatement = function (node, st, c) {
  2165. if (node.init) { c(node.init, st, "ForInit"); }
  2166. if (node.test) { c(node.test, st, "Expression"); }
  2167. if (node.update) { c(node.update, st, "Expression"); }
  2168. c(node.body, st, "Statement");
  2169. };
  2170. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  2171. c(node.left, st, "ForInit");
  2172. c(node.right, st, "Expression");
  2173. c(node.body, st, "Statement");
  2174. };
  2175. base$1.ForInit = function (node, st, c) {
  2176. if (node.type === "VariableDeclaration") { c(node, st); }
  2177. else { c(node, st, "Expression"); }
  2178. };
  2179. base$1.DebuggerStatement = ignore;
  2180. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  2181. base$1.VariableDeclaration = function (node, st, c) {
  2182. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  2183. {
  2184. var decl = list[i];
  2185. c(decl, st);
  2186. }
  2187. };
  2188. base$1.VariableDeclarator = function (node, st, c) {
  2189. c(node.id, st, "Pattern");
  2190. if (node.init) { c(node.init, st, "Expression"); }
  2191. };
  2192. base$1.Function = function (node, st, c) {
  2193. if (node.id) { c(node.id, st, "Pattern"); }
  2194. for (var i = 0, list = node.params; i < list.length; i += 1)
  2195. {
  2196. var param = list[i];
  2197. c(param, st, "Pattern");
  2198. }
  2199. c(node.body, st, node.expression ? "Expression" : "Statement");
  2200. };
  2201. base$1.Pattern = function (node, st, c) {
  2202. if (node.type === "Identifier")
  2203. { c(node, st, "VariablePattern"); }
  2204. else if (node.type === "MemberExpression")
  2205. { c(node, st, "MemberPattern"); }
  2206. else
  2207. { c(node, st); }
  2208. };
  2209. base$1.VariablePattern = ignore;
  2210. base$1.MemberPattern = skipThrough;
  2211. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  2212. base$1.ArrayPattern = function (node, st, c) {
  2213. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  2214. var elt = list[i];
  2215. if (elt) { c(elt, st, "Pattern"); }
  2216. }
  2217. };
  2218. base$1.ObjectPattern = function (node, st, c) {
  2219. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  2220. var prop = list[i];
  2221. if (prop.type === "Property") {
  2222. if (prop.computed) { c(prop.key, st, "Expression"); }
  2223. c(prop.value, st, "Pattern");
  2224. } else if (prop.type === "RestElement") {
  2225. c(prop.argument, st, "Pattern");
  2226. }
  2227. }
  2228. };
  2229. base$1.Expression = skipThrough;
  2230. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  2231. base$1.ArrayExpression = function (node, st, c) {
  2232. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  2233. var elt = list[i];
  2234. if (elt) { c(elt, st, "Expression"); }
  2235. }
  2236. };
  2237. base$1.ObjectExpression = function (node, st, c) {
  2238. for (var i = 0, list = node.properties; i < list.length; i += 1)
  2239. {
  2240. var prop = list[i];
  2241. c(prop, st);
  2242. }
  2243. };
  2244. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  2245. base$1.SequenceExpression = function (node, st, c) {
  2246. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  2247. {
  2248. var expr = list[i];
  2249. c(expr, st, "Expression");
  2250. }
  2251. };
  2252. base$1.TemplateLiteral = function (node, st, c) {
  2253. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  2254. {
  2255. var quasi = list[i];
  2256. c(quasi, st);
  2257. }
  2258. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  2259. {
  2260. var expr = list$1[i$1];
  2261. c(expr, st, "Expression");
  2262. }
  2263. };
  2264. base$1.TemplateElement = ignore;
  2265. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  2266. c(node.argument, st, "Expression");
  2267. };
  2268. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  2269. c(node.left, st, "Expression");
  2270. c(node.right, st, "Expression");
  2271. };
  2272. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  2273. c(node.left, st, "Pattern");
  2274. c(node.right, st, "Expression");
  2275. };
  2276. base$1.ConditionalExpression = function (node, st, c) {
  2277. c(node.test, st, "Expression");
  2278. c(node.consequent, st, "Expression");
  2279. c(node.alternate, st, "Expression");
  2280. };
  2281. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  2282. c(node.callee, st, "Expression");
  2283. if (node.arguments)
  2284. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  2285. {
  2286. var arg = list[i];
  2287. c(arg, st, "Expression");
  2288. } }
  2289. };
  2290. base$1.MemberExpression = function (node, st, c) {
  2291. c(node.object, st, "Expression");
  2292. if (node.computed) { c(node.property, st, "Expression"); }
  2293. };
  2294. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  2295. if (node.declaration)
  2296. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  2297. if (node.source) { c(node.source, st, "Expression"); }
  2298. };
  2299. base$1.ExportAllDeclaration = function (node, st, c) {
  2300. if (node.exported)
  2301. { c(node.exported, st); }
  2302. c(node.source, st, "Expression");
  2303. };
  2304. base$1.ImportDeclaration = function (node, st, c) {
  2305. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  2306. {
  2307. var spec = list[i];
  2308. c(spec, st);
  2309. }
  2310. c(node.source, st, "Expression");
  2311. };
  2312. base$1.ImportExpression = function (node, st, c) {
  2313. c(node.source, st, "Expression");
  2314. };
  2315. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  2316. base$1.TaggedTemplateExpression = function (node, st, c) {
  2317. c(node.tag, st, "Expression");
  2318. c(node.quasi, st, "Expression");
  2319. };
  2320. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  2321. base$1.Class = function (node, st, c) {
  2322. if (node.id) { c(node.id, st, "Pattern"); }
  2323. if (node.superClass) { c(node.superClass, st, "Expression"); }
  2324. c(node.body, st);
  2325. };
  2326. base$1.ClassBody = function (node, st, c) {
  2327. for (var i = 0, list = node.body; i < list.length; i += 1)
  2328. {
  2329. var elt = list[i];
  2330. c(elt, st);
  2331. }
  2332. };
  2333. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  2334. if (node.computed) { c(node.key, st, "Expression"); }
  2335. if (node.value) { c(node.value, st, "Expression"); }
  2336. };
  2337. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  2338. const BinaryExpression$1 = 'BinaryExpression';
  2339. const BlockStatement$1 = 'BlockStatement';
  2340. const CallExpression$1 = 'CallExpression';
  2341. const ChainExpression$1 = 'ChainExpression';
  2342. const ConditionalExpression$1 = 'ConditionalExpression';
  2343. const ExpressionStatement$1 = 'ExpressionStatement';
  2344. const Identifier$1 = 'Identifier';
  2345. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  2346. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  2347. const LogicalExpression$1 = 'LogicalExpression';
  2348. const NewExpression$1 = 'NewExpression';
  2349. const Program$1 = 'Program';
  2350. const Property$1 = 'Property';
  2351. const ReturnStatement$1 = 'ReturnStatement';
  2352. const SequenceExpression$1 = 'SequenceExpression';
  2353. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  2354. // this for an actual sourceMappingURL
  2355. let SOURCEMAPPING_URL = 'sourceMa';
  2356. SOURCEMAPPING_URL += 'ppingURL';
  2357. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  2358. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  2359. // patch up acorn-walk until class-fields are officially supported
  2360. base$1.PropertyDefinition = function (node, st, c) {
  2361. if (node.computed) {
  2362. c(node.key, st, 'Expression');
  2363. }
  2364. if (node.value) {
  2365. c(node.value, st, 'Expression');
  2366. }
  2367. };
  2368. const ANNOTATION_KEY = '_rollupAnnotations';
  2369. const INVALID_COMMENT_KEY = '_rollupRemoved';
  2370. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  2371. const { annotations } = state;
  2372. let comment = annotations[state.annotationIndex];
  2373. while (comment && node.start >= comment.end) {
  2374. markPureNode(node, comment, state.code);
  2375. comment = annotations[++state.annotationIndex];
  2376. }
  2377. if (comment && comment.end <= node.end) {
  2378. base$1[type](node, state, handlePureAnnotationsOfNode);
  2379. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  2380. ++state.annotationIndex;
  2381. annotateNode(node, comment, false);
  2382. }
  2383. }
  2384. }
  2385. const neitherWithespaceNorBrackets = /[^\s(]/g;
  2386. const noWhitespace = /\S/g;
  2387. function markPureNode(node, comment, code) {
  2388. const annotatedNodes = [];
  2389. let invalidAnnotation;
  2390. const codeInBetween = code.slice(comment.end, node.start);
  2391. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  2392. const parentStart = node.start;
  2393. while (true) {
  2394. annotatedNodes.push(node);
  2395. switch (node.type) {
  2396. case ExpressionStatement$1:
  2397. case ChainExpression$1:
  2398. node = node.expression;
  2399. continue;
  2400. case SequenceExpression$1:
  2401. // if there are parentheses, the annotation would apply to the entire expression
  2402. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  2403. node = node.expressions[0];
  2404. continue;
  2405. }
  2406. invalidAnnotation = true;
  2407. break;
  2408. case ConditionalExpression$1:
  2409. // if there are parentheses, the annotation would apply to the entire expression
  2410. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  2411. node = node.test;
  2412. continue;
  2413. }
  2414. invalidAnnotation = true;
  2415. break;
  2416. case LogicalExpression$1:
  2417. case BinaryExpression$1:
  2418. // if there are parentheses, the annotation would apply to the entire expression
  2419. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  2420. node = node.left;
  2421. continue;
  2422. }
  2423. invalidAnnotation = true;
  2424. break;
  2425. case CallExpression$1:
  2426. case NewExpression$1:
  2427. break;
  2428. default:
  2429. invalidAnnotation = true;
  2430. }
  2431. break;
  2432. }
  2433. }
  2434. else {
  2435. invalidAnnotation = true;
  2436. }
  2437. if (invalidAnnotation) {
  2438. annotateNode(node, comment, false);
  2439. }
  2440. else {
  2441. for (const node of annotatedNodes) {
  2442. annotateNode(node, comment, true);
  2443. }
  2444. }
  2445. }
  2446. function doesNotMatchOutsideComment(code, forbiddenChars) {
  2447. let nextMatch;
  2448. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  2449. if (nextMatch[0] === '/') {
  2450. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  2451. if (charCodeAfterSlash === 42 /*"*"*/) {
  2452. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  2453. continue;
  2454. }
  2455. else if (charCodeAfterSlash === 47 /*"/"*/) {
  2456. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  2457. continue;
  2458. }
  2459. }
  2460. forbiddenChars.lastIndex = 0;
  2461. return false;
  2462. }
  2463. return true;
  2464. }
  2465. const pureCommentRegex = /[@#]__PURE__/;
  2466. function addAnnotations(comments, esTreeAst, code) {
  2467. const annotations = [];
  2468. const sourceMappingComments = [];
  2469. for (const comment of comments) {
  2470. if (pureCommentRegex.test(comment.value)) {
  2471. annotations.push(comment);
  2472. }
  2473. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  2474. sourceMappingComments.push(comment);
  2475. }
  2476. }
  2477. for (const comment of sourceMappingComments) {
  2478. annotateNode(esTreeAst, comment, false);
  2479. }
  2480. handlePureAnnotationsOfNode(esTreeAst, {
  2481. annotationIndex: 0,
  2482. annotations,
  2483. code
  2484. });
  2485. }
  2486. function annotateNode(node, comment, valid) {
  2487. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  2488. const property = node[key];
  2489. if (property) {
  2490. property.push(comment);
  2491. }
  2492. else {
  2493. node[key] = [comment];
  2494. }
  2495. }
  2496. const keys = {
  2497. Literal: [],
  2498. Program: ['body']
  2499. };
  2500. function getAndCreateKeys(esTreeNode) {
  2501. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2502. return keys[esTreeNode.type];
  2503. }
  2504. const INCLUDE_PARAMETERS = 'variables';
  2505. class NodeBase extends ExpressionEntity {
  2506. constructor(esTreeNode, parent, parentScope) {
  2507. super();
  2508. this.esTreeNode = esTreeNode;
  2509. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  2510. this.parent = parent;
  2511. this.context = parent.context;
  2512. this.createScope(parentScope);
  2513. this.parseNode(esTreeNode);
  2514. this.initialise();
  2515. this.context.magicString.addSourcemapLocation(this.start);
  2516. this.context.magicString.addSourcemapLocation(this.end);
  2517. }
  2518. addExportedVariables(_variables, _exportNamesByVariable) { }
  2519. /**
  2520. * Override this to bind assignments to variables and do any initialisations that
  2521. * require the scopes to be populated with variables.
  2522. */
  2523. bind() {
  2524. for (const key of this.keys) {
  2525. const value = this[key];
  2526. if (value === null)
  2527. continue;
  2528. if (Array.isArray(value)) {
  2529. for (const child of value) {
  2530. if (child !== null)
  2531. child.bind();
  2532. }
  2533. }
  2534. else {
  2535. value.bind();
  2536. }
  2537. }
  2538. }
  2539. /**
  2540. * Override if this node should receive a different scope than the parent scope.
  2541. */
  2542. createScope(parentScope) {
  2543. this.scope = parentScope;
  2544. }
  2545. hasEffects(context) {
  2546. if (this.deoptimized === false)
  2547. this.applyDeoptimizations();
  2548. for (const key of this.keys) {
  2549. const value = this[key];
  2550. if (value === null)
  2551. continue;
  2552. if (Array.isArray(value)) {
  2553. for (const child of value) {
  2554. if (child !== null && child.hasEffects(context))
  2555. return true;
  2556. }
  2557. }
  2558. else if (value.hasEffects(context))
  2559. return true;
  2560. }
  2561. return false;
  2562. }
  2563. include(context, includeChildrenRecursively) {
  2564. if (this.deoptimized === false)
  2565. this.applyDeoptimizations();
  2566. this.included = true;
  2567. for (const key of this.keys) {
  2568. const value = this[key];
  2569. if (value === null)
  2570. continue;
  2571. if (Array.isArray(value)) {
  2572. for (const child of value) {
  2573. if (child !== null)
  2574. child.include(context, includeChildrenRecursively);
  2575. }
  2576. }
  2577. else {
  2578. value.include(context, includeChildrenRecursively);
  2579. }
  2580. }
  2581. }
  2582. includeAsSingleStatement(context, includeChildrenRecursively) {
  2583. this.include(context, includeChildrenRecursively);
  2584. }
  2585. /**
  2586. * Override to perform special initialisation steps after the scope is initialised
  2587. */
  2588. initialise() { }
  2589. insertSemicolon(code) {
  2590. if (code.original[this.end - 1] !== ';') {
  2591. code.appendLeft(this.end, ';');
  2592. }
  2593. }
  2594. parseNode(esTreeNode) {
  2595. for (const [key, value] of Object.entries(esTreeNode)) {
  2596. // That way, we can override this function to add custom initialisation and then call super.parseNode
  2597. if (this.hasOwnProperty(key))
  2598. continue;
  2599. if (key.charCodeAt(0) === 95 /* _ */) {
  2600. if (key === ANNOTATION_KEY) {
  2601. this.annotations = value;
  2602. }
  2603. else if (key === INVALID_COMMENT_KEY) {
  2604. for (const { start, end } of value)
  2605. this.context.magicString.remove(start, end);
  2606. }
  2607. }
  2608. else if (typeof value !== 'object' || value === null) {
  2609. this[key] = value;
  2610. }
  2611. else if (Array.isArray(value)) {
  2612. this[key] = [];
  2613. for (const child of value) {
  2614. this[key].push(child === null
  2615. ? null
  2616. : new (this.context.nodeConstructors[child.type] ||
  2617. this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
  2618. }
  2619. }
  2620. else {
  2621. this[key] = new (this.context.nodeConstructors[value.type] ||
  2622. this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
  2623. }
  2624. }
  2625. }
  2626. render(code, options) {
  2627. for (const key of this.keys) {
  2628. const value = this[key];
  2629. if (value === null)
  2630. continue;
  2631. if (Array.isArray(value)) {
  2632. for (const child of value) {
  2633. if (child !== null)
  2634. child.render(code, options);
  2635. }
  2636. }
  2637. else {
  2638. value.render(code, options);
  2639. }
  2640. }
  2641. }
  2642. shouldBeIncluded(context) {
  2643. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2644. }
  2645. applyDeoptimizations() { }
  2646. }
  2647. class ExportAllDeclaration extends NodeBase {
  2648. hasEffects() {
  2649. return false;
  2650. }
  2651. initialise() {
  2652. this.context.addExport(this);
  2653. }
  2654. render(code, _options, nodeRenderOptions) {
  2655. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  2656. }
  2657. }
  2658. ExportAllDeclaration.prototype.needsBoundaries = true;
  2659. function treeshakeNode(node, code, start, end) {
  2660. code.remove(start, end);
  2661. if (node.annotations) {
  2662. for (const annotation of node.annotations) {
  2663. if (annotation.start < start) {
  2664. code.remove(annotation.start, annotation.end);
  2665. }
  2666. else {
  2667. return;
  2668. }
  2669. }
  2670. }
  2671. }
  2672. function removeAnnotations(node, code) {
  2673. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  2674. node = node.parent;
  2675. }
  2676. if (node.annotations) {
  2677. for (const annotation of node.annotations) {
  2678. code.remove(annotation.start, annotation.end);
  2679. }
  2680. }
  2681. }
  2682. const NO_SEMICOLON = { isNoStatement: true };
  2683. // This assumes there are only white-space and comments between start and the string we are looking for
  2684. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  2685. let searchPos, charCodeAfterSlash;
  2686. searchPos = code.indexOf(searchString, start);
  2687. while (true) {
  2688. start = code.indexOf('/', start);
  2689. if (start === -1 || start >= searchPos)
  2690. return searchPos;
  2691. charCodeAfterSlash = code.charCodeAt(++start);
  2692. ++start;
  2693. // With our assumption, '/' always starts a comment. Determine comment type:
  2694. start =
  2695. charCodeAfterSlash === 47 /*"/"*/
  2696. ? code.indexOf('\n', start) + 1
  2697. : code.indexOf('*/', start) + 2;
  2698. if (start > searchPos) {
  2699. searchPos = code.indexOf(searchString, start);
  2700. }
  2701. }
  2702. }
  2703. const NON_WHITESPACE = /\S/g;
  2704. function findNonWhiteSpace(code, index) {
  2705. NON_WHITESPACE.lastIndex = index;
  2706. const result = NON_WHITESPACE.exec(code);
  2707. return result.index;
  2708. }
  2709. // This assumes "code" only contains white-space and comments
  2710. // Returns position of line-comment if applicable
  2711. function findFirstLineBreakOutsideComment(code) {
  2712. let lineBreakPos, charCodeAfterSlash, start = 0;
  2713. lineBreakPos = code.indexOf('\n', start);
  2714. while (true) {
  2715. start = code.indexOf('/', start);
  2716. if (start === -1 || start > lineBreakPos)
  2717. return [lineBreakPos, lineBreakPos + 1];
  2718. // With our assumption, '/' always starts a comment. Determine comment type:
  2719. charCodeAfterSlash = code.charCodeAt(start + 1);
  2720. if (charCodeAfterSlash === 47 /*"/"*/)
  2721. return [start, lineBreakPos + 1];
  2722. start = code.indexOf('*/', start + 3) + 2;
  2723. if (start > lineBreakPos) {
  2724. lineBreakPos = code.indexOf('\n', start);
  2725. }
  2726. }
  2727. }
  2728. function renderStatementList(statements, code, start, end, options) {
  2729. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  2730. let nextNode = statements[0];
  2731. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  2732. if (nextNodeNeedsBoundaries) {
  2733. nextNodeStart =
  2734. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  2735. }
  2736. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  2737. currentNode = nextNode;
  2738. currentNodeStart = nextNodeStart;
  2739. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  2740. nextNode = statements[nextIndex];
  2741. nextNodeNeedsBoundaries =
  2742. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  2743. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  2744. nextNodeStart =
  2745. currentNode.end +
  2746. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  2747. if (currentNode.included) {
  2748. currentNodeNeedsBoundaries
  2749. ? currentNode.render(code, options, {
  2750. end: nextNodeStart,
  2751. start: currentNodeStart
  2752. })
  2753. : currentNode.render(code, options);
  2754. }
  2755. else {
  2756. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  2757. }
  2758. }
  2759. else {
  2760. currentNode.render(code, options);
  2761. }
  2762. }
  2763. }
  2764. // This assumes that the first character is not part of the first node
  2765. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  2766. const splitUpNodes = [];
  2767. let node, nextNode, nextNodeStart, contentEnd, char;
  2768. let separator = start - 1;
  2769. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  2770. nextNode = nodes[nextIndex];
  2771. if (node !== undefined) {
  2772. separator =
  2773. node.end +
  2774. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  2775. }
  2776. nextNodeStart = contentEnd =
  2777. separator +
  2778. 1 +
  2779. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  2780. while (((char = code.original.charCodeAt(nextNodeStart)),
  2781. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  2782. nextNodeStart++;
  2783. if (node !== undefined) {
  2784. splitUpNodes.push({
  2785. contentEnd,
  2786. end: nextNodeStart,
  2787. node,
  2788. separator,
  2789. start
  2790. });
  2791. }
  2792. node = nextNode;
  2793. start = nextNodeStart;
  2794. }
  2795. splitUpNodes.push({
  2796. contentEnd: end,
  2797. end,
  2798. node: node,
  2799. separator: null,
  2800. start
  2801. });
  2802. return splitUpNodes;
  2803. }
  2804. // This assumes there are only white-space and comments between start and end
  2805. function removeLineBreaks(code, start, end) {
  2806. while (true) {
  2807. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  2808. if (removeStart === -1) {
  2809. break;
  2810. }
  2811. code.remove(start + removeStart, (start += removeEnd));
  2812. }
  2813. }
  2814. function getSystemExportStatement(exportedVariables, { compact, exportNamesByVariable }, modifier = '') {
  2815. const _ = compact ? '' : ' ';
  2816. if (exportedVariables.length === 1 &&
  2817. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  2818. const variable = exportedVariables[0];
  2819. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName()}${modifier})`;
  2820. }
  2821. else {
  2822. return `exports({${_}${exportedVariables
  2823. .map(variable => {
  2824. return exportNamesByVariable
  2825. .get(variable)
  2826. .map(exportName => `${exportName}:${_}${variable.getName()}${modifier}`)
  2827. .join(`,${_}`);
  2828. })
  2829. .join(`,${_}`)}${_}})`;
  2830. }
  2831. }
  2832. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { compact, exportNamesByVariable }) {
  2833. const _ = compact ? '' : ' ';
  2834. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  2835. code.appendLeft(expressionEnd, ')');
  2836. }
  2837. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  2838. const _ = options.compact ? '' : ' ';
  2839. const s = options.compact ? '' : ';';
  2840. code.prependRight(expressionStart, `function${_}(v)${_}{${_}return ${getSystemExportStatement(exportedVariables, options)},${_}v${s}${_}}(`);
  2841. code.appendLeft(expressionEnd, ')');
  2842. if (needsParens) {
  2843. code.prependRight(expressionStart, '(');
  2844. code.appendLeft(expressionEnd, ')');
  2845. }
  2846. }
  2847. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  2848. const _ = options.compact ? '' : ' ';
  2849. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName()}`);
  2850. if (needsParens) {
  2851. code.prependRight(expressionStart, '(');
  2852. code.appendLeft(expressionEnd, ')');
  2853. }
  2854. }
  2855. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  2856. const _ = options.compact ? '' : ' ';
  2857. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  2858. if (needsParens) {
  2859. code.prependRight(expressionStart, '(');
  2860. code.appendLeft(expressionEnd, ')');
  2861. }
  2862. }
  2863. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  2864. const base = 64;
  2865. function toBase64(num) {
  2866. let outStr = '';
  2867. do {
  2868. const curDigit = num % base;
  2869. num = Math.floor(num / base);
  2870. outStr = chars[curDigit] + outStr;
  2871. } while (num !== 0);
  2872. return outStr;
  2873. }
  2874. function getSafeName(baseName, usedNames) {
  2875. let safeName = baseName;
  2876. let count = 1;
  2877. while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
  2878. safeName = `${baseName}$${toBase64(count++)}`;
  2879. }
  2880. usedNames.add(safeName);
  2881. return safeName;
  2882. }
  2883. const NO_ARGS = [];
  2884. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2885. return Object.create(inheritedDescriptions, memberDescriptions);
  2886. }
  2887. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2888. getLiteralValueAtPath() {
  2889. return undefined;
  2890. }
  2891. })();
  2892. const returnsUnknown = {
  2893. value: {
  2894. callsArgs: null,
  2895. returns: UNKNOWN_EXPRESSION
  2896. }
  2897. };
  2898. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2899. getReturnExpressionWhenCalledAtPath(path) {
  2900. if (path.length === 1) {
  2901. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2902. }
  2903. return UNKNOWN_EXPRESSION;
  2904. }
  2905. hasEffectsWhenAccessedAtPath(path) {
  2906. return path.length > 1;
  2907. }
  2908. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2909. if (path.length === 1) {
  2910. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], callOptions, context);
  2911. }
  2912. return true;
  2913. }
  2914. })();
  2915. const returnsBoolean = {
  2916. value: {
  2917. callsArgs: null,
  2918. returns: UNKNOWN_LITERAL_BOOLEAN
  2919. }
  2920. };
  2921. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2922. getReturnExpressionWhenCalledAtPath(path) {
  2923. if (path.length === 1) {
  2924. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2925. }
  2926. return UNKNOWN_EXPRESSION;
  2927. }
  2928. hasEffectsWhenAccessedAtPath(path) {
  2929. return path.length > 1;
  2930. }
  2931. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2932. if (path.length === 1) {
  2933. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], callOptions, context);
  2934. }
  2935. return true;
  2936. }
  2937. })();
  2938. const returnsNumber = {
  2939. value: {
  2940. callsArgs: null,
  2941. returns: UNKNOWN_LITERAL_NUMBER
  2942. }
  2943. };
  2944. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2945. getReturnExpressionWhenCalledAtPath(path) {
  2946. if (path.length === 1) {
  2947. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2948. }
  2949. return UNKNOWN_EXPRESSION;
  2950. }
  2951. hasEffectsWhenAccessedAtPath(path) {
  2952. return path.length > 1;
  2953. }
  2954. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2955. if (path.length === 1) {
  2956. return hasMemberEffectWhenCalled(literalStringMembers, path[0], callOptions, context);
  2957. }
  2958. return true;
  2959. }
  2960. })();
  2961. const returnsString = {
  2962. value: {
  2963. callsArgs: null,
  2964. returns: UNKNOWN_LITERAL_STRING
  2965. }
  2966. };
  2967. const objectMembers = assembleMemberDescriptions({
  2968. hasOwnProperty: returnsBoolean,
  2969. isPrototypeOf: returnsBoolean,
  2970. propertyIsEnumerable: returnsBoolean,
  2971. toLocaleString: returnsString,
  2972. toString: returnsString,
  2973. valueOf: returnsUnknown
  2974. });
  2975. const literalBooleanMembers = assembleMemberDescriptions({
  2976. valueOf: returnsBoolean
  2977. }, objectMembers);
  2978. const literalNumberMembers = assembleMemberDescriptions({
  2979. toExponential: returnsString,
  2980. toFixed: returnsString,
  2981. toLocaleString: returnsString,
  2982. toPrecision: returnsString,
  2983. valueOf: returnsNumber
  2984. }, objectMembers);
  2985. const literalStringMembers = assembleMemberDescriptions({
  2986. charAt: returnsString,
  2987. charCodeAt: returnsNumber,
  2988. codePointAt: returnsNumber,
  2989. concat: returnsString,
  2990. endsWith: returnsBoolean,
  2991. includes: returnsBoolean,
  2992. indexOf: returnsNumber,
  2993. lastIndexOf: returnsNumber,
  2994. localeCompare: returnsNumber,
  2995. match: returnsBoolean,
  2996. normalize: returnsString,
  2997. padEnd: returnsString,
  2998. padStart: returnsString,
  2999. repeat: returnsString,
  3000. replace: {
  3001. value: {
  3002. callsArgs: [1],
  3003. returns: UNKNOWN_LITERAL_STRING
  3004. }
  3005. },
  3006. search: returnsNumber,
  3007. slice: returnsString,
  3008. split: returnsUnknown,
  3009. startsWith: returnsBoolean,
  3010. substr: returnsString,
  3011. substring: returnsString,
  3012. toLocaleLowerCase: returnsString,
  3013. toLocaleUpperCase: returnsString,
  3014. toLowerCase: returnsString,
  3015. toUpperCase: returnsString,
  3016. trim: returnsString,
  3017. valueOf: returnsString
  3018. }, objectMembers);
  3019. function getLiteralMembersForValue(value) {
  3020. switch (typeof value) {
  3021. case 'boolean':
  3022. return literalBooleanMembers;
  3023. case 'number':
  3024. return literalNumberMembers;
  3025. case 'string':
  3026. return literalStringMembers;
  3027. default:
  3028. return Object.create(null);
  3029. }
  3030. }
  3031. function hasMemberEffectWhenCalled(members, memberName, callOptions, context) {
  3032. if (typeof memberName !== 'string' || !members[memberName]) {
  3033. return true;
  3034. }
  3035. if (!members[memberName].callsArgs)
  3036. return false;
  3037. for (const argIndex of members[memberName].callsArgs) {
  3038. if (callOptions.args[argIndex] &&
  3039. callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  3040. args: NO_ARGS,
  3041. thisParam: null,
  3042. withNew: false
  3043. }, context))
  3044. return true;
  3045. }
  3046. return false;
  3047. }
  3048. function getMemberReturnExpressionWhenCalled(members, memberName) {
  3049. if (typeof memberName !== 'string' || !members[memberName])
  3050. return UNKNOWN_EXPRESSION;
  3051. return members[memberName].returns;
  3052. }
  3053. class LocalVariable extends Variable {
  3054. constructor(name, declarator, init, context) {
  3055. super(name);
  3056. this.calledFromTryStatement = false;
  3057. this.additionalInitializers = null;
  3058. this.expressionsToBeDeoptimized = [];
  3059. this.declarations = declarator ? [declarator] : [];
  3060. this.init = init;
  3061. this.deoptimizationTracker = context.deoptimizationTracker;
  3062. this.module = context.module;
  3063. }
  3064. addDeclaration(identifier, init) {
  3065. this.declarations.push(identifier);
  3066. const additionalInitializers = this.markInitializersForDeoptimization();
  3067. if (init !== null) {
  3068. additionalInitializers.push(init);
  3069. }
  3070. }
  3071. consolidateInitializers() {
  3072. if (this.additionalInitializers !== null) {
  3073. for (const initializer of this.additionalInitializers) {
  3074. initializer.deoptimizePath(UNKNOWN_PATH);
  3075. }
  3076. this.additionalInitializers = null;
  3077. }
  3078. }
  3079. deoptimizePath(path) {
  3080. var _a, _b;
  3081. if (this.isReassigned ||
  3082. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  3083. return;
  3084. }
  3085. if (path.length === 0) {
  3086. if (!this.isReassigned) {
  3087. this.isReassigned = true;
  3088. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  3089. this.expressionsToBeDeoptimized = [];
  3090. for (const expression of expressionsToBeDeoptimized) {
  3091. expression.deoptimizeCache();
  3092. }
  3093. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  3094. }
  3095. }
  3096. else {
  3097. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  3098. }
  3099. }
  3100. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  3101. if (this.isReassigned || !this.init) {
  3102. return thisParameter.deoptimizePath(UNKNOWN_PATH);
  3103. }
  3104. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker), undefined);
  3105. }
  3106. getLiteralValueAtPath(path, recursionTracker, origin) {
  3107. if (this.isReassigned || !this.init) {
  3108. return UnknownValue;
  3109. }
  3110. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  3111. this.expressionsToBeDeoptimized.push(origin);
  3112. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  3113. }, UnknownValue);
  3114. }
  3115. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  3116. if (this.isReassigned || !this.init) {
  3117. return UNKNOWN_EXPRESSION;
  3118. }
  3119. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  3120. this.expressionsToBeDeoptimized.push(origin);
  3121. return this.init.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  3122. }, UNKNOWN_EXPRESSION);
  3123. }
  3124. hasEffectsWhenAccessedAtPath(path, context) {
  3125. if (this.isReassigned)
  3126. return true;
  3127. return (this.init &&
  3128. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  3129. this.init.hasEffectsWhenAccessedAtPath(path, context));
  3130. }
  3131. hasEffectsWhenAssignedAtPath(path, context) {
  3132. if (this.included)
  3133. return true;
  3134. if (path.length === 0)
  3135. return false;
  3136. if (this.isReassigned)
  3137. return true;
  3138. return (this.init &&
  3139. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  3140. this.init.hasEffectsWhenAssignedAtPath(path, context));
  3141. }
  3142. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3143. if (this.isReassigned)
  3144. return true;
  3145. return (this.init &&
  3146. !(callOptions.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, callOptions, this) &&
  3147. this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
  3148. }
  3149. include() {
  3150. if (!this.included) {
  3151. this.included = true;
  3152. for (const declaration of this.declarations) {
  3153. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  3154. if (!declaration.included)
  3155. declaration.include(createInclusionContext(), false);
  3156. let node = declaration.parent;
  3157. while (!node.included) {
  3158. // We do not want to properly include parents in case they are part of a dead branch
  3159. // in which case .include() might pull in more dead code
  3160. node.included = true;
  3161. if (node.type === Program$1)
  3162. break;
  3163. node = node.parent;
  3164. }
  3165. }
  3166. }
  3167. }
  3168. includeCallArguments(context, args) {
  3169. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  3170. for (const arg of args) {
  3171. arg.include(context, false);
  3172. }
  3173. }
  3174. else if (this.init) {
  3175. context.includedCallArguments.add(this.init);
  3176. this.init.includeCallArguments(context, args);
  3177. context.includedCallArguments.delete(this.init);
  3178. }
  3179. }
  3180. markCalledFromTryStatement() {
  3181. this.calledFromTryStatement = true;
  3182. }
  3183. markInitializersForDeoptimization() {
  3184. if (this.additionalInitializers === null) {
  3185. this.additionalInitializers = this.init === null ? [] : [this.init];
  3186. this.init = UNKNOWN_EXPRESSION;
  3187. this.isReassigned = true;
  3188. }
  3189. return this.additionalInitializers;
  3190. }
  3191. }
  3192. class Scope$1 {
  3193. constructor() {
  3194. this.children = [];
  3195. this.variables = new Map();
  3196. }
  3197. addDeclaration(identifier, context, init, _isHoisted) {
  3198. const name = identifier.name;
  3199. let variable = this.variables.get(name);
  3200. if (variable) {
  3201. variable.addDeclaration(identifier, init);
  3202. }
  3203. else {
  3204. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  3205. this.variables.set(name, variable);
  3206. }
  3207. return variable;
  3208. }
  3209. contains(name) {
  3210. return this.variables.has(name);
  3211. }
  3212. findVariable(_name) {
  3213. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  3214. }
  3215. }
  3216. class ChildScope extends Scope$1 {
  3217. constructor(parent) {
  3218. super();
  3219. this.accessedOutsideVariables = new Map();
  3220. this.parent = parent;
  3221. parent.children.push(this);
  3222. }
  3223. addAccessedDynamicImport(importExpression) {
  3224. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  3225. if (this.parent instanceof ChildScope) {
  3226. this.parent.addAccessedDynamicImport(importExpression);
  3227. }
  3228. }
  3229. addAccessedGlobals(globals, accessedGlobalsByScope) {
  3230. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  3231. for (const name of globals) {
  3232. accessedGlobals.add(name);
  3233. }
  3234. accessedGlobalsByScope.set(this, accessedGlobals);
  3235. if (this.parent instanceof ChildScope) {
  3236. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  3237. }
  3238. }
  3239. addNamespaceMemberAccess(name, variable) {
  3240. this.accessedOutsideVariables.set(name, variable);
  3241. this.parent.addNamespaceMemberAccess(name, variable);
  3242. }
  3243. addReturnExpression(expression) {
  3244. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  3245. }
  3246. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  3247. for (const variable of this.accessedOutsideVariables.values()) {
  3248. if (variable.included) {
  3249. usedNames.add(variable.getBaseVariableName());
  3250. if (format === 'system' && exportNamesByVariable.has(variable)) {
  3251. usedNames.add('exports');
  3252. }
  3253. }
  3254. }
  3255. const accessedGlobals = accessedGlobalsByScope.get(this);
  3256. if (accessedGlobals) {
  3257. for (const name of accessedGlobals) {
  3258. usedNames.add(name);
  3259. }
  3260. }
  3261. }
  3262. contains(name) {
  3263. return this.variables.has(name) || this.parent.contains(name);
  3264. }
  3265. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  3266. const usedNames = new Set();
  3267. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  3268. if (this.accessedDynamicImports) {
  3269. for (const importExpression of this.accessedDynamicImports) {
  3270. if (importExpression.inlineNamespace) {
  3271. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  3272. }
  3273. }
  3274. }
  3275. for (const [name, variable] of this.variables) {
  3276. if (variable.included || variable.alwaysRendered) {
  3277. variable.setRenderNames(null, getSafeName(name, usedNames));
  3278. }
  3279. }
  3280. for (const scope of this.children) {
  3281. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  3282. }
  3283. }
  3284. findLexicalBoundary() {
  3285. return this.parent.findLexicalBoundary();
  3286. }
  3287. findVariable(name) {
  3288. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  3289. if (knownVariable) {
  3290. return knownVariable;
  3291. }
  3292. const variable = this.parent.findVariable(name);
  3293. this.accessedOutsideVariables.set(name, variable);
  3294. return variable;
  3295. }
  3296. }
  3297. //@ts-check
  3298. /** @typedef { import('estree').Node} Node */
  3299. /** @typedef {Node | {
  3300. * type: 'PropertyDefinition';
  3301. * computed: boolean;
  3302. * value: Node
  3303. * }} NodeWithPropertyDefinition */
  3304. /**
  3305. *
  3306. * @param {NodeWithPropertyDefinition} node
  3307. * @param {NodeWithPropertyDefinition} parent
  3308. * @returns boolean
  3309. */
  3310. function is_reference (node, parent) {
  3311. if (node.type === 'MemberExpression') {
  3312. return !node.computed && is_reference(node.object, node);
  3313. }
  3314. if (node.type === 'Identifier') {
  3315. if (!parent) return true;
  3316. switch (parent.type) {
  3317. // disregard `bar` in `foo.bar`
  3318. case 'MemberExpression': return parent.computed || node === parent.object;
  3319. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  3320. case 'MethodDefinition': return parent.computed;
  3321. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  3322. case 'PropertyDefinition': return parent.computed || node === parent.value;
  3323. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  3324. case 'Property': return parent.computed || node === parent.value;
  3325. // disregard the `bar` in `export { foo as bar }` or
  3326. // the foo in `import { foo as bar }`
  3327. case 'ExportSpecifier':
  3328. case 'ImportSpecifier': return node === parent.local;
  3329. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  3330. case 'LabeledStatement':
  3331. case 'BreakStatement':
  3332. case 'ContinueStatement': return false;
  3333. default: return true;
  3334. }
  3335. }
  3336. return false;
  3337. }
  3338. /* eslint sort-keys: "off" */
  3339. const ValueProperties = Symbol('Value Properties');
  3340. const PURE = { pure: true };
  3341. const IMPURE = { pure: false };
  3342. // We use shortened variables to reduce file size here
  3343. /* OBJECT */
  3344. const O = {
  3345. __proto__: null,
  3346. [ValueProperties]: IMPURE
  3347. };
  3348. /* PURE FUNCTION */
  3349. const PF = {
  3350. __proto__: null,
  3351. [ValueProperties]: PURE
  3352. };
  3353. /* CONSTRUCTOR */
  3354. const C = {
  3355. __proto__: null,
  3356. [ValueProperties]: IMPURE,
  3357. prototype: O
  3358. };
  3359. /* PURE CONSTRUCTOR */
  3360. const PC = {
  3361. __proto__: null,
  3362. [ValueProperties]: PURE,
  3363. prototype: O
  3364. };
  3365. const ARRAY_TYPE = {
  3366. __proto__: null,
  3367. [ValueProperties]: PURE,
  3368. from: PF,
  3369. of: PF,
  3370. prototype: O
  3371. };
  3372. const INTL_MEMBER = {
  3373. __proto__: null,
  3374. [ValueProperties]: PURE,
  3375. supportedLocalesOf: PC
  3376. };
  3377. const knownGlobals = {
  3378. // Placeholders for global objects to avoid shape mutations
  3379. global: O,
  3380. globalThis: O,
  3381. self: O,
  3382. window: O,
  3383. // Common globals
  3384. __proto__: null,
  3385. [ValueProperties]: IMPURE,
  3386. Array: {
  3387. __proto__: null,
  3388. [ValueProperties]: IMPURE,
  3389. from: O,
  3390. isArray: PF,
  3391. of: PF,
  3392. prototype: O
  3393. },
  3394. ArrayBuffer: {
  3395. __proto__: null,
  3396. [ValueProperties]: PURE,
  3397. isView: PF,
  3398. prototype: O
  3399. },
  3400. Atomics: O,
  3401. BigInt: C,
  3402. BigInt64Array: C,
  3403. BigUint64Array: C,
  3404. Boolean: PC,
  3405. constructor: C,
  3406. DataView: PC,
  3407. Date: {
  3408. __proto__: null,
  3409. [ValueProperties]: PURE,
  3410. now: PF,
  3411. parse: PF,
  3412. prototype: O,
  3413. UTC: PF
  3414. },
  3415. decodeURI: PF,
  3416. decodeURIComponent: PF,
  3417. encodeURI: PF,
  3418. encodeURIComponent: PF,
  3419. Error: PC,
  3420. escape: PF,
  3421. eval: O,
  3422. EvalError: PC,
  3423. Float32Array: ARRAY_TYPE,
  3424. Float64Array: ARRAY_TYPE,
  3425. Function: C,
  3426. hasOwnProperty: O,
  3427. Infinity: O,
  3428. Int16Array: ARRAY_TYPE,
  3429. Int32Array: ARRAY_TYPE,
  3430. Int8Array: ARRAY_TYPE,
  3431. isFinite: PF,
  3432. isNaN: PF,
  3433. isPrototypeOf: O,
  3434. JSON: O,
  3435. Map: PC,
  3436. Math: {
  3437. __proto__: null,
  3438. [ValueProperties]: IMPURE,
  3439. abs: PF,
  3440. acos: PF,
  3441. acosh: PF,
  3442. asin: PF,
  3443. asinh: PF,
  3444. atan: PF,
  3445. atan2: PF,
  3446. atanh: PF,
  3447. cbrt: PF,
  3448. ceil: PF,
  3449. clz32: PF,
  3450. cos: PF,
  3451. cosh: PF,
  3452. exp: PF,
  3453. expm1: PF,
  3454. floor: PF,
  3455. fround: PF,
  3456. hypot: PF,
  3457. imul: PF,
  3458. log: PF,
  3459. log10: PF,
  3460. log1p: PF,
  3461. log2: PF,
  3462. max: PF,
  3463. min: PF,
  3464. pow: PF,
  3465. random: PF,
  3466. round: PF,
  3467. sign: PF,
  3468. sin: PF,
  3469. sinh: PF,
  3470. sqrt: PF,
  3471. tan: PF,
  3472. tanh: PF,
  3473. trunc: PF
  3474. },
  3475. NaN: O,
  3476. Number: {
  3477. __proto__: null,
  3478. [ValueProperties]: PURE,
  3479. isFinite: PF,
  3480. isInteger: PF,
  3481. isNaN: PF,
  3482. isSafeInteger: PF,
  3483. parseFloat: PF,
  3484. parseInt: PF,
  3485. prototype: O
  3486. },
  3487. Object: {
  3488. __proto__: null,
  3489. [ValueProperties]: PURE,
  3490. create: PF,
  3491. getNotifier: PF,
  3492. getOwn: PF,
  3493. getOwnPropertyDescriptor: PF,
  3494. getOwnPropertyNames: PF,
  3495. getOwnPropertySymbols: PF,
  3496. getPrototypeOf: PF,
  3497. is: PF,
  3498. isExtensible: PF,
  3499. isFrozen: PF,
  3500. isSealed: PF,
  3501. keys: PF,
  3502. prototype: O
  3503. },
  3504. parseFloat: PF,
  3505. parseInt: PF,
  3506. Promise: {
  3507. __proto__: null,
  3508. [ValueProperties]: IMPURE,
  3509. all: O,
  3510. prototype: O,
  3511. race: O,
  3512. reject: O,
  3513. resolve: O
  3514. },
  3515. propertyIsEnumerable: O,
  3516. Proxy: O,
  3517. RangeError: PC,
  3518. ReferenceError: PC,
  3519. Reflect: O,
  3520. RegExp: PC,
  3521. Set: PC,
  3522. SharedArrayBuffer: C,
  3523. String: {
  3524. __proto__: null,
  3525. [ValueProperties]: PURE,
  3526. fromCharCode: PF,
  3527. fromCodePoint: PF,
  3528. prototype: O,
  3529. raw: PF
  3530. },
  3531. Symbol: {
  3532. __proto__: null,
  3533. [ValueProperties]: PURE,
  3534. for: PF,
  3535. keyFor: PF,
  3536. prototype: O
  3537. },
  3538. SyntaxError: PC,
  3539. toLocaleString: O,
  3540. toString: O,
  3541. TypeError: PC,
  3542. Uint16Array: ARRAY_TYPE,
  3543. Uint32Array: ARRAY_TYPE,
  3544. Uint8Array: ARRAY_TYPE,
  3545. Uint8ClampedArray: ARRAY_TYPE,
  3546. // Technically, this is a global, but it needs special handling
  3547. // undefined: ?,
  3548. unescape: PF,
  3549. URIError: PC,
  3550. valueOf: O,
  3551. WeakMap: PC,
  3552. WeakSet: PC,
  3553. // Additional globals shared by Node and Browser that are not strictly part of the language
  3554. clearInterval: C,
  3555. clearTimeout: C,
  3556. console: O,
  3557. Intl: {
  3558. __proto__: null,
  3559. [ValueProperties]: IMPURE,
  3560. Collator: INTL_MEMBER,
  3561. DateTimeFormat: INTL_MEMBER,
  3562. ListFormat: INTL_MEMBER,
  3563. NumberFormat: INTL_MEMBER,
  3564. PluralRules: INTL_MEMBER,
  3565. RelativeTimeFormat: INTL_MEMBER
  3566. },
  3567. setInterval: C,
  3568. setTimeout: C,
  3569. TextDecoder: C,
  3570. TextEncoder: C,
  3571. URL: C,
  3572. URLSearchParams: C,
  3573. // Browser specific globals
  3574. AbortController: C,
  3575. AbortSignal: C,
  3576. addEventListener: O,
  3577. alert: O,
  3578. AnalyserNode: C,
  3579. Animation: C,
  3580. AnimationEvent: C,
  3581. applicationCache: O,
  3582. ApplicationCache: C,
  3583. ApplicationCacheErrorEvent: C,
  3584. atob: O,
  3585. Attr: C,
  3586. Audio: C,
  3587. AudioBuffer: C,
  3588. AudioBufferSourceNode: C,
  3589. AudioContext: C,
  3590. AudioDestinationNode: C,
  3591. AudioListener: C,
  3592. AudioNode: C,
  3593. AudioParam: C,
  3594. AudioProcessingEvent: C,
  3595. AudioScheduledSourceNode: C,
  3596. AudioWorkletNode: C,
  3597. BarProp: C,
  3598. BaseAudioContext: C,
  3599. BatteryManager: C,
  3600. BeforeUnloadEvent: C,
  3601. BiquadFilterNode: C,
  3602. Blob: C,
  3603. BlobEvent: C,
  3604. blur: O,
  3605. BroadcastChannel: C,
  3606. btoa: O,
  3607. ByteLengthQueuingStrategy: C,
  3608. Cache: C,
  3609. caches: O,
  3610. CacheStorage: C,
  3611. cancelAnimationFrame: O,
  3612. cancelIdleCallback: O,
  3613. CanvasCaptureMediaStreamTrack: C,
  3614. CanvasGradient: C,
  3615. CanvasPattern: C,
  3616. CanvasRenderingContext2D: C,
  3617. ChannelMergerNode: C,
  3618. ChannelSplitterNode: C,
  3619. CharacterData: C,
  3620. clientInformation: O,
  3621. ClipboardEvent: C,
  3622. close: O,
  3623. closed: O,
  3624. CloseEvent: C,
  3625. Comment: C,
  3626. CompositionEvent: C,
  3627. confirm: O,
  3628. ConstantSourceNode: C,
  3629. ConvolverNode: C,
  3630. CountQueuingStrategy: C,
  3631. createImageBitmap: O,
  3632. Credential: C,
  3633. CredentialsContainer: C,
  3634. crypto: O,
  3635. Crypto: C,
  3636. CryptoKey: C,
  3637. CSS: C,
  3638. CSSConditionRule: C,
  3639. CSSFontFaceRule: C,
  3640. CSSGroupingRule: C,
  3641. CSSImportRule: C,
  3642. CSSKeyframeRule: C,
  3643. CSSKeyframesRule: C,
  3644. CSSMediaRule: C,
  3645. CSSNamespaceRule: C,
  3646. CSSPageRule: C,
  3647. CSSRule: C,
  3648. CSSRuleList: C,
  3649. CSSStyleDeclaration: C,
  3650. CSSStyleRule: C,
  3651. CSSStyleSheet: C,
  3652. CSSSupportsRule: C,
  3653. CustomElementRegistry: C,
  3654. customElements: O,
  3655. CustomEvent: C,
  3656. DataTransfer: C,
  3657. DataTransferItem: C,
  3658. DataTransferItemList: C,
  3659. defaultstatus: O,
  3660. defaultStatus: O,
  3661. DelayNode: C,
  3662. DeviceMotionEvent: C,
  3663. DeviceOrientationEvent: C,
  3664. devicePixelRatio: O,
  3665. dispatchEvent: O,
  3666. document: O,
  3667. Document: C,
  3668. DocumentFragment: C,
  3669. DocumentType: C,
  3670. DOMError: C,
  3671. DOMException: C,
  3672. DOMImplementation: C,
  3673. DOMMatrix: C,
  3674. DOMMatrixReadOnly: C,
  3675. DOMParser: C,
  3676. DOMPoint: C,
  3677. DOMPointReadOnly: C,
  3678. DOMQuad: C,
  3679. DOMRect: C,
  3680. DOMRectReadOnly: C,
  3681. DOMStringList: C,
  3682. DOMStringMap: C,
  3683. DOMTokenList: C,
  3684. DragEvent: C,
  3685. DynamicsCompressorNode: C,
  3686. Element: C,
  3687. ErrorEvent: C,
  3688. Event: C,
  3689. EventSource: C,
  3690. EventTarget: C,
  3691. external: O,
  3692. fetch: O,
  3693. File: C,
  3694. FileList: C,
  3695. FileReader: C,
  3696. find: O,
  3697. focus: O,
  3698. FocusEvent: C,
  3699. FontFace: C,
  3700. FontFaceSetLoadEvent: C,
  3701. FormData: C,
  3702. frames: O,
  3703. GainNode: C,
  3704. Gamepad: C,
  3705. GamepadButton: C,
  3706. GamepadEvent: C,
  3707. getComputedStyle: O,
  3708. getSelection: O,
  3709. HashChangeEvent: C,
  3710. Headers: C,
  3711. history: O,
  3712. History: C,
  3713. HTMLAllCollection: C,
  3714. HTMLAnchorElement: C,
  3715. HTMLAreaElement: C,
  3716. HTMLAudioElement: C,
  3717. HTMLBaseElement: C,
  3718. HTMLBodyElement: C,
  3719. HTMLBRElement: C,
  3720. HTMLButtonElement: C,
  3721. HTMLCanvasElement: C,
  3722. HTMLCollection: C,
  3723. HTMLContentElement: C,
  3724. HTMLDataElement: C,
  3725. HTMLDataListElement: C,
  3726. HTMLDetailsElement: C,
  3727. HTMLDialogElement: C,
  3728. HTMLDirectoryElement: C,
  3729. HTMLDivElement: C,
  3730. HTMLDListElement: C,
  3731. HTMLDocument: C,
  3732. HTMLElement: C,
  3733. HTMLEmbedElement: C,
  3734. HTMLFieldSetElement: C,
  3735. HTMLFontElement: C,
  3736. HTMLFormControlsCollection: C,
  3737. HTMLFormElement: C,
  3738. HTMLFrameElement: C,
  3739. HTMLFrameSetElement: C,
  3740. HTMLHeadElement: C,
  3741. HTMLHeadingElement: C,
  3742. HTMLHRElement: C,
  3743. HTMLHtmlElement: C,
  3744. HTMLIFrameElement: C,
  3745. HTMLImageElement: C,
  3746. HTMLInputElement: C,
  3747. HTMLLabelElement: C,
  3748. HTMLLegendElement: C,
  3749. HTMLLIElement: C,
  3750. HTMLLinkElement: C,
  3751. HTMLMapElement: C,
  3752. HTMLMarqueeElement: C,
  3753. HTMLMediaElement: C,
  3754. HTMLMenuElement: C,
  3755. HTMLMetaElement: C,
  3756. HTMLMeterElement: C,
  3757. HTMLModElement: C,
  3758. HTMLObjectElement: C,
  3759. HTMLOListElement: C,
  3760. HTMLOptGroupElement: C,
  3761. HTMLOptionElement: C,
  3762. HTMLOptionsCollection: C,
  3763. HTMLOutputElement: C,
  3764. HTMLParagraphElement: C,
  3765. HTMLParamElement: C,
  3766. HTMLPictureElement: C,
  3767. HTMLPreElement: C,
  3768. HTMLProgressElement: C,
  3769. HTMLQuoteElement: C,
  3770. HTMLScriptElement: C,
  3771. HTMLSelectElement: C,
  3772. HTMLShadowElement: C,
  3773. HTMLSlotElement: C,
  3774. HTMLSourceElement: C,
  3775. HTMLSpanElement: C,
  3776. HTMLStyleElement: C,
  3777. HTMLTableCaptionElement: C,
  3778. HTMLTableCellElement: C,
  3779. HTMLTableColElement: C,
  3780. HTMLTableElement: C,
  3781. HTMLTableRowElement: C,
  3782. HTMLTableSectionElement: C,
  3783. HTMLTemplateElement: C,
  3784. HTMLTextAreaElement: C,
  3785. HTMLTimeElement: C,
  3786. HTMLTitleElement: C,
  3787. HTMLTrackElement: C,
  3788. HTMLUListElement: C,
  3789. HTMLUnknownElement: C,
  3790. HTMLVideoElement: C,
  3791. IDBCursor: C,
  3792. IDBCursorWithValue: C,
  3793. IDBDatabase: C,
  3794. IDBFactory: C,
  3795. IDBIndex: C,
  3796. IDBKeyRange: C,
  3797. IDBObjectStore: C,
  3798. IDBOpenDBRequest: C,
  3799. IDBRequest: C,
  3800. IDBTransaction: C,
  3801. IDBVersionChangeEvent: C,
  3802. IdleDeadline: C,
  3803. IIRFilterNode: C,
  3804. Image: C,
  3805. ImageBitmap: C,
  3806. ImageBitmapRenderingContext: C,
  3807. ImageCapture: C,
  3808. ImageData: C,
  3809. indexedDB: O,
  3810. innerHeight: O,
  3811. innerWidth: O,
  3812. InputEvent: C,
  3813. IntersectionObserver: C,
  3814. IntersectionObserverEntry: C,
  3815. isSecureContext: O,
  3816. KeyboardEvent: C,
  3817. KeyframeEffect: C,
  3818. length: O,
  3819. localStorage: O,
  3820. location: O,
  3821. Location: C,
  3822. locationbar: O,
  3823. matchMedia: O,
  3824. MediaDeviceInfo: C,
  3825. MediaDevices: C,
  3826. MediaElementAudioSourceNode: C,
  3827. MediaEncryptedEvent: C,
  3828. MediaError: C,
  3829. MediaKeyMessageEvent: C,
  3830. MediaKeySession: C,
  3831. MediaKeyStatusMap: C,
  3832. MediaKeySystemAccess: C,
  3833. MediaList: C,
  3834. MediaQueryList: C,
  3835. MediaQueryListEvent: C,
  3836. MediaRecorder: C,
  3837. MediaSettingsRange: C,
  3838. MediaSource: C,
  3839. MediaStream: C,
  3840. MediaStreamAudioDestinationNode: C,
  3841. MediaStreamAudioSourceNode: C,
  3842. MediaStreamEvent: C,
  3843. MediaStreamTrack: C,
  3844. MediaStreamTrackEvent: C,
  3845. menubar: O,
  3846. MessageChannel: C,
  3847. MessageEvent: C,
  3848. MessagePort: C,
  3849. MIDIAccess: C,
  3850. MIDIConnectionEvent: C,
  3851. MIDIInput: C,
  3852. MIDIInputMap: C,
  3853. MIDIMessageEvent: C,
  3854. MIDIOutput: C,
  3855. MIDIOutputMap: C,
  3856. MIDIPort: C,
  3857. MimeType: C,
  3858. MimeTypeArray: C,
  3859. MouseEvent: C,
  3860. moveBy: O,
  3861. moveTo: O,
  3862. MutationEvent: C,
  3863. MutationObserver: C,
  3864. MutationRecord: C,
  3865. name: O,
  3866. NamedNodeMap: C,
  3867. NavigationPreloadManager: C,
  3868. navigator: O,
  3869. Navigator: C,
  3870. NetworkInformation: C,
  3871. Node: C,
  3872. NodeFilter: O,
  3873. NodeIterator: C,
  3874. NodeList: C,
  3875. Notification: C,
  3876. OfflineAudioCompletionEvent: C,
  3877. OfflineAudioContext: C,
  3878. offscreenBuffering: O,
  3879. OffscreenCanvas: C,
  3880. open: O,
  3881. openDatabase: O,
  3882. Option: C,
  3883. origin: O,
  3884. OscillatorNode: C,
  3885. outerHeight: O,
  3886. outerWidth: O,
  3887. PageTransitionEvent: C,
  3888. pageXOffset: O,
  3889. pageYOffset: O,
  3890. PannerNode: C,
  3891. parent: O,
  3892. Path2D: C,
  3893. PaymentAddress: C,
  3894. PaymentRequest: C,
  3895. PaymentRequestUpdateEvent: C,
  3896. PaymentResponse: C,
  3897. performance: O,
  3898. Performance: C,
  3899. PerformanceEntry: C,
  3900. PerformanceLongTaskTiming: C,
  3901. PerformanceMark: C,
  3902. PerformanceMeasure: C,
  3903. PerformanceNavigation: C,
  3904. PerformanceNavigationTiming: C,
  3905. PerformanceObserver: C,
  3906. PerformanceObserverEntryList: C,
  3907. PerformancePaintTiming: C,
  3908. PerformanceResourceTiming: C,
  3909. PerformanceTiming: C,
  3910. PeriodicWave: C,
  3911. Permissions: C,
  3912. PermissionStatus: C,
  3913. personalbar: O,
  3914. PhotoCapabilities: C,
  3915. Plugin: C,
  3916. PluginArray: C,
  3917. PointerEvent: C,
  3918. PopStateEvent: C,
  3919. postMessage: O,
  3920. Presentation: C,
  3921. PresentationAvailability: C,
  3922. PresentationConnection: C,
  3923. PresentationConnectionAvailableEvent: C,
  3924. PresentationConnectionCloseEvent: C,
  3925. PresentationConnectionList: C,
  3926. PresentationReceiver: C,
  3927. PresentationRequest: C,
  3928. print: O,
  3929. ProcessingInstruction: C,
  3930. ProgressEvent: C,
  3931. PromiseRejectionEvent: C,
  3932. prompt: O,
  3933. PushManager: C,
  3934. PushSubscription: C,
  3935. PushSubscriptionOptions: C,
  3936. queueMicrotask: O,
  3937. RadioNodeList: C,
  3938. Range: C,
  3939. ReadableStream: C,
  3940. RemotePlayback: C,
  3941. removeEventListener: O,
  3942. Request: C,
  3943. requestAnimationFrame: O,
  3944. requestIdleCallback: O,
  3945. resizeBy: O,
  3946. ResizeObserver: C,
  3947. ResizeObserverEntry: C,
  3948. resizeTo: O,
  3949. Response: C,
  3950. RTCCertificate: C,
  3951. RTCDataChannel: C,
  3952. RTCDataChannelEvent: C,
  3953. RTCDtlsTransport: C,
  3954. RTCIceCandidate: C,
  3955. RTCIceTransport: C,
  3956. RTCPeerConnection: C,
  3957. RTCPeerConnectionIceEvent: C,
  3958. RTCRtpReceiver: C,
  3959. RTCRtpSender: C,
  3960. RTCSctpTransport: C,
  3961. RTCSessionDescription: C,
  3962. RTCStatsReport: C,
  3963. RTCTrackEvent: C,
  3964. screen: O,
  3965. Screen: C,
  3966. screenLeft: O,
  3967. ScreenOrientation: C,
  3968. screenTop: O,
  3969. screenX: O,
  3970. screenY: O,
  3971. ScriptProcessorNode: C,
  3972. scroll: O,
  3973. scrollbars: O,
  3974. scrollBy: O,
  3975. scrollTo: O,
  3976. scrollX: O,
  3977. scrollY: O,
  3978. SecurityPolicyViolationEvent: C,
  3979. Selection: C,
  3980. ServiceWorker: C,
  3981. ServiceWorkerContainer: C,
  3982. ServiceWorkerRegistration: C,
  3983. sessionStorage: O,
  3984. ShadowRoot: C,
  3985. SharedWorker: C,
  3986. SourceBuffer: C,
  3987. SourceBufferList: C,
  3988. speechSynthesis: O,
  3989. SpeechSynthesisEvent: C,
  3990. SpeechSynthesisUtterance: C,
  3991. StaticRange: C,
  3992. status: O,
  3993. statusbar: O,
  3994. StereoPannerNode: C,
  3995. stop: O,
  3996. Storage: C,
  3997. StorageEvent: C,
  3998. StorageManager: C,
  3999. styleMedia: O,
  4000. StyleSheet: C,
  4001. StyleSheetList: C,
  4002. SubtleCrypto: C,
  4003. SVGAElement: C,
  4004. SVGAngle: C,
  4005. SVGAnimatedAngle: C,
  4006. SVGAnimatedBoolean: C,
  4007. SVGAnimatedEnumeration: C,
  4008. SVGAnimatedInteger: C,
  4009. SVGAnimatedLength: C,
  4010. SVGAnimatedLengthList: C,
  4011. SVGAnimatedNumber: C,
  4012. SVGAnimatedNumberList: C,
  4013. SVGAnimatedPreserveAspectRatio: C,
  4014. SVGAnimatedRect: C,
  4015. SVGAnimatedString: C,
  4016. SVGAnimatedTransformList: C,
  4017. SVGAnimateElement: C,
  4018. SVGAnimateMotionElement: C,
  4019. SVGAnimateTransformElement: C,
  4020. SVGAnimationElement: C,
  4021. SVGCircleElement: C,
  4022. SVGClipPathElement: C,
  4023. SVGComponentTransferFunctionElement: C,
  4024. SVGDefsElement: C,
  4025. SVGDescElement: C,
  4026. SVGDiscardElement: C,
  4027. SVGElement: C,
  4028. SVGEllipseElement: C,
  4029. SVGFEBlendElement: C,
  4030. SVGFEColorMatrixElement: C,
  4031. SVGFEComponentTransferElement: C,
  4032. SVGFECompositeElement: C,
  4033. SVGFEConvolveMatrixElement: C,
  4034. SVGFEDiffuseLightingElement: C,
  4035. SVGFEDisplacementMapElement: C,
  4036. SVGFEDistantLightElement: C,
  4037. SVGFEDropShadowElement: C,
  4038. SVGFEFloodElement: C,
  4039. SVGFEFuncAElement: C,
  4040. SVGFEFuncBElement: C,
  4041. SVGFEFuncGElement: C,
  4042. SVGFEFuncRElement: C,
  4043. SVGFEGaussianBlurElement: C,
  4044. SVGFEImageElement: C,
  4045. SVGFEMergeElement: C,
  4046. SVGFEMergeNodeElement: C,
  4047. SVGFEMorphologyElement: C,
  4048. SVGFEOffsetElement: C,
  4049. SVGFEPointLightElement: C,
  4050. SVGFESpecularLightingElement: C,
  4051. SVGFESpotLightElement: C,
  4052. SVGFETileElement: C,
  4053. SVGFETurbulenceElement: C,
  4054. SVGFilterElement: C,
  4055. SVGForeignObjectElement: C,
  4056. SVGGElement: C,
  4057. SVGGeometryElement: C,
  4058. SVGGradientElement: C,
  4059. SVGGraphicsElement: C,
  4060. SVGImageElement: C,
  4061. SVGLength: C,
  4062. SVGLengthList: C,
  4063. SVGLinearGradientElement: C,
  4064. SVGLineElement: C,
  4065. SVGMarkerElement: C,
  4066. SVGMaskElement: C,
  4067. SVGMatrix: C,
  4068. SVGMetadataElement: C,
  4069. SVGMPathElement: C,
  4070. SVGNumber: C,
  4071. SVGNumberList: C,
  4072. SVGPathElement: C,
  4073. SVGPatternElement: C,
  4074. SVGPoint: C,
  4075. SVGPointList: C,
  4076. SVGPolygonElement: C,
  4077. SVGPolylineElement: C,
  4078. SVGPreserveAspectRatio: C,
  4079. SVGRadialGradientElement: C,
  4080. SVGRect: C,
  4081. SVGRectElement: C,
  4082. SVGScriptElement: C,
  4083. SVGSetElement: C,
  4084. SVGStopElement: C,
  4085. SVGStringList: C,
  4086. SVGStyleElement: C,
  4087. SVGSVGElement: C,
  4088. SVGSwitchElement: C,
  4089. SVGSymbolElement: C,
  4090. SVGTextContentElement: C,
  4091. SVGTextElement: C,
  4092. SVGTextPathElement: C,
  4093. SVGTextPositioningElement: C,
  4094. SVGTitleElement: C,
  4095. SVGTransform: C,
  4096. SVGTransformList: C,
  4097. SVGTSpanElement: C,
  4098. SVGUnitTypes: C,
  4099. SVGUseElement: C,
  4100. SVGViewElement: C,
  4101. TaskAttributionTiming: C,
  4102. Text: C,
  4103. TextEvent: C,
  4104. TextMetrics: C,
  4105. TextTrack: C,
  4106. TextTrackCue: C,
  4107. TextTrackCueList: C,
  4108. TextTrackList: C,
  4109. TimeRanges: C,
  4110. toolbar: O,
  4111. top: O,
  4112. Touch: C,
  4113. TouchEvent: C,
  4114. TouchList: C,
  4115. TrackEvent: C,
  4116. TransitionEvent: C,
  4117. TreeWalker: C,
  4118. UIEvent: C,
  4119. ValidityState: C,
  4120. visualViewport: O,
  4121. VisualViewport: C,
  4122. VTTCue: C,
  4123. WaveShaperNode: C,
  4124. WebAssembly: O,
  4125. WebGL2RenderingContext: C,
  4126. WebGLActiveInfo: C,
  4127. WebGLBuffer: C,
  4128. WebGLContextEvent: C,
  4129. WebGLFramebuffer: C,
  4130. WebGLProgram: C,
  4131. WebGLQuery: C,
  4132. WebGLRenderbuffer: C,
  4133. WebGLRenderingContext: C,
  4134. WebGLSampler: C,
  4135. WebGLShader: C,
  4136. WebGLShaderPrecisionFormat: C,
  4137. WebGLSync: C,
  4138. WebGLTexture: C,
  4139. WebGLTransformFeedback: C,
  4140. WebGLUniformLocation: C,
  4141. WebGLVertexArrayObject: C,
  4142. WebSocket: C,
  4143. WheelEvent: C,
  4144. Window: C,
  4145. Worker: C,
  4146. WritableStream: C,
  4147. XMLDocument: C,
  4148. XMLHttpRequest: C,
  4149. XMLHttpRequestEventTarget: C,
  4150. XMLHttpRequestUpload: C,
  4151. XMLSerializer: C,
  4152. XPathEvaluator: C,
  4153. XPathExpression: C,
  4154. XPathResult: C,
  4155. XSLTProcessor: C
  4156. };
  4157. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4158. knownGlobals[global] = knownGlobals;
  4159. }
  4160. function getGlobalAtPath(path) {
  4161. let currentGlobal = knownGlobals;
  4162. for (const pathSegment of path) {
  4163. if (typeof pathSegment !== 'string') {
  4164. return null;
  4165. }
  4166. currentGlobal = currentGlobal[pathSegment];
  4167. if (!currentGlobal) {
  4168. return null;
  4169. }
  4170. }
  4171. return currentGlobal[ValueProperties];
  4172. }
  4173. function isPureGlobal(path) {
  4174. const globalAtPath = getGlobalAtPath(path);
  4175. return globalAtPath !== null && globalAtPath.pure;
  4176. }
  4177. function isGlobalMember(path) {
  4178. if (path.length === 1) {
  4179. return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
  4180. }
  4181. return getGlobalAtPath(path.slice(0, -1)) !== null;
  4182. }
  4183. class GlobalVariable extends Variable {
  4184. constructor() {
  4185. super(...arguments);
  4186. this.isReassigned = true;
  4187. }
  4188. hasEffectsWhenAccessedAtPath(path) {
  4189. return !isGlobalMember([this.name, ...path]);
  4190. }
  4191. hasEffectsWhenCalledAtPath(path) {
  4192. return !isPureGlobal([this.name, ...path]);
  4193. }
  4194. }
  4195. const tdzVariableKinds = {
  4196. __proto__: null,
  4197. class: true,
  4198. const: true,
  4199. let: true,
  4200. var: true
  4201. };
  4202. class Identifier extends NodeBase {
  4203. constructor() {
  4204. super(...arguments);
  4205. this.variable = null;
  4206. this.deoptimized = false;
  4207. this.isTDZAccess = null;
  4208. }
  4209. addExportedVariables(variables, exportNamesByVariable) {
  4210. if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
  4211. variables.push(this.variable);
  4212. }
  4213. }
  4214. bind() {
  4215. if (this.variable === null && is_reference(this, this.parent)) {
  4216. this.variable = this.scope.findVariable(this.name);
  4217. this.variable.addReference(this);
  4218. }
  4219. }
  4220. declare(kind, init) {
  4221. let variable;
  4222. const { treeshake } = this.context.options;
  4223. switch (kind) {
  4224. case 'var':
  4225. variable = this.scope.addDeclaration(this, this.context, init, true);
  4226. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  4227. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  4228. variable.markInitializersForDeoptimization();
  4229. }
  4230. break;
  4231. case 'function':
  4232. // in strict mode, functions are only hoisted within a scope but not across block scopes
  4233. variable = this.scope.addDeclaration(this, this.context, init, false);
  4234. break;
  4235. case 'let':
  4236. case 'const':
  4237. case 'class':
  4238. variable = this.scope.addDeclaration(this, this.context, init, false);
  4239. break;
  4240. case 'parameter':
  4241. variable = this.scope.addParameterDeclaration(this);
  4242. break;
  4243. /* istanbul ignore next */
  4244. default:
  4245. /* istanbul ignore next */
  4246. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  4247. }
  4248. variable.kind = kind;
  4249. return [(this.variable = variable)];
  4250. }
  4251. deoptimizePath(path) {
  4252. if (path.length === 0 && !this.scope.contains(this.name)) {
  4253. this.disallowImportReassignment();
  4254. }
  4255. this.variable.deoptimizePath(path);
  4256. }
  4257. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4258. this.variable.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  4259. }
  4260. getLiteralValueAtPath(path, recursionTracker, origin) {
  4261. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  4262. }
  4263. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4264. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  4265. }
  4266. hasEffects() {
  4267. if (!this.deoptimized)
  4268. this.applyDeoptimizations();
  4269. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  4270. return true;
  4271. }
  4272. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  4273. this.variable instanceof GlobalVariable &&
  4274. this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
  4275. }
  4276. hasEffectsWhenAccessedAtPath(path, context) {
  4277. return (this.variable !== null &&
  4278. this.getVariableRespectingTDZ().hasEffectsWhenAccessedAtPath(path, context));
  4279. }
  4280. hasEffectsWhenAssignedAtPath(path, context) {
  4281. return (!this.variable ||
  4282. (path.length > 0
  4283. ? this.getVariableRespectingTDZ()
  4284. : this.variable).hasEffectsWhenAssignedAtPath(path, context));
  4285. }
  4286. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4287. return (!this.variable ||
  4288. this.getVariableRespectingTDZ().hasEffectsWhenCalledAtPath(path, callOptions, context));
  4289. }
  4290. include() {
  4291. if (!this.deoptimized)
  4292. this.applyDeoptimizations();
  4293. if (!this.included) {
  4294. this.included = true;
  4295. if (this.variable !== null) {
  4296. this.context.includeVariableInModule(this.variable);
  4297. }
  4298. }
  4299. }
  4300. includeCallArguments(context, args) {
  4301. this.getVariableRespectingTDZ().includeCallArguments(context, args);
  4302. }
  4303. isPossibleTDZ() {
  4304. // return cached value to avoid issues with the next tree-shaking pass
  4305. if (this.isTDZAccess !== null)
  4306. return this.isTDZAccess;
  4307. if (!(this.variable instanceof LocalVariable) ||
  4308. !this.variable.kind ||
  4309. !(this.variable.kind in tdzVariableKinds)) {
  4310. return (this.isTDZAccess = false);
  4311. }
  4312. let decl_id;
  4313. if (this.variable.declarations &&
  4314. this.variable.declarations.length === 1 &&
  4315. (decl_id = this.variable.declarations[0]) &&
  4316. this.start < decl_id.start &&
  4317. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  4318. // a variable accessed before its declaration
  4319. // in the same function or at top level of module
  4320. return (this.isTDZAccess = true);
  4321. }
  4322. if (!this.variable.initReached) {
  4323. // Either a const/let TDZ violation or
  4324. // var use before declaration was encountered.
  4325. return (this.isTDZAccess = true);
  4326. }
  4327. return (this.isTDZAccess = false);
  4328. }
  4329. markDeclarationReached() {
  4330. this.variable.initReached = true;
  4331. }
  4332. render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  4333. if (this.variable) {
  4334. const name = this.variable.getName();
  4335. if (name !== this.name) {
  4336. code.overwrite(this.start, this.end, name, {
  4337. contentOnly: true,
  4338. storeName: true
  4339. });
  4340. if (isShorthandProperty) {
  4341. code.prependRight(this.start, `${this.name}: `);
  4342. }
  4343. }
  4344. // In strict mode, any variable named "eval" must be the actual "eval" function
  4345. if (name === 'eval' &&
  4346. renderedParentType === CallExpression$1 &&
  4347. isCalleeOfRenderedParent) {
  4348. code.appendRight(this.start, '0, ');
  4349. }
  4350. }
  4351. }
  4352. applyDeoptimizations() {
  4353. this.deoptimized = true;
  4354. if (this.variable !== null && this.variable instanceof LocalVariable) {
  4355. this.variable.consolidateInitializers();
  4356. this.context.requestTreeshakingPass();
  4357. }
  4358. }
  4359. disallowImportReassignment() {
  4360. return this.context.error({
  4361. code: 'ILLEGAL_REASSIGNMENT',
  4362. message: `Illegal reassignment to import '${this.name}'`
  4363. }, this.start);
  4364. }
  4365. getVariableRespectingTDZ() {
  4366. if (this.isPossibleTDZ()) {
  4367. return UNKNOWN_EXPRESSION;
  4368. }
  4369. return this.variable;
  4370. }
  4371. }
  4372. function closestParentFunctionOrProgram(node) {
  4373. while (node && !/^Program|Function/.test(node.type)) {
  4374. node = node.parent;
  4375. }
  4376. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  4377. return node;
  4378. }
  4379. const EVENT_ACCESSED = 0;
  4380. const EVENT_ASSIGNED = 1;
  4381. const EVENT_CALLED = 2;
  4382. class MethodBase extends NodeBase {
  4383. constructor() {
  4384. super(...arguments);
  4385. this.accessedValue = null;
  4386. this.accessorCallOptions = {
  4387. args: NO_ARGS,
  4388. thisParam: null,
  4389. withNew: false
  4390. };
  4391. }
  4392. // As getter properties directly receive their values from fixed function
  4393. // expressions, there is no known situation where a getter is deoptimized.
  4394. deoptimizeCache() { }
  4395. deoptimizePath(path) {
  4396. this.getAccessedValue().deoptimizePath(path);
  4397. }
  4398. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4399. if (event === EVENT_ACCESSED && this.kind === 'get' && path.length === 0) {
  4400. return this.value.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParameter, recursionTracker);
  4401. }
  4402. if (event === EVENT_ASSIGNED && this.kind === 'set' && path.length === 0) {
  4403. return this.value.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParameter, recursionTracker);
  4404. }
  4405. this.getAccessedValue().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  4406. }
  4407. getLiteralValueAtPath(path, recursionTracker, origin) {
  4408. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  4409. }
  4410. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4411. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  4412. }
  4413. hasEffects(context) {
  4414. return this.key.hasEffects(context);
  4415. }
  4416. hasEffectsWhenAccessedAtPath(path, context) {
  4417. if (this.kind === 'get' && path.length === 0) {
  4418. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  4419. }
  4420. return this.getAccessedValue().hasEffectsWhenAccessedAtPath(path, context);
  4421. }
  4422. hasEffectsWhenAssignedAtPath(path, context) {
  4423. if (this.kind === 'set') {
  4424. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  4425. }
  4426. return this.getAccessedValue().hasEffectsWhenAssignedAtPath(path, context);
  4427. }
  4428. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4429. return this.getAccessedValue().hasEffectsWhenCalledAtPath(path, callOptions, context);
  4430. }
  4431. getAccessedValue() {
  4432. if (this.accessedValue === null) {
  4433. if (this.kind === 'get') {
  4434. this.accessedValue = UNKNOWN_EXPRESSION;
  4435. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, SHARED_RECURSION_TRACKER, this));
  4436. }
  4437. else {
  4438. return (this.accessedValue = this.value);
  4439. }
  4440. }
  4441. return this.accessedValue;
  4442. }
  4443. }
  4444. class MethodDefinition extends MethodBase {
  4445. }
  4446. const INTEGER_REG_EXP = /^\d+$/;
  4447. class ObjectEntity extends ExpressionEntity {
  4448. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4449. // and we assume there are no setters or getters
  4450. constructor(properties, prototypeExpression, immutable = false) {
  4451. super();
  4452. this.prototypeExpression = prototypeExpression;
  4453. this.immutable = immutable;
  4454. this.allProperties = [];
  4455. this.deoptimizedPaths = Object.create(null);
  4456. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4457. this.gettersByKey = Object.create(null);
  4458. this.hasUnknownDeoptimizedInteger = false;
  4459. this.hasUnknownDeoptimizedProperty = false;
  4460. this.propertiesAndGettersByKey = Object.create(null);
  4461. this.propertiesAndSettersByKey = Object.create(null);
  4462. this.settersByKey = Object.create(null);
  4463. this.thisParametersToBeDeoptimized = new Set();
  4464. this.unknownIntegerProps = [];
  4465. this.unmatchableGetters = [];
  4466. this.unmatchablePropertiesAndGetters = [];
  4467. this.unmatchableSetters = [];
  4468. if (Array.isArray(properties)) {
  4469. this.buildPropertyMaps(properties);
  4470. }
  4471. else {
  4472. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4473. for (const propertiesForKey of Object.values(properties)) {
  4474. this.allProperties.push(...propertiesForKey);
  4475. }
  4476. }
  4477. }
  4478. deoptimizeAllProperties() {
  4479. var _a;
  4480. if (this.hasUnknownDeoptimizedProperty) {
  4481. return;
  4482. }
  4483. this.hasUnknownDeoptimizedProperty = true;
  4484. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4485. for (const property of properties) {
  4486. property.deoptimizePath(UNKNOWN_PATH);
  4487. }
  4488. }
  4489. // While the prototype itself cannot be mutated, each property can
  4490. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4491. this.deoptimizeCachedEntities();
  4492. }
  4493. deoptimizeIntegerProperties() {
  4494. if (this.hasUnknownDeoptimizedProperty || this.hasUnknownDeoptimizedInteger) {
  4495. return;
  4496. }
  4497. this.hasUnknownDeoptimizedInteger = true;
  4498. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4499. if (INTEGER_REG_EXP.test(key)) {
  4500. for (const property of propertiesAndGetters) {
  4501. property.deoptimizePath(UNKNOWN_PATH);
  4502. }
  4503. }
  4504. }
  4505. this.deoptimizeCachedIntegerEntities();
  4506. }
  4507. deoptimizePath(path) {
  4508. var _a;
  4509. if (this.hasUnknownDeoptimizedProperty || this.immutable)
  4510. return;
  4511. const key = path[0];
  4512. if (path.length === 1) {
  4513. if (typeof key !== 'string') {
  4514. if (key === UnknownInteger) {
  4515. return this.deoptimizeIntegerProperties();
  4516. }
  4517. return this.deoptimizeAllProperties();
  4518. }
  4519. if (!this.deoptimizedPaths[key]) {
  4520. this.deoptimizedPaths[key] = true;
  4521. // we only deoptimizeCache exact matches as in all other cases,
  4522. // we do not return a literal value or return expression
  4523. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4524. if (expressionsToBeDeoptimized) {
  4525. for (const expression of expressionsToBeDeoptimized) {
  4526. expression.deoptimizeCache();
  4527. }
  4528. }
  4529. }
  4530. }
  4531. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4532. for (const property of typeof key === 'string'
  4533. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  4534. : this.allProperties) {
  4535. property.deoptimizePath(subPath);
  4536. }
  4537. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [UnknownKey, UnknownKey] : path);
  4538. }
  4539. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4540. var _a;
  4541. const [key, ...subPath] = path;
  4542. if (this.hasUnknownDeoptimizedProperty ||
  4543. // single paths that are deoptimized will not become getters or setters
  4544. ((event === EVENT_CALLED || path.length > 1) &&
  4545. typeof key === 'string' &&
  4546. this.deoptimizedPaths[key])) {
  4547. thisParameter.deoptimizePath(UNKNOWN_PATH);
  4548. return;
  4549. }
  4550. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = event === EVENT_CALLED || path.length > 1
  4551. ? [
  4552. this.propertiesAndGettersByKey,
  4553. this.propertiesAndGettersByKey,
  4554. this.unmatchablePropertiesAndGetters
  4555. ]
  4556. : event === EVENT_ACCESSED
  4557. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4558. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4559. if (typeof key === 'string') {
  4560. if (propertiesForExactMatchByKey[key]) {
  4561. const properties = relevantPropertiesByKey[key];
  4562. if (properties) {
  4563. for (const property of properties) {
  4564. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4565. }
  4566. }
  4567. if (!this.immutable) {
  4568. this.thisParametersToBeDeoptimized.add(thisParameter);
  4569. }
  4570. return;
  4571. }
  4572. for (const property of relevantUnmatchableProperties) {
  4573. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4574. }
  4575. if (INTEGER_REG_EXP.test(key)) {
  4576. for (const property of this.unknownIntegerProps) {
  4577. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4578. }
  4579. }
  4580. }
  4581. else {
  4582. for (const properties of Object.values(relevantPropertiesByKey).concat([
  4583. relevantUnmatchableProperties
  4584. ])) {
  4585. for (const property of properties) {
  4586. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4587. }
  4588. }
  4589. for (const property of this.unknownIntegerProps) {
  4590. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4591. }
  4592. }
  4593. if (!this.immutable) {
  4594. this.thisParametersToBeDeoptimized.add(thisParameter);
  4595. }
  4596. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  4597. }
  4598. getLiteralValueAtPath(path, recursionTracker, origin) {
  4599. if (path.length === 0) {
  4600. return UnknownValue;
  4601. }
  4602. const key = path[0];
  4603. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4604. if (expressionAtPath) {
  4605. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4606. }
  4607. if (this.prototypeExpression) {
  4608. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4609. }
  4610. if (path.length === 1) {
  4611. return undefined;
  4612. }
  4613. return UnknownValue;
  4614. }
  4615. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4616. if (path.length === 0) {
  4617. return UNKNOWN_EXPRESSION;
  4618. }
  4619. const key = path[0];
  4620. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4621. if (expressionAtPath) {
  4622. return expressionAtPath.getReturnExpressionWhenCalledAtPath(path.slice(1), callOptions, recursionTracker, origin);
  4623. }
  4624. if (this.prototypeExpression) {
  4625. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  4626. }
  4627. return UNKNOWN_EXPRESSION;
  4628. }
  4629. hasEffectsWhenAccessedAtPath(path, context) {
  4630. const [key, ...subPath] = path;
  4631. if (path.length > 1) {
  4632. if (typeof key !== 'string') {
  4633. return true;
  4634. }
  4635. const expressionAtPath = this.getMemberExpression(key);
  4636. if (expressionAtPath) {
  4637. return expressionAtPath.hasEffectsWhenAccessedAtPath(subPath, context);
  4638. }
  4639. if (this.prototypeExpression) {
  4640. return this.prototypeExpression.hasEffectsWhenAccessedAtPath(path, context);
  4641. }
  4642. return true;
  4643. }
  4644. if (this.hasUnknownDeoptimizedProperty)
  4645. return true;
  4646. if (typeof key === 'string') {
  4647. if (this.propertiesAndGettersByKey[key]) {
  4648. const getters = this.gettersByKey[key];
  4649. if (getters) {
  4650. for (const getter of getters) {
  4651. if (getter.hasEffectsWhenAccessedAtPath(subPath, context))
  4652. return true;
  4653. }
  4654. }
  4655. return false;
  4656. }
  4657. for (const getter of this.unmatchableGetters) {
  4658. if (getter.hasEffectsWhenAccessedAtPath(subPath, context)) {
  4659. return true;
  4660. }
  4661. }
  4662. }
  4663. else {
  4664. for (const getters of Object.values(this.gettersByKey).concat([this.unmatchableGetters])) {
  4665. for (const getter of getters) {
  4666. if (getter.hasEffectsWhenAccessedAtPath(subPath, context))
  4667. return true;
  4668. }
  4669. }
  4670. }
  4671. if (this.prototypeExpression) {
  4672. return this.prototypeExpression.hasEffectsWhenAccessedAtPath(path, context);
  4673. }
  4674. return false;
  4675. }
  4676. hasEffectsWhenAssignedAtPath(path, context) {
  4677. const [key, ...subPath] = path;
  4678. if (path.length > 1) {
  4679. if (typeof key !== 'string') {
  4680. return true;
  4681. }
  4682. const expressionAtPath = this.getMemberExpression(key);
  4683. if (expressionAtPath) {
  4684. return expressionAtPath.hasEffectsWhenAssignedAtPath(subPath, context);
  4685. }
  4686. if (this.prototypeExpression) {
  4687. return this.prototypeExpression.hasEffectsWhenAssignedAtPath(path, context);
  4688. }
  4689. return true;
  4690. }
  4691. if (this.hasUnknownDeoptimizedProperty)
  4692. return true;
  4693. // We do not need to test for unknown properties as in that case, hasUnknownDeoptimizedProperty is true
  4694. if (typeof key === 'string') {
  4695. if (this.propertiesAndSettersByKey[key]) {
  4696. const setters = this.settersByKey[key];
  4697. if (setters) {
  4698. for (const setter of setters) {
  4699. if (setter.hasEffectsWhenAssignedAtPath(subPath, context))
  4700. return true;
  4701. }
  4702. }
  4703. return false;
  4704. }
  4705. for (const property of this.unmatchableSetters) {
  4706. if (property.hasEffectsWhenAssignedAtPath(subPath, context)) {
  4707. return true;
  4708. }
  4709. }
  4710. }
  4711. if (this.prototypeExpression) {
  4712. return this.prototypeExpression.hasEffectsWhenAssignedAtPath(path, context);
  4713. }
  4714. return false;
  4715. }
  4716. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4717. const key = path[0];
  4718. const expressionAtPath = this.getMemberExpression(key);
  4719. if (expressionAtPath) {
  4720. return expressionAtPath.hasEffectsWhenCalledAtPath(path.slice(1), callOptions, context);
  4721. }
  4722. if (this.prototypeExpression) {
  4723. return this.prototypeExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  4724. }
  4725. return true;
  4726. }
  4727. buildPropertyMaps(properties) {
  4728. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  4729. const unmatchablePropertiesAndSetters = [];
  4730. for (let index = properties.length - 1; index >= 0; index--) {
  4731. const { key, kind, property } = properties[index];
  4732. allProperties.push(property);
  4733. if (typeof key !== 'string') {
  4734. if (key === UnknownInteger) {
  4735. unknownIntegerProps.push(property);
  4736. continue;
  4737. }
  4738. if (kind === 'set')
  4739. unmatchableSetters.push(property);
  4740. if (kind === 'get')
  4741. unmatchableGetters.push(property);
  4742. if (kind !== 'get')
  4743. unmatchablePropertiesAndSetters.push(property);
  4744. if (kind !== 'set')
  4745. unmatchablePropertiesAndGetters.push(property);
  4746. }
  4747. else {
  4748. if (kind === 'set') {
  4749. if (!propertiesAndSettersByKey[key]) {
  4750. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4751. settersByKey[key] = [property, ...unmatchableSetters];
  4752. }
  4753. }
  4754. else if (kind === 'get') {
  4755. if (!propertiesAndGettersByKey[key]) {
  4756. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4757. gettersByKey[key] = [property, ...unmatchableGetters];
  4758. }
  4759. }
  4760. else {
  4761. if (!propertiesAndSettersByKey[key]) {
  4762. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4763. }
  4764. if (!propertiesAndGettersByKey[key]) {
  4765. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4766. }
  4767. }
  4768. }
  4769. }
  4770. }
  4771. deoptimizeCachedEntities() {
  4772. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  4773. for (const expression of expressionsToBeDeoptimized) {
  4774. expression.deoptimizeCache();
  4775. }
  4776. }
  4777. for (const expression of this.thisParametersToBeDeoptimized) {
  4778. expression.deoptimizePath(UNKNOWN_PATH);
  4779. }
  4780. }
  4781. deoptimizeCachedIntegerEntities() {
  4782. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  4783. if (INTEGER_REG_EXP.test(key)) {
  4784. for (const expression of expressionsToBeDeoptimized) {
  4785. expression.deoptimizeCache();
  4786. }
  4787. }
  4788. }
  4789. for (const expression of this.thisParametersToBeDeoptimized) {
  4790. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4791. }
  4792. }
  4793. getMemberExpression(key) {
  4794. if (this.hasUnknownDeoptimizedProperty ||
  4795. typeof key !== 'string' ||
  4796. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  4797. this.deoptimizedPaths[key]) {
  4798. return UNKNOWN_EXPRESSION;
  4799. }
  4800. const properties = this.propertiesAndGettersByKey[key];
  4801. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  4802. return properties[0];
  4803. }
  4804. if (properties ||
  4805. this.unmatchablePropertiesAndGetters.length > 0 ||
  4806. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  4807. return UNKNOWN_EXPRESSION;
  4808. }
  4809. return null;
  4810. }
  4811. getMemberExpressionAndTrackDeopt(key, origin) {
  4812. if (typeof key !== 'string') {
  4813. return UNKNOWN_EXPRESSION;
  4814. }
  4815. const expression = this.getMemberExpression(key);
  4816. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  4817. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  4818. this.expressionsToBeDeoptimizedByKey[key] || []);
  4819. expressionsToBeDeoptimized.push(origin);
  4820. }
  4821. return expression;
  4822. }
  4823. }
  4824. class ObjectMember extends ExpressionEntity {
  4825. constructor(object, key) {
  4826. super();
  4827. this.object = object;
  4828. this.key = key;
  4829. }
  4830. deoptimizePath(path) {
  4831. this.object.deoptimizePath([this.key, ...path]);
  4832. }
  4833. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4834. this.object.deoptimizeThisOnEventAtPath(event, [this.key, ...path], thisParameter, recursionTracker);
  4835. }
  4836. getLiteralValueAtPath(path, recursionTracker, origin) {
  4837. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  4838. }
  4839. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4840. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], callOptions, recursionTracker, origin);
  4841. }
  4842. hasEffectsWhenAccessedAtPath(path, context) {
  4843. if (path.length === 0)
  4844. return false;
  4845. return this.object.hasEffectsWhenAccessedAtPath([this.key, ...path], context);
  4846. }
  4847. hasEffectsWhenAssignedAtPath(path, context) {
  4848. return this.object.hasEffectsWhenAssignedAtPath([this.key, ...path], context);
  4849. }
  4850. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4851. return this.object.hasEffectsWhenCalledAtPath([this.key, ...path], callOptions, context);
  4852. }
  4853. }
  4854. class Method extends ExpressionEntity {
  4855. constructor(description) {
  4856. super();
  4857. this.description = description;
  4858. }
  4859. deoptimizeThisOnEventAtPath(event, path, thisParameter) {
  4860. if (event === EVENT_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4861. thisParameter.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4862. }
  4863. }
  4864. getReturnExpressionWhenCalledAtPath(path, callOptions) {
  4865. if (path.length > 0) {
  4866. return UNKNOWN_EXPRESSION;
  4867. }
  4868. return (this.description.returnsPrimitive ||
  4869. (this.description.returns === 'self'
  4870. ? callOptions.thisParam || UNKNOWN_EXPRESSION
  4871. : this.description.returns()));
  4872. }
  4873. hasEffectsWhenAccessedAtPath(path) {
  4874. return path.length > 1;
  4875. }
  4876. hasEffectsWhenAssignedAtPath(path) {
  4877. return path.length > 0;
  4878. }
  4879. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4880. var _a, _b;
  4881. if (path.length > 0 ||
  4882. (this.description.mutatesSelfAsArray === true &&
  4883. ((_a = callOptions.thisParam) === null || _a === void 0 ? void 0 : _a.hasEffectsWhenAssignedAtPath(UNKNOWN_INTEGER_PATH, context)))) {
  4884. return true;
  4885. }
  4886. if (!this.description.callsArgs) {
  4887. return false;
  4888. }
  4889. for (const argIndex of this.description.callsArgs) {
  4890. if ((_b = callOptions.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  4891. args: NO_ARGS,
  4892. thisParam: null,
  4893. withNew: false
  4894. }, context)) {
  4895. return true;
  4896. }
  4897. }
  4898. return false;
  4899. }
  4900. includeCallArguments(context, args) {
  4901. for (const arg of args) {
  4902. arg.include(context, false);
  4903. }
  4904. }
  4905. }
  4906. const METHOD_RETURNS_BOOLEAN = [
  4907. new Method({
  4908. callsArgs: null,
  4909. mutatesSelfAsArray: false,
  4910. returns: null,
  4911. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4912. })
  4913. ];
  4914. const METHOD_RETURNS_STRING = [
  4915. new Method({
  4916. callsArgs: null,
  4917. mutatesSelfAsArray: false,
  4918. returns: null,
  4919. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4920. })
  4921. ];
  4922. const METHOD_RETURNS_NUMBER = [
  4923. new Method({
  4924. callsArgs: null,
  4925. mutatesSelfAsArray: false,
  4926. returns: null,
  4927. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4928. })
  4929. ];
  4930. const METHOD_RETURNS_UNKNOWN = [
  4931. new Method({
  4932. callsArgs: null,
  4933. mutatesSelfAsArray: false,
  4934. returns: null,
  4935. returnsPrimitive: UNKNOWN_EXPRESSION
  4936. })
  4937. ];
  4938. const OBJECT_PROTOTYPE = new ObjectEntity({
  4939. __proto__: null,
  4940. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  4941. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  4942. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  4943. toLocaleString: METHOD_RETURNS_STRING,
  4944. toString: METHOD_RETURNS_STRING,
  4945. valueOf: METHOD_RETURNS_UNKNOWN
  4946. }, null, true);
  4947. class ClassNode extends NodeBase {
  4948. constructor() {
  4949. super(...arguments);
  4950. this.objectEntity = null;
  4951. }
  4952. createScope(parentScope) {
  4953. this.scope = new ChildScope(parentScope);
  4954. }
  4955. deoptimizeCache() {
  4956. this.getObjectEntity().deoptimizeAllProperties();
  4957. }
  4958. deoptimizePath(path) {
  4959. this.getObjectEntity().deoptimizePath(path);
  4960. }
  4961. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4962. this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  4963. }
  4964. getLiteralValueAtPath(path, recursionTracker, origin) {
  4965. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  4966. }
  4967. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4968. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  4969. }
  4970. hasEffects(context) {
  4971. var _a, _b;
  4972. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  4973. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  4974. return initEffect || super.hasEffects(context);
  4975. }
  4976. hasEffectsWhenAccessedAtPath(path, context) {
  4977. return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
  4978. }
  4979. hasEffectsWhenAssignedAtPath(path, context) {
  4980. return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
  4981. }
  4982. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4983. if (path.length === 0) {
  4984. return (!callOptions.withNew ||
  4985. (this.classConstructor !== null
  4986. ? this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context)
  4987. : this.superClass !== null &&
  4988. this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
  4989. }
  4990. else {
  4991. return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
  4992. }
  4993. }
  4994. include(context, includeChildrenRecursively) {
  4995. var _a;
  4996. this.included = true;
  4997. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  4998. this.body.include(context, includeChildrenRecursively);
  4999. if (this.id) {
  5000. this.id.markDeclarationReached();
  5001. this.id.include();
  5002. }
  5003. }
  5004. initialise() {
  5005. var _a;
  5006. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  5007. for (const method of this.body.body) {
  5008. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  5009. this.classConstructor = method;
  5010. return;
  5011. }
  5012. }
  5013. this.classConstructor = null;
  5014. }
  5015. getObjectEntity() {
  5016. if (this.objectEntity !== null) {
  5017. return this.objectEntity;
  5018. }
  5019. const staticProperties = [];
  5020. const dynamicMethods = [];
  5021. for (const definition of this.body.body) {
  5022. const properties = definition.static ? staticProperties : dynamicMethods;
  5023. const definitionKind = definition.kind;
  5024. // Note that class fields do not end up on the prototype
  5025. if (properties === dynamicMethods && !definitionKind)
  5026. continue;
  5027. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  5028. let key;
  5029. if (definition.computed) {
  5030. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5031. if (keyValue === UnknownValue) {
  5032. properties.push({ key: UnknownKey, kind, property: definition });
  5033. continue;
  5034. }
  5035. else {
  5036. key = String(keyValue);
  5037. }
  5038. }
  5039. else {
  5040. key =
  5041. definition.key instanceof Identifier
  5042. ? definition.key.name
  5043. : String(definition.key.value);
  5044. }
  5045. properties.push({ key, kind, property: definition });
  5046. }
  5047. staticProperties.unshift({
  5048. key: 'prototype',
  5049. kind: 'init',
  5050. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  5051. });
  5052. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  5053. }
  5054. }
  5055. class ClassDeclaration extends ClassNode {
  5056. initialise() {
  5057. super.initialise();
  5058. if (this.id !== null) {
  5059. this.id.variable.isId = true;
  5060. }
  5061. }
  5062. parseNode(esTreeNode) {
  5063. if (esTreeNode.id !== null) {
  5064. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  5065. }
  5066. super.parseNode(esTreeNode);
  5067. }
  5068. render(code, options) {
  5069. if (options.format === 'system' &&
  5070. this.id &&
  5071. options.exportNamesByVariable.has(this.id.variable)) {
  5072. code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
  5073. }
  5074. super.render(code, options);
  5075. }
  5076. }
  5077. class ArgumentsVariable extends LocalVariable {
  5078. constructor(context) {
  5079. super('arguments', null, UNKNOWN_EXPRESSION, context);
  5080. }
  5081. hasEffectsWhenAccessedAtPath(path) {
  5082. return path.length > 1;
  5083. }
  5084. hasEffectsWhenAssignedAtPath() {
  5085. return true;
  5086. }
  5087. hasEffectsWhenCalledAtPath() {
  5088. return true;
  5089. }
  5090. }
  5091. class ThisVariable extends LocalVariable {
  5092. constructor(context) {
  5093. super('this', null, null, context);
  5094. this.deoptimizedPaths = [];
  5095. this.entitiesToBeDeoptimized = new Set();
  5096. this.thisDeoptimizationList = [];
  5097. this.thisDeoptimizations = new DiscriminatedPathTracker();
  5098. }
  5099. addEntityToBeDeoptimized(entity) {
  5100. for (const path of this.deoptimizedPaths) {
  5101. entity.deoptimizePath(path);
  5102. }
  5103. for (const thisDeoptimization of this.thisDeoptimizationList) {
  5104. this.applyThisDeoptimizationEvent(entity, thisDeoptimization);
  5105. }
  5106. this.entitiesToBeDeoptimized.add(entity);
  5107. }
  5108. deoptimizePath(path) {
  5109. if (path.length === 0 ||
  5110. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5111. return;
  5112. }
  5113. this.deoptimizedPaths.push(path);
  5114. for (const entity of this.entitiesToBeDeoptimized) {
  5115. entity.deoptimizePath(path);
  5116. }
  5117. }
  5118. deoptimizeThisOnEventAtPath(event, path, thisParameter) {
  5119. const thisDeoptimization = {
  5120. event,
  5121. path,
  5122. thisParameter
  5123. };
  5124. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, event, thisParameter)) {
  5125. for (const entity of this.entitiesToBeDeoptimized) {
  5126. this.applyThisDeoptimizationEvent(entity, thisDeoptimization);
  5127. }
  5128. this.thisDeoptimizationList.push(thisDeoptimization);
  5129. }
  5130. }
  5131. hasEffectsWhenAccessedAtPath(path, context) {
  5132. return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
  5133. super.hasEffectsWhenAccessedAtPath(path, context));
  5134. }
  5135. hasEffectsWhenAssignedAtPath(path, context) {
  5136. return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
  5137. super.hasEffectsWhenAssignedAtPath(path, context));
  5138. }
  5139. applyThisDeoptimizationEvent(entity, { event, path, thisParameter }) {
  5140. entity.deoptimizeThisOnEventAtPath(event, path, thisParameter === this ? entity : thisParameter, SHARED_RECURSION_TRACKER);
  5141. }
  5142. getInit(context) {
  5143. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  5144. }
  5145. }
  5146. class SpreadElement extends NodeBase {
  5147. constructor() {
  5148. super(...arguments);
  5149. this.deoptimized = false;
  5150. }
  5151. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  5152. if (path.length > 0) {
  5153. this.argument.deoptimizeThisOnEventAtPath(event, [UnknownKey, ...path], thisParameter, recursionTracker);
  5154. }
  5155. }
  5156. hasEffects(context) {
  5157. if (!this.deoptimized)
  5158. this.applyDeoptimizations();
  5159. const { propertyReadSideEffects } = this.context.options
  5160. .treeshake;
  5161. return (this.argument.hasEffects(context) ||
  5162. (propertyReadSideEffects &&
  5163. (propertyReadSideEffects === 'always' ||
  5164. this.argument.hasEffectsWhenAccessedAtPath(UNKNOWN_PATH, context))));
  5165. }
  5166. applyDeoptimizations() {
  5167. this.deoptimized = true;
  5168. // Only properties of properties of the argument could become subject to reassignment
  5169. // This will also reassign the return values of iterators
  5170. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  5171. this.context.requestTreeshakingPass();
  5172. }
  5173. }
  5174. class ParameterScope extends ChildScope {
  5175. constructor(parent, context) {
  5176. super(parent);
  5177. this.parameters = [];
  5178. this.hasRest = false;
  5179. this.context = context;
  5180. this.hoistedBodyVarScope = new ChildScope(this);
  5181. }
  5182. /**
  5183. * Adds a parameter to this scope. Parameters must be added in the correct
  5184. * order, e.g. from left to right.
  5185. */
  5186. addParameterDeclaration(identifier) {
  5187. const name = identifier.name;
  5188. let variable = this.hoistedBodyVarScope.variables.get(name);
  5189. if (variable) {
  5190. variable.addDeclaration(identifier, null);
  5191. }
  5192. else {
  5193. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  5194. }
  5195. this.variables.set(name, variable);
  5196. return variable;
  5197. }
  5198. addParameterVariables(parameters, hasRest) {
  5199. this.parameters = parameters;
  5200. for (const parameterList of parameters) {
  5201. for (const parameter of parameterList) {
  5202. parameter.alwaysRendered = true;
  5203. }
  5204. }
  5205. this.hasRest = hasRest;
  5206. }
  5207. includeCallArguments(context, args) {
  5208. let calledFromTryStatement = false;
  5209. let argIncluded = false;
  5210. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  5211. for (const checkedArg of args) {
  5212. if (checkedArg instanceof SpreadElement) {
  5213. for (const arg of args) {
  5214. arg.include(context, false);
  5215. }
  5216. break;
  5217. }
  5218. }
  5219. for (let index = args.length - 1; index >= 0; index--) {
  5220. const paramVars = this.parameters[index] || restParam;
  5221. const arg = args[index];
  5222. if (paramVars) {
  5223. calledFromTryStatement = false;
  5224. if (paramVars.length === 0) {
  5225. // handle empty destructuring
  5226. argIncluded = true;
  5227. }
  5228. else {
  5229. for (const variable of paramVars) {
  5230. if (variable.included) {
  5231. argIncluded = true;
  5232. }
  5233. if (variable.calledFromTryStatement) {
  5234. calledFromTryStatement = true;
  5235. }
  5236. }
  5237. }
  5238. }
  5239. if (!argIncluded && arg.shouldBeIncluded(context)) {
  5240. argIncluded = true;
  5241. }
  5242. if (argIncluded) {
  5243. arg.include(context, calledFromTryStatement);
  5244. }
  5245. }
  5246. }
  5247. }
  5248. class ReturnValueScope extends ParameterScope {
  5249. constructor() {
  5250. super(...arguments);
  5251. this.returnExpression = null;
  5252. this.returnExpressions = [];
  5253. }
  5254. addReturnExpression(expression) {
  5255. this.returnExpressions.push(expression);
  5256. }
  5257. getReturnExpression() {
  5258. if (this.returnExpression === null)
  5259. this.updateReturnExpression();
  5260. return this.returnExpression;
  5261. }
  5262. updateReturnExpression() {
  5263. if (this.returnExpressions.length === 1) {
  5264. this.returnExpression = this.returnExpressions[0];
  5265. }
  5266. else {
  5267. this.returnExpression = UNKNOWN_EXPRESSION;
  5268. for (const expression of this.returnExpressions) {
  5269. expression.deoptimizePath(UNKNOWN_PATH);
  5270. }
  5271. }
  5272. }
  5273. }
  5274. class FunctionScope extends ReturnValueScope {
  5275. constructor(parent, context) {
  5276. super(parent, context);
  5277. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  5278. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  5279. }
  5280. findLexicalBoundary() {
  5281. return this;
  5282. }
  5283. includeCallArguments(context, args) {
  5284. super.includeCallArguments(context, args);
  5285. if (this.argumentsVariable.included) {
  5286. for (const arg of args) {
  5287. if (!arg.included) {
  5288. arg.include(context, false);
  5289. }
  5290. }
  5291. }
  5292. }
  5293. }
  5294. class RestElement extends NodeBase {
  5295. constructor() {
  5296. super(...arguments);
  5297. this.deoptimized = false;
  5298. this.declarationInit = null;
  5299. }
  5300. addExportedVariables(variables, exportNamesByVariable) {
  5301. this.argument.addExportedVariables(variables, exportNamesByVariable);
  5302. }
  5303. declare(kind, init) {
  5304. this.declarationInit = init;
  5305. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  5306. }
  5307. deoptimizePath(path) {
  5308. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  5309. }
  5310. hasEffectsWhenAssignedAtPath(path, context) {
  5311. return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  5312. }
  5313. markDeclarationReached() {
  5314. this.argument.markDeclarationReached();
  5315. }
  5316. applyDeoptimizations() {
  5317. this.deoptimized = true;
  5318. if (this.declarationInit !== null) {
  5319. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  5320. this.context.requestTreeshakingPass();
  5321. }
  5322. }
  5323. }
  5324. class FunctionNode extends NodeBase {
  5325. constructor() {
  5326. super(...arguments);
  5327. this.deoptimizedReturn = false;
  5328. this.isPrototypeDeoptimized = false;
  5329. }
  5330. createScope(parentScope) {
  5331. this.scope = new FunctionScope(parentScope, this.context);
  5332. }
  5333. deoptimizePath(path) {
  5334. if (path.length === 1) {
  5335. if (path[0] === 'prototype') {
  5336. this.isPrototypeDeoptimized = true;
  5337. }
  5338. else if (path[0] === UnknownKey) {
  5339. this.isPrototypeDeoptimized = true;
  5340. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  5341. // which means the return expression needs to be reassigned as well
  5342. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5343. }
  5344. }
  5345. }
  5346. // TODO for completeness, we should also track other events here
  5347. deoptimizeThisOnEventAtPath(event, path, thisParameter) {
  5348. if (event === EVENT_CALLED) {
  5349. if (path.length > 0) {
  5350. thisParameter.deoptimizePath(UNKNOWN_PATH);
  5351. }
  5352. else {
  5353. this.scope.thisVariable.addEntityToBeDeoptimized(thisParameter);
  5354. }
  5355. }
  5356. }
  5357. getReturnExpressionWhenCalledAtPath(path) {
  5358. if (path.length !== 0) {
  5359. return UNKNOWN_EXPRESSION;
  5360. }
  5361. if (this.async) {
  5362. if (!this.deoptimizedReturn) {
  5363. this.deoptimizedReturn = true;
  5364. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5365. this.context.requestTreeshakingPass();
  5366. }
  5367. return UNKNOWN_EXPRESSION;
  5368. }
  5369. return this.scope.getReturnExpression();
  5370. }
  5371. hasEffects() {
  5372. return this.id !== null && this.id.hasEffects();
  5373. }
  5374. hasEffectsWhenAccessedAtPath(path) {
  5375. if (path.length <= 1)
  5376. return false;
  5377. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  5378. }
  5379. hasEffectsWhenAssignedAtPath(path) {
  5380. if (path.length <= 1) {
  5381. return false;
  5382. }
  5383. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  5384. }
  5385. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5386. if (path.length > 0)
  5387. return true;
  5388. if (this.async) {
  5389. const { propertyReadSideEffects } = this.context.options
  5390. .treeshake;
  5391. const returnExpression = this.scope.getReturnExpression();
  5392. if (returnExpression.hasEffectsWhenCalledAtPath(['then'], { args: NO_ARGS, thisParam: null, withNew: false }, context) ||
  5393. (propertyReadSideEffects &&
  5394. (propertyReadSideEffects === 'always' ||
  5395. returnExpression.hasEffectsWhenAccessedAtPath(['then'], context)))) {
  5396. return true;
  5397. }
  5398. }
  5399. for (const param of this.params) {
  5400. if (param.hasEffects(context))
  5401. return true;
  5402. }
  5403. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  5404. context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew
  5405. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  5406. : UNKNOWN_EXPRESSION);
  5407. const { brokenFlow, ignore } = context;
  5408. context.ignore = {
  5409. breaks: false,
  5410. continues: false,
  5411. labels: new Set(),
  5412. returnYield: true
  5413. };
  5414. if (this.body.hasEffects(context))
  5415. return true;
  5416. context.brokenFlow = brokenFlow;
  5417. if (thisInit) {
  5418. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  5419. }
  5420. else {
  5421. context.replacedVariableInits.delete(this.scope.thisVariable);
  5422. }
  5423. context.ignore = ignore;
  5424. return false;
  5425. }
  5426. include(context, includeChildrenRecursively) {
  5427. this.included = true;
  5428. if (this.id)
  5429. this.id.include();
  5430. const hasArguments = this.scope.argumentsVariable.included;
  5431. for (const param of this.params) {
  5432. if (!(param instanceof Identifier) || hasArguments) {
  5433. param.include(context, includeChildrenRecursively);
  5434. }
  5435. }
  5436. const { brokenFlow } = context;
  5437. context.brokenFlow = BROKEN_FLOW_NONE;
  5438. this.body.include(context, includeChildrenRecursively);
  5439. context.brokenFlow = brokenFlow;
  5440. }
  5441. includeCallArguments(context, args) {
  5442. this.scope.includeCallArguments(context, args);
  5443. }
  5444. initialise() {
  5445. if (this.id !== null) {
  5446. this.id.declare('function', this);
  5447. }
  5448. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  5449. this.body.addImplicitReturnExpressionToScope();
  5450. }
  5451. parseNode(esTreeNode) {
  5452. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  5453. super.parseNode(esTreeNode);
  5454. }
  5455. }
  5456. FunctionNode.prototype.preventChildBlockScope = true;
  5457. class FunctionDeclaration extends FunctionNode {
  5458. initialise() {
  5459. super.initialise();
  5460. if (this.id !== null) {
  5461. this.id.variable.isId = true;
  5462. }
  5463. }
  5464. parseNode(esTreeNode) {
  5465. if (esTreeNode.id !== null) {
  5466. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  5467. }
  5468. super.parseNode(esTreeNode);
  5469. }
  5470. }
  5471. // The header ends at the first non-white-space after "default"
  5472. function getDeclarationStart(code, start) {
  5473. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  5474. }
  5475. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  5476. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  5477. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  5478. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  5479. if (generatorStarPos === -1) {
  5480. return declarationEnd;
  5481. }
  5482. return declarationEnd + generatorStarPos + 1;
  5483. }
  5484. class ExportDefaultDeclaration extends NodeBase {
  5485. include(context, includeChildrenRecursively) {
  5486. super.include(context, includeChildrenRecursively);
  5487. if (includeChildrenRecursively) {
  5488. this.context.includeVariableInModule(this.variable);
  5489. }
  5490. }
  5491. initialise() {
  5492. const declaration = this.declaration;
  5493. this.declarationName =
  5494. (declaration.id && declaration.id.name) || this.declaration.name;
  5495. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  5496. this.context.addExport(this);
  5497. }
  5498. render(code, options, nodeRenderOptions) {
  5499. const { start, end } = nodeRenderOptions;
  5500. const declarationStart = getDeclarationStart(code.original, this.start);
  5501. if (this.declaration instanceof FunctionDeclaration) {
  5502. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  5503. }
  5504. else if (this.declaration instanceof ClassDeclaration) {
  5505. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  5506. }
  5507. else if (this.variable.getOriginalVariable() !== this.variable) {
  5508. // Remove altogether to prevent re-declaring the same variable
  5509. treeshakeNode(this, code, start, end);
  5510. return;
  5511. }
  5512. else if (this.variable.included) {
  5513. this.renderVariableDeclaration(code, declarationStart, options);
  5514. }
  5515. else {
  5516. code.remove(this.start, declarationStart);
  5517. this.declaration.render(code, options, {
  5518. renderedSurroundingElement: ExpressionStatement$1
  5519. });
  5520. if (code.original[this.end - 1] !== ';') {
  5521. code.appendLeft(this.end, ';');
  5522. }
  5523. return;
  5524. }
  5525. this.declaration.render(code, options);
  5526. }
  5527. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  5528. const name = this.variable.getName();
  5529. // Remove `export default`
  5530. code.remove(this.start, declarationStart);
  5531. if (needsId) {
  5532. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  5533. }
  5534. if (options.format === 'system' &&
  5535. this.declaration instanceof ClassDeclaration &&
  5536. options.exportNamesByVariable.has(this.variable)) {
  5537. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  5538. }
  5539. }
  5540. renderVariableDeclaration(code, declarationStart, options) {
  5541. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  5542. const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
  5543. if (systemExportNames) {
  5544. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
  5545. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  5546. }
  5547. else {
  5548. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
  5549. if (!hasTrailingSemicolon) {
  5550. code.appendLeft(this.end, ';');
  5551. }
  5552. }
  5553. }
  5554. }
  5555. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  5556. class Literal extends NodeBase {
  5557. deoptimizeThisOnEventAtPath() { }
  5558. getLiteralValueAtPath(path) {
  5559. if (path.length > 0 ||
  5560. // unknown literals can also be null but do not start with an "n"
  5561. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  5562. typeof this.value === 'bigint' ||
  5563. // to support shims for regular expressions
  5564. this.context.code.charCodeAt(this.start) === 47) {
  5565. return UnknownValue;
  5566. }
  5567. return this.value;
  5568. }
  5569. getReturnExpressionWhenCalledAtPath(path) {
  5570. if (path.length !== 1)
  5571. return UNKNOWN_EXPRESSION;
  5572. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  5573. }
  5574. hasEffectsWhenAccessedAtPath(path) {
  5575. if (this.value === null) {
  5576. return path.length > 0;
  5577. }
  5578. return path.length > 1;
  5579. }
  5580. hasEffectsWhenAssignedAtPath(path) {
  5581. return path.length > 0;
  5582. }
  5583. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5584. if (path.length === 1) {
  5585. return hasMemberEffectWhenCalled(this.members, path[0], callOptions, context);
  5586. }
  5587. return true;
  5588. }
  5589. initialise() {
  5590. this.members = getLiteralMembersForValue(this.value);
  5591. }
  5592. parseNode(esTreeNode) {
  5593. this.value = esTreeNode.value;
  5594. this.regex = esTreeNode.regex;
  5595. super.parseNode(esTreeNode);
  5596. }
  5597. render(code) {
  5598. if (typeof this.value === 'string') {
  5599. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  5600. }
  5601. }
  5602. }
  5603. class Program extends NodeBase {
  5604. constructor() {
  5605. super(...arguments);
  5606. this.hasCachedEffect = false;
  5607. }
  5608. hasEffects(context) {
  5609. // We are caching here to later more efficiently identify side-effect-free modules
  5610. if (this.hasCachedEffect)
  5611. return true;
  5612. for (const node of this.body) {
  5613. if (node.hasEffects(context)) {
  5614. return (this.hasCachedEffect = true);
  5615. }
  5616. }
  5617. return false;
  5618. }
  5619. include(context, includeChildrenRecursively) {
  5620. this.included = true;
  5621. for (const node of this.body) {
  5622. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  5623. node.include(context, includeChildrenRecursively);
  5624. }
  5625. }
  5626. }
  5627. render(code, options) {
  5628. if (this.body.length) {
  5629. renderStatementList(this.body, code, this.start, this.end, options);
  5630. }
  5631. else {
  5632. super.render(code, options);
  5633. }
  5634. }
  5635. }
  5636. class TemplateLiteral extends NodeBase {
  5637. getLiteralValueAtPath(path) {
  5638. if (path.length > 0 || this.quasis.length !== 1) {
  5639. return UnknownValue;
  5640. }
  5641. return this.quasis[0].value.cooked;
  5642. }
  5643. render(code, options) {
  5644. code.indentExclusionRanges.push([this.start, this.end]);
  5645. super.render(code, options);
  5646. }
  5647. }
  5648. function isReassignedExportsMember(variable, exportNamesByVariable) {
  5649. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  5650. }
  5651. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  5652. for (const declarator of declarations) {
  5653. if (!declarator.id.included)
  5654. return false;
  5655. if (declarator.id.type === Identifier$1) {
  5656. if (exportNamesByVariable.has(declarator.id.variable))
  5657. return false;
  5658. }
  5659. else {
  5660. const exportedVariables = [];
  5661. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  5662. if (exportedVariables.length > 0)
  5663. return false;
  5664. }
  5665. }
  5666. return true;
  5667. }
  5668. class VariableDeclaration extends NodeBase {
  5669. deoptimizePath() {
  5670. for (const declarator of this.declarations) {
  5671. declarator.deoptimizePath(EMPTY_PATH);
  5672. }
  5673. }
  5674. hasEffectsWhenAssignedAtPath() {
  5675. return false;
  5676. }
  5677. include(context, includeChildrenRecursively) {
  5678. this.included = true;
  5679. for (const declarator of this.declarations) {
  5680. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  5681. declarator.include(context, includeChildrenRecursively);
  5682. }
  5683. }
  5684. includeAsSingleStatement(context, includeChildrenRecursively) {
  5685. this.included = true;
  5686. for (const declarator of this.declarations) {
  5687. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  5688. declarator.include(context, includeChildrenRecursively);
  5689. declarator.id.include(context, includeChildrenRecursively);
  5690. }
  5691. }
  5692. }
  5693. initialise() {
  5694. for (const declarator of this.declarations) {
  5695. declarator.declareDeclarator(this.kind);
  5696. }
  5697. }
  5698. render(code, options, nodeRenderOptions = BLANK) {
  5699. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  5700. for (const declarator of this.declarations) {
  5701. declarator.render(code, options);
  5702. }
  5703. if (!nodeRenderOptions.isNoStatement &&
  5704. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  5705. code.appendLeft(this.end, ';');
  5706. }
  5707. }
  5708. else {
  5709. this.renderReplacedDeclarations(code, options, nodeRenderOptions);
  5710. }
  5711. }
  5712. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement) {
  5713. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  5714. code.remove(this.end - 1, this.end);
  5715. }
  5716. if (!isNoStatement) {
  5717. separatorString += ';';
  5718. }
  5719. if (lastSeparatorPos !== null) {
  5720. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  5721. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  5722. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  5723. actualContentEnd--;
  5724. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  5725. actualContentEnd--;
  5726. }
  5727. }
  5728. if (actualContentEnd === lastSeparatorPos + 1) {
  5729. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  5730. }
  5731. else {
  5732. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  5733. code.remove(actualContentEnd, renderedContentEnd);
  5734. }
  5735. }
  5736. else {
  5737. code.appendLeft(renderedContentEnd, separatorString);
  5738. }
  5739. if (systemPatternExports.length > 0) {
  5740. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  5741. }
  5742. }
  5743. renderReplacedDeclarations(code, options, { isNoStatement }) {
  5744. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  5745. let actualContentEnd, renderedContentEnd;
  5746. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  5747. let lastSeparatorPos = renderedContentEnd - 1;
  5748. code.remove(this.start, lastSeparatorPos);
  5749. let isInDeclaration = false;
  5750. let hasRenderedContent = false;
  5751. let separatorString = '', leadingString, nextSeparatorString;
  5752. const aggregatedSystemExports = [];
  5753. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  5754. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  5755. if (!node.included) {
  5756. code.remove(start, end);
  5757. continue;
  5758. }
  5759. node.render(code, options);
  5760. leadingString = '';
  5761. nextSeparatorString = '';
  5762. if (!node.id.included ||
  5763. (node.id instanceof Identifier &&
  5764. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  5765. if (hasRenderedContent) {
  5766. separatorString += ';';
  5767. }
  5768. isInDeclaration = false;
  5769. }
  5770. else {
  5771. if (singleSystemExport && singleSystemExport === node.id.variable) {
  5772. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  5773. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  5774. }
  5775. if (isInDeclaration) {
  5776. separatorString += ',';
  5777. }
  5778. else {
  5779. if (hasRenderedContent) {
  5780. separatorString += ';';
  5781. }
  5782. leadingString += `${this.kind} `;
  5783. isInDeclaration = true;
  5784. }
  5785. }
  5786. if (renderedContentEnd === lastSeparatorPos + 1) {
  5787. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  5788. }
  5789. else {
  5790. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  5791. code.appendLeft(renderedContentEnd, leadingString);
  5792. }
  5793. actualContentEnd = contentEnd;
  5794. renderedContentEnd = end;
  5795. hasRenderedContent = true;
  5796. lastSeparatorPos = separator;
  5797. separatorString = nextSeparatorString;
  5798. }
  5799. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options, isNoStatement);
  5800. }
  5801. }
  5802. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  5803. var _a;
  5804. let singleSystemExport = null;
  5805. if (options.format === 'system') {
  5806. for (const { node } of separatedNodes) {
  5807. if (node.id instanceof Identifier &&
  5808. node.init &&
  5809. aggregatedSystemExports.length === 0 &&
  5810. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  5811. singleSystemExport = node.id.variable;
  5812. aggregatedSystemExports.push(singleSystemExport);
  5813. }
  5814. else {
  5815. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  5816. }
  5817. }
  5818. if (aggregatedSystemExports.length > 1) {
  5819. singleSystemExport = null;
  5820. }
  5821. else if (singleSystemExport) {
  5822. aggregatedSystemExports.length = 0;
  5823. }
  5824. }
  5825. return singleSystemExport;
  5826. }
  5827. const NEW_ARRAY_PROPERTIES = [
  5828. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5829. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5830. ];
  5831. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5832. new Method({
  5833. callsArgs: [0],
  5834. mutatesSelfAsArray: 'deopt-only',
  5835. returns: null,
  5836. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5837. })
  5838. ];
  5839. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5840. new Method({
  5841. callsArgs: [0],
  5842. mutatesSelfAsArray: 'deopt-only',
  5843. returns: null,
  5844. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5845. })
  5846. ];
  5847. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5848. new Method({
  5849. callsArgs: null,
  5850. mutatesSelfAsArray: true,
  5851. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5852. returnsPrimitive: null
  5853. })
  5854. ];
  5855. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5856. new Method({
  5857. callsArgs: null,
  5858. mutatesSelfAsArray: 'deopt-only',
  5859. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5860. returnsPrimitive: null
  5861. })
  5862. ];
  5863. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5864. new Method({
  5865. callsArgs: [0],
  5866. mutatesSelfAsArray: 'deopt-only',
  5867. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5868. returnsPrimitive: null
  5869. })
  5870. ];
  5871. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5872. new Method({
  5873. callsArgs: null,
  5874. mutatesSelfAsArray: true,
  5875. returns: null,
  5876. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5877. })
  5878. ];
  5879. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5880. new Method({
  5881. callsArgs: null,
  5882. mutatesSelfAsArray: true,
  5883. returns: null,
  5884. returnsPrimitive: UNKNOWN_EXPRESSION
  5885. })
  5886. ];
  5887. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5888. new Method({
  5889. callsArgs: null,
  5890. mutatesSelfAsArray: 'deopt-only',
  5891. returns: null,
  5892. returnsPrimitive: UNKNOWN_EXPRESSION
  5893. })
  5894. ];
  5895. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5896. new Method({
  5897. callsArgs: [0],
  5898. mutatesSelfAsArray: 'deopt-only',
  5899. returns: null,
  5900. returnsPrimitive: UNKNOWN_EXPRESSION
  5901. })
  5902. ];
  5903. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5904. new Method({
  5905. callsArgs: null,
  5906. mutatesSelfAsArray: true,
  5907. returns: 'self',
  5908. returnsPrimitive: null
  5909. })
  5910. ];
  5911. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5912. new Method({
  5913. callsArgs: [0],
  5914. mutatesSelfAsArray: true,
  5915. returns: 'self',
  5916. returnsPrimitive: null
  5917. })
  5918. ];
  5919. const ARRAY_PROTOTYPE = new ObjectEntity({
  5920. __proto__: null,
  5921. // We assume that accessors have effects as we do not track the accessed value afterwards
  5922. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5923. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5924. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5925. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5926. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5927. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5928. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5929. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5930. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5931. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5932. includes: METHOD_RETURNS_BOOLEAN,
  5933. indexOf: METHOD_RETURNS_NUMBER,
  5934. join: METHOD_RETURNS_STRING,
  5935. keys: METHOD_RETURNS_UNKNOWN,
  5936. lastIndexOf: METHOD_RETURNS_NUMBER,
  5937. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5938. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5939. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5940. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5941. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5942. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5943. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5944. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5945. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5946. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5947. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5948. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5949. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5950. }, OBJECT_PROTOTYPE, true);
  5951. class ArrayExpression extends NodeBase {
  5952. constructor() {
  5953. super(...arguments);
  5954. this.objectEntity = null;
  5955. }
  5956. deoptimizePath(path) {
  5957. this.getObjectEntity().deoptimizePath(path);
  5958. }
  5959. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  5960. this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  5961. }
  5962. getLiteralValueAtPath(path, recursionTracker, origin) {
  5963. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5964. }
  5965. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  5966. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  5967. }
  5968. hasEffectsWhenAccessedAtPath(path, context) {
  5969. return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
  5970. }
  5971. hasEffectsWhenAssignedAtPath(path, context) {
  5972. return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
  5973. }
  5974. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5975. return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
  5976. }
  5977. getObjectEntity() {
  5978. if (this.objectEntity !== null) {
  5979. return this.objectEntity;
  5980. }
  5981. const properties = [
  5982. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5983. ];
  5984. let hasSpread = false;
  5985. for (let index = 0; index < this.elements.length; index++) {
  5986. const element = this.elements[index];
  5987. if (element instanceof SpreadElement || hasSpread) {
  5988. if (element) {
  5989. hasSpread = true;
  5990. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5991. }
  5992. }
  5993. else if (!element) {
  5994. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5995. }
  5996. else {
  5997. properties.push({ key: String(index), kind: 'init', property: element });
  5998. }
  5999. }
  6000. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  6001. }
  6002. }
  6003. class ArrayPattern extends NodeBase {
  6004. addExportedVariables(variables, exportNamesByVariable) {
  6005. for (const element of this.elements) {
  6006. if (element !== null) {
  6007. element.addExportedVariables(variables, exportNamesByVariable);
  6008. }
  6009. }
  6010. }
  6011. declare(kind) {
  6012. const variables = [];
  6013. for (const element of this.elements) {
  6014. if (element !== null) {
  6015. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  6016. }
  6017. }
  6018. return variables;
  6019. }
  6020. deoptimizePath(path) {
  6021. if (path.length === 0) {
  6022. for (const element of this.elements) {
  6023. if (element !== null) {
  6024. element.deoptimizePath(path);
  6025. }
  6026. }
  6027. }
  6028. }
  6029. hasEffectsWhenAssignedAtPath(path, context) {
  6030. if (path.length > 0)
  6031. return true;
  6032. for (const element of this.elements) {
  6033. if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  6034. return true;
  6035. }
  6036. return false;
  6037. }
  6038. markDeclarationReached() {
  6039. for (const element of this.elements) {
  6040. if (element !== null) {
  6041. element.markDeclarationReached();
  6042. }
  6043. }
  6044. }
  6045. }
  6046. class BlockScope extends ChildScope {
  6047. addDeclaration(identifier, context, init, isHoisted) {
  6048. if (isHoisted) {
  6049. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  6050. // Necessary to make sure the init is deoptimized for conditional declarations.
  6051. // We cannot call deoptimizePath here.
  6052. variable.markInitializersForDeoptimization();
  6053. return variable;
  6054. }
  6055. else {
  6056. return super.addDeclaration(identifier, context, init, false);
  6057. }
  6058. }
  6059. }
  6060. class ExpressionStatement extends NodeBase {
  6061. initialise() {
  6062. if (this.directive &&
  6063. this.directive !== 'use strict' &&
  6064. this.parent.type === Program$1) {
  6065. this.context.warn(
  6066. // This is necessary, because either way (deleting or not) can lead to errors.
  6067. {
  6068. code: 'MODULE_LEVEL_DIRECTIVE',
  6069. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  6070. }, this.start);
  6071. }
  6072. }
  6073. render(code, options) {
  6074. super.render(code, options);
  6075. if (this.included)
  6076. this.insertSemicolon(code);
  6077. }
  6078. shouldBeIncluded(context) {
  6079. if (this.directive && this.directive !== 'use strict')
  6080. return this.parent.type !== Program$1;
  6081. return super.shouldBeIncluded(context);
  6082. }
  6083. }
  6084. class BlockStatement extends NodeBase {
  6085. constructor() {
  6086. super(...arguments);
  6087. this.directlyIncluded = false;
  6088. }
  6089. addImplicitReturnExpressionToScope() {
  6090. const lastStatement = this.body[this.body.length - 1];
  6091. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  6092. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6093. }
  6094. }
  6095. createScope(parentScope) {
  6096. this.scope = this.parent.preventChildBlockScope
  6097. ? parentScope
  6098. : new BlockScope(parentScope);
  6099. }
  6100. hasEffects(context) {
  6101. if (this.deoptimizeBody)
  6102. return true;
  6103. for (const node of this.body) {
  6104. if (node.hasEffects(context))
  6105. return true;
  6106. if (context.brokenFlow)
  6107. break;
  6108. }
  6109. return false;
  6110. }
  6111. include(context, includeChildrenRecursively) {
  6112. if (!this.deoptimizeBody || !this.directlyIncluded) {
  6113. this.included = true;
  6114. this.directlyIncluded = true;
  6115. if (this.deoptimizeBody)
  6116. includeChildrenRecursively = true;
  6117. for (const node of this.body) {
  6118. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6119. node.include(context, includeChildrenRecursively);
  6120. }
  6121. }
  6122. }
  6123. initialise() {
  6124. const firstBodyStatement = this.body[0];
  6125. this.deoptimizeBody =
  6126. firstBodyStatement instanceof ExpressionStatement &&
  6127. firstBodyStatement.directive === 'use asm';
  6128. }
  6129. render(code, options) {
  6130. if (this.body.length) {
  6131. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  6132. }
  6133. else {
  6134. super.render(code, options);
  6135. }
  6136. }
  6137. }
  6138. class ArrowFunctionExpression extends NodeBase {
  6139. constructor() {
  6140. super(...arguments);
  6141. this.deoptimizedReturn = false;
  6142. }
  6143. createScope(parentScope) {
  6144. this.scope = new ReturnValueScope(parentScope, this.context);
  6145. }
  6146. deoptimizePath(path) {
  6147. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  6148. // which means the return expression needs to be reassigned
  6149. if (path.length === 1 && path[0] === UnknownKey) {
  6150. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6151. }
  6152. }
  6153. // Arrow functions do not mutate their context
  6154. deoptimizeThisOnEventAtPath() { }
  6155. getReturnExpressionWhenCalledAtPath(path) {
  6156. if (path.length !== 0) {
  6157. return UNKNOWN_EXPRESSION;
  6158. }
  6159. if (this.async) {
  6160. if (!this.deoptimizedReturn) {
  6161. this.deoptimizedReturn = true;
  6162. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6163. this.context.requestTreeshakingPass();
  6164. }
  6165. return UNKNOWN_EXPRESSION;
  6166. }
  6167. return this.scope.getReturnExpression();
  6168. }
  6169. hasEffects() {
  6170. return false;
  6171. }
  6172. hasEffectsWhenAccessedAtPath(path) {
  6173. return path.length > 1;
  6174. }
  6175. hasEffectsWhenAssignedAtPath(path) {
  6176. return path.length > 1;
  6177. }
  6178. hasEffectsWhenCalledAtPath(path, _callOptions, context) {
  6179. if (path.length > 0)
  6180. return true;
  6181. if (this.async) {
  6182. const { propertyReadSideEffects } = this.context.options
  6183. .treeshake;
  6184. const returnExpression = this.scope.getReturnExpression();
  6185. if (returnExpression.hasEffectsWhenCalledAtPath(['then'], { args: NO_ARGS, thisParam: null, withNew: false }, context) ||
  6186. (propertyReadSideEffects &&
  6187. (propertyReadSideEffects === 'always' ||
  6188. returnExpression.hasEffectsWhenAccessedAtPath(['then'], context)))) {
  6189. return true;
  6190. }
  6191. }
  6192. for (const param of this.params) {
  6193. if (param.hasEffects(context))
  6194. return true;
  6195. }
  6196. const { ignore, brokenFlow } = context;
  6197. context.ignore = {
  6198. breaks: false,
  6199. continues: false,
  6200. labels: new Set(),
  6201. returnYield: true
  6202. };
  6203. if (this.body.hasEffects(context))
  6204. return true;
  6205. context.ignore = ignore;
  6206. context.brokenFlow = brokenFlow;
  6207. return false;
  6208. }
  6209. include(context, includeChildrenRecursively) {
  6210. this.included = true;
  6211. for (const param of this.params) {
  6212. if (!(param instanceof Identifier)) {
  6213. param.include(context, includeChildrenRecursively);
  6214. }
  6215. }
  6216. const { brokenFlow } = context;
  6217. context.brokenFlow = BROKEN_FLOW_NONE;
  6218. this.body.include(context, includeChildrenRecursively);
  6219. context.brokenFlow = brokenFlow;
  6220. }
  6221. includeCallArguments(context, args) {
  6222. this.scope.includeCallArguments(context, args);
  6223. }
  6224. initialise() {
  6225. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  6226. if (this.body instanceof BlockStatement) {
  6227. this.body.addImplicitReturnExpressionToScope();
  6228. }
  6229. else {
  6230. this.scope.addReturnExpression(this.body);
  6231. }
  6232. }
  6233. parseNode(esTreeNode) {
  6234. if (esTreeNode.body.type === BlockStatement$1) {
  6235. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  6236. }
  6237. super.parseNode(esTreeNode);
  6238. }
  6239. }
  6240. ArrowFunctionExpression.prototype.preventChildBlockScope = true;
  6241. class ObjectPattern extends NodeBase {
  6242. addExportedVariables(variables, exportNamesByVariable) {
  6243. for (const property of this.properties) {
  6244. if (property.type === Property$1) {
  6245. property.value.addExportedVariables(variables, exportNamesByVariable);
  6246. }
  6247. else {
  6248. property.argument.addExportedVariables(variables, exportNamesByVariable);
  6249. }
  6250. }
  6251. }
  6252. declare(kind, init) {
  6253. const variables = [];
  6254. for (const property of this.properties) {
  6255. variables.push(...property.declare(kind, init));
  6256. }
  6257. return variables;
  6258. }
  6259. deoptimizePath(path) {
  6260. if (path.length === 0) {
  6261. for (const property of this.properties) {
  6262. property.deoptimizePath(path);
  6263. }
  6264. }
  6265. }
  6266. hasEffectsWhenAssignedAtPath(path, context) {
  6267. if (path.length > 0)
  6268. return true;
  6269. for (const property of this.properties) {
  6270. if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  6271. return true;
  6272. }
  6273. return false;
  6274. }
  6275. markDeclarationReached() {
  6276. for (const property of this.properties) {
  6277. property.markDeclarationReached();
  6278. }
  6279. }
  6280. }
  6281. class AssignmentExpression extends NodeBase {
  6282. constructor() {
  6283. super(...arguments);
  6284. this.deoptimized = false;
  6285. }
  6286. hasEffects(context) {
  6287. if (!this.deoptimized)
  6288. this.applyDeoptimizations();
  6289. return (this.right.hasEffects(context) ||
  6290. this.left.hasEffects(context) ||
  6291. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  6292. }
  6293. hasEffectsWhenAccessedAtPath(path, context) {
  6294. return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
  6295. }
  6296. include(context, includeChildrenRecursively) {
  6297. if (!this.deoptimized)
  6298. this.applyDeoptimizations();
  6299. this.included = true;
  6300. let hasEffectsContext;
  6301. if (includeChildrenRecursively ||
  6302. this.operator !== '=' ||
  6303. this.left.included ||
  6304. ((hasEffectsContext = createHasEffectsContext()),
  6305. this.left.hasEffects(hasEffectsContext) ||
  6306. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, hasEffectsContext))) {
  6307. this.left.include(context, includeChildrenRecursively);
  6308. }
  6309. this.right.include(context, includeChildrenRecursively);
  6310. }
  6311. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  6312. if (this.left.included) {
  6313. this.left.render(code, options);
  6314. this.right.render(code, options);
  6315. }
  6316. else {
  6317. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', this.left.end) + 1);
  6318. code.remove(this.start, inclusionStart);
  6319. if (preventASI) {
  6320. removeLineBreaks(code, inclusionStart, this.right.start);
  6321. }
  6322. this.right.render(code, options, {
  6323. renderedParentType: renderedParentType || this.parent.type,
  6324. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  6325. });
  6326. }
  6327. if (options.format === 'system') {
  6328. if (this.left instanceof Identifier) {
  6329. const variable = this.left.variable;
  6330. const exportNames = options.exportNamesByVariable.get(variable);
  6331. if (exportNames) {
  6332. if (exportNames.length === 1) {
  6333. renderSystemExportExpression(variable, this.start, this.end, code, options);
  6334. }
  6335. else {
  6336. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  6337. }
  6338. return;
  6339. }
  6340. }
  6341. else {
  6342. const systemPatternExports = [];
  6343. this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  6344. if (systemPatternExports.length > 0) {
  6345. renderSystemExportFunction(systemPatternExports, this.start, this.end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  6346. return;
  6347. }
  6348. }
  6349. }
  6350. if (this.left.included &&
  6351. this.left instanceof ObjectPattern &&
  6352. (renderedSurroundingElement === ExpressionStatement$1 ||
  6353. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  6354. code.appendRight(this.start, '(');
  6355. code.prependLeft(this.end, ')');
  6356. }
  6357. }
  6358. applyDeoptimizations() {
  6359. this.deoptimized = true;
  6360. this.left.deoptimizePath(EMPTY_PATH);
  6361. this.right.deoptimizePath(UNKNOWN_PATH);
  6362. this.context.requestTreeshakingPass();
  6363. }
  6364. }
  6365. class AssignmentPattern extends NodeBase {
  6366. constructor() {
  6367. super(...arguments);
  6368. this.deoptimized = false;
  6369. }
  6370. addExportedVariables(variables, exportNamesByVariable) {
  6371. this.left.addExportedVariables(variables, exportNamesByVariable);
  6372. }
  6373. declare(kind, init) {
  6374. return this.left.declare(kind, init);
  6375. }
  6376. deoptimizePath(path) {
  6377. path.length === 0 && this.left.deoptimizePath(path);
  6378. }
  6379. hasEffectsWhenAssignedAtPath(path, context) {
  6380. return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  6381. }
  6382. markDeclarationReached() {
  6383. this.left.markDeclarationReached();
  6384. }
  6385. render(code, options, { isShorthandProperty } = BLANK) {
  6386. this.left.render(code, options, { isShorthandProperty });
  6387. this.right.render(code, options);
  6388. }
  6389. applyDeoptimizations() {
  6390. this.deoptimized = true;
  6391. this.left.deoptimizePath(EMPTY_PATH);
  6392. this.right.deoptimizePath(UNKNOWN_PATH);
  6393. this.context.requestTreeshakingPass();
  6394. }
  6395. }
  6396. class AwaitExpression extends NodeBase {
  6397. constructor() {
  6398. super(...arguments);
  6399. this.deoptimized = false;
  6400. }
  6401. hasEffects() {
  6402. if (!this.deoptimized)
  6403. this.applyDeoptimizations();
  6404. return true;
  6405. }
  6406. include(context, includeChildrenRecursively) {
  6407. if (!this.deoptimized)
  6408. this.applyDeoptimizations();
  6409. if (!this.included) {
  6410. this.included = true;
  6411. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  6412. let parent = this.parent;
  6413. do {
  6414. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  6415. break checkTopLevelAwait;
  6416. } while ((parent = parent.parent));
  6417. this.context.usesTopLevelAwait = true;
  6418. }
  6419. }
  6420. this.argument.include(context, includeChildrenRecursively);
  6421. }
  6422. applyDeoptimizations() {
  6423. this.deoptimized = true;
  6424. this.argument.deoptimizePath(UNKNOWN_PATH);
  6425. this.context.requestTreeshakingPass();
  6426. }
  6427. }
  6428. const binaryOperators = {
  6429. '!=': (left, right) => left != right,
  6430. '!==': (left, right) => left !== right,
  6431. '%': (left, right) => left % right,
  6432. '&': (left, right) => left & right,
  6433. '*': (left, right) => left * right,
  6434. // At the moment, "**" will be transpiled to Math.pow
  6435. '**': (left, right) => left ** right,
  6436. '+': (left, right) => left + right,
  6437. '-': (left, right) => left - right,
  6438. '/': (left, right) => left / right,
  6439. '<': (left, right) => left < right,
  6440. '<<': (left, right) => left << right,
  6441. '<=': (left, right) => left <= right,
  6442. '==': (left, right) => left == right,
  6443. '===': (left, right) => left === right,
  6444. '>': (left, right) => left > right,
  6445. '>=': (left, right) => left >= right,
  6446. '>>': (left, right) => left >> right,
  6447. '>>>': (left, right) => left >>> right,
  6448. '^': (left, right) => left ^ right,
  6449. in: () => UnknownValue,
  6450. instanceof: () => UnknownValue,
  6451. '|': (left, right) => left | right
  6452. };
  6453. class BinaryExpression extends NodeBase {
  6454. deoptimizeCache() { }
  6455. getLiteralValueAtPath(path, recursionTracker, origin) {
  6456. if (path.length > 0)
  6457. return UnknownValue;
  6458. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6459. if (leftValue === UnknownValue)
  6460. return UnknownValue;
  6461. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6462. if (rightValue === UnknownValue)
  6463. return UnknownValue;
  6464. const operatorFn = binaryOperators[this.operator];
  6465. if (!operatorFn)
  6466. return UnknownValue;
  6467. return operatorFn(leftValue, rightValue);
  6468. }
  6469. hasEffects(context) {
  6470. // support some implicit type coercion runtime errors
  6471. if (this.operator === '+' &&
  6472. this.parent instanceof ExpressionStatement &&
  6473. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
  6474. return true;
  6475. return super.hasEffects(context);
  6476. }
  6477. hasEffectsWhenAccessedAtPath(path) {
  6478. return path.length > 1;
  6479. }
  6480. render(code, options, { renderedSurroundingElement } = BLANK) {
  6481. this.left.render(code, options, { renderedSurroundingElement });
  6482. this.right.render(code, options);
  6483. }
  6484. }
  6485. class BreakStatement extends NodeBase {
  6486. hasEffects(context) {
  6487. if (this.label) {
  6488. if (!context.ignore.labels.has(this.label.name))
  6489. return true;
  6490. context.includedLabels.add(this.label.name);
  6491. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6492. }
  6493. else {
  6494. if (!context.ignore.breaks)
  6495. return true;
  6496. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6497. }
  6498. return false;
  6499. }
  6500. include(context) {
  6501. this.included = true;
  6502. if (this.label) {
  6503. this.label.include();
  6504. context.includedLabels.add(this.label.name);
  6505. }
  6506. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6507. }
  6508. }
  6509. // To avoid infinite recursions
  6510. const MAX_PATH_DEPTH = 7;
  6511. function getResolvablePropertyKey(memberExpression) {
  6512. return memberExpression.computed
  6513. ? getResolvableComputedPropertyKey(memberExpression.property)
  6514. : memberExpression.property.name;
  6515. }
  6516. function getResolvableComputedPropertyKey(propertyKey) {
  6517. if (propertyKey instanceof Literal) {
  6518. return String(propertyKey.value);
  6519. }
  6520. return null;
  6521. }
  6522. function getPathIfNotComputed(memberExpression) {
  6523. const nextPathKey = memberExpression.propertyKey;
  6524. const object = memberExpression.object;
  6525. if (typeof nextPathKey === 'string') {
  6526. if (object instanceof Identifier) {
  6527. return [
  6528. { key: object.name, pos: object.start },
  6529. { key: nextPathKey, pos: memberExpression.property.start }
  6530. ];
  6531. }
  6532. if (object instanceof MemberExpression) {
  6533. const parentPath = getPathIfNotComputed(object);
  6534. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6535. }
  6536. }
  6537. return null;
  6538. }
  6539. function getStringFromPath(path) {
  6540. let pathString = path[0].key;
  6541. for (let index = 1; index < path.length; index++) {
  6542. pathString += '.' + path[index].key;
  6543. }
  6544. return pathString;
  6545. }
  6546. class MemberExpression extends NodeBase {
  6547. constructor() {
  6548. super(...arguments);
  6549. this.variable = null;
  6550. this.deoptimized = false;
  6551. this.bound = false;
  6552. this.expressionsToBeDeoptimized = [];
  6553. this.replacement = null;
  6554. }
  6555. bind() {
  6556. this.bound = true;
  6557. const path = getPathIfNotComputed(this);
  6558. const baseVariable = path && this.scope.findVariable(path[0].key);
  6559. if (baseVariable && baseVariable.isNamespace) {
  6560. const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
  6561. if (!resolvedVariable) {
  6562. super.bind();
  6563. }
  6564. else if (typeof resolvedVariable === 'string') {
  6565. this.replacement = resolvedVariable;
  6566. }
  6567. else {
  6568. this.variable = resolvedVariable;
  6569. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6570. }
  6571. }
  6572. else {
  6573. super.bind();
  6574. }
  6575. }
  6576. deoptimizeCache() {
  6577. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6578. this.expressionsToBeDeoptimized = [];
  6579. this.propertyKey = UnknownKey;
  6580. this.object.deoptimizePath(UNKNOWN_PATH);
  6581. for (const expression of expressionsToBeDeoptimized) {
  6582. expression.deoptimizeCache();
  6583. }
  6584. }
  6585. deoptimizePath(path) {
  6586. if (path.length === 0)
  6587. this.disallowNamespaceReassignment();
  6588. if (this.variable) {
  6589. this.variable.deoptimizePath(path);
  6590. }
  6591. else if (!this.replacement) {
  6592. if (path.length < MAX_PATH_DEPTH) {
  6593. this.object.deoptimizePath([this.getPropertyKey(), ...path]);
  6594. }
  6595. }
  6596. }
  6597. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  6598. if (this.variable) {
  6599. this.variable.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  6600. }
  6601. else if (!this.replacement) {
  6602. if (path.length < MAX_PATH_DEPTH) {
  6603. this.object.deoptimizeThisOnEventAtPath(event, [this.getPropertyKey(), ...path], thisParameter, recursionTracker);
  6604. }
  6605. else {
  6606. thisParameter.deoptimizePath(UNKNOWN_PATH);
  6607. }
  6608. }
  6609. }
  6610. getLiteralValueAtPath(path, recursionTracker, origin) {
  6611. if (this.variable !== null) {
  6612. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6613. }
  6614. if (this.replacement) {
  6615. return UnknownValue;
  6616. }
  6617. this.expressionsToBeDeoptimized.push(origin);
  6618. if (path.length < MAX_PATH_DEPTH) {
  6619. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6620. }
  6621. return UnknownValue;
  6622. }
  6623. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  6624. if (this.variable !== null) {
  6625. return this.variable.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  6626. }
  6627. if (this.replacement) {
  6628. return UNKNOWN_EXPRESSION;
  6629. }
  6630. this.expressionsToBeDeoptimized.push(origin);
  6631. if (path.length < MAX_PATH_DEPTH) {
  6632. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], callOptions, recursionTracker, origin);
  6633. }
  6634. return UNKNOWN_EXPRESSION;
  6635. }
  6636. hasEffects(context) {
  6637. if (!this.deoptimized)
  6638. this.applyDeoptimizations();
  6639. const { propertyReadSideEffects } = this.context.options
  6640. .treeshake;
  6641. return (this.property.hasEffects(context) ||
  6642. this.object.hasEffects(context) ||
  6643. // Assignments do not access the property before assigning
  6644. (!(this.variable ||
  6645. this.replacement ||
  6646. (this.parent instanceof AssignmentExpression && this.parent.operator === '=')) &&
  6647. propertyReadSideEffects &&
  6648. (propertyReadSideEffects === 'always' ||
  6649. this.object.hasEffectsWhenAccessedAtPath([this.getPropertyKey()], context))));
  6650. }
  6651. hasEffectsWhenAccessedAtPath(path, context) {
  6652. if (this.variable !== null) {
  6653. return this.variable.hasEffectsWhenAccessedAtPath(path, context);
  6654. }
  6655. if (this.replacement) {
  6656. return true;
  6657. }
  6658. if (path.length < MAX_PATH_DEPTH) {
  6659. return this.object.hasEffectsWhenAccessedAtPath([this.getPropertyKey(), ...path], context);
  6660. }
  6661. return true;
  6662. }
  6663. hasEffectsWhenAssignedAtPath(path, context) {
  6664. if (this.variable !== null) {
  6665. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  6666. }
  6667. if (this.replacement) {
  6668. return true;
  6669. }
  6670. if (path.length < MAX_PATH_DEPTH) {
  6671. return this.object.hasEffectsWhenAssignedAtPath([this.getPropertyKey(), ...path], context);
  6672. }
  6673. return true;
  6674. }
  6675. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6676. if (this.variable !== null) {
  6677. return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6678. }
  6679. if (this.replacement) {
  6680. return true;
  6681. }
  6682. if (path.length < MAX_PATH_DEPTH) {
  6683. return this.object.hasEffectsWhenCalledAtPath([this.getPropertyKey(), ...path], callOptions, context);
  6684. }
  6685. return true;
  6686. }
  6687. include(context, includeChildrenRecursively) {
  6688. if (!this.deoptimized)
  6689. this.applyDeoptimizations();
  6690. if (!this.included) {
  6691. this.included = true;
  6692. if (this.variable !== null) {
  6693. this.context.includeVariableInModule(this.variable);
  6694. }
  6695. }
  6696. this.object.include(context, includeChildrenRecursively);
  6697. this.property.include(context, includeChildrenRecursively);
  6698. }
  6699. includeCallArguments(context, args) {
  6700. if (this.variable) {
  6701. this.variable.includeCallArguments(context, args);
  6702. }
  6703. else {
  6704. super.includeCallArguments(context, args);
  6705. }
  6706. }
  6707. initialise() {
  6708. this.propertyKey = getResolvablePropertyKey(this);
  6709. }
  6710. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  6711. if (this.variable || this.replacement) {
  6712. let replacement = this.variable ? this.variable.getName() : this.replacement;
  6713. if (renderedParentType && isCalleeOfRenderedParent)
  6714. replacement = '0, ' + replacement;
  6715. code.overwrite(this.start, this.end, replacement, {
  6716. contentOnly: true,
  6717. storeName: true
  6718. });
  6719. }
  6720. else {
  6721. if (renderedParentType && isCalleeOfRenderedParent) {
  6722. code.appendRight(this.start, '0, ');
  6723. }
  6724. this.object.render(code, options, { renderedSurroundingElement });
  6725. this.property.render(code, options);
  6726. }
  6727. }
  6728. applyDeoptimizations() {
  6729. this.deoptimized = true;
  6730. const { propertyReadSideEffects } = this.context.options
  6731. .treeshake;
  6732. if (
  6733. // Namespaces are not bound and should not be deoptimized
  6734. this.bound &&
  6735. propertyReadSideEffects &&
  6736. !(this.variable || this.replacement)) {
  6737. // Regular Assignments do not access the property before assigning
  6738. if (!(this.parent instanceof AssignmentExpression && this.parent.operator === '=')) {
  6739. this.object.deoptimizeThisOnEventAtPath(EVENT_ACCESSED, [this.propertyKey], this.object, SHARED_RECURSION_TRACKER);
  6740. }
  6741. if (this.parent instanceof AssignmentExpression) {
  6742. this.object.deoptimizeThisOnEventAtPath(EVENT_ASSIGNED, [this.propertyKey], this.object, SHARED_RECURSION_TRACKER);
  6743. }
  6744. this.context.requestTreeshakingPass();
  6745. }
  6746. }
  6747. disallowNamespaceReassignment() {
  6748. if (this.object instanceof Identifier) {
  6749. const variable = this.scope.findVariable(this.object.name);
  6750. if (variable.isNamespace) {
  6751. if (this.variable) {
  6752. this.context.includeVariableInModule(this.variable);
  6753. }
  6754. this.context.warn({
  6755. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  6756. message: `Illegal reassignment to import '${this.object.name}'`
  6757. }, this.start);
  6758. }
  6759. }
  6760. }
  6761. getPropertyKey() {
  6762. if (this.propertyKey === null) {
  6763. this.propertyKey = UnknownKey;
  6764. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6765. return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
  6766. }
  6767. return this.propertyKey;
  6768. }
  6769. resolveNamespaceVariables(baseVariable, path) {
  6770. if (path.length === 0)
  6771. return baseVariable;
  6772. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  6773. return null;
  6774. const exportName = path[0].key;
  6775. const variable = baseVariable.context.traceExport(exportName);
  6776. if (!variable) {
  6777. const fileName = baseVariable.context.fileName;
  6778. this.context.warn({
  6779. code: 'MISSING_EXPORT',
  6780. exporter: relativeId(fileName),
  6781. importer: relativeId(this.context.fileName),
  6782. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  6783. missing: exportName,
  6784. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  6785. }, path[0].pos);
  6786. return 'undefined';
  6787. }
  6788. return this.resolveNamespaceVariables(variable, path.slice(1));
  6789. }
  6790. }
  6791. class CallExpression extends NodeBase {
  6792. constructor() {
  6793. super(...arguments);
  6794. this.deoptimized = false;
  6795. this.deoptimizableDependentExpressions = [];
  6796. this.expressionsToBeDeoptimized = new Set();
  6797. this.returnExpression = null;
  6798. }
  6799. bind() {
  6800. super.bind();
  6801. if (this.callee instanceof Identifier) {
  6802. const variable = this.scope.findVariable(this.callee.name);
  6803. if (variable.isNamespace) {
  6804. this.context.warn({
  6805. code: 'CANNOT_CALL_NAMESPACE',
  6806. message: `Cannot call a namespace ('${this.callee.name}')`
  6807. }, this.start);
  6808. }
  6809. if (this.callee.name === 'eval') {
  6810. this.context.warn({
  6811. code: 'EVAL',
  6812. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  6813. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  6814. }, this.start);
  6815. }
  6816. }
  6817. this.callOptions = {
  6818. args: this.arguments,
  6819. thisParam: this.callee instanceof MemberExpression && !this.callee.variable
  6820. ? this.callee.object
  6821. : null,
  6822. withNew: false
  6823. };
  6824. }
  6825. deoptimizeCache() {
  6826. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  6827. this.returnExpression = UNKNOWN_EXPRESSION;
  6828. for (const expression of this.deoptimizableDependentExpressions) {
  6829. expression.deoptimizeCache();
  6830. }
  6831. for (const expression of this.expressionsToBeDeoptimized) {
  6832. expression.deoptimizePath(UNKNOWN_PATH);
  6833. }
  6834. }
  6835. }
  6836. deoptimizePath(path) {
  6837. if (path.length === 0 ||
  6838. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  6839. return;
  6840. }
  6841. const returnExpression = this.getReturnExpression();
  6842. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6843. returnExpression.deoptimizePath(path);
  6844. }
  6845. }
  6846. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  6847. const returnExpression = this.getReturnExpression(recursionTracker);
  6848. if (returnExpression === UNKNOWN_EXPRESSION) {
  6849. thisParameter.deoptimizePath(UNKNOWN_PATH);
  6850. }
  6851. else {
  6852. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  6853. this.expressionsToBeDeoptimized.add(thisParameter);
  6854. returnExpression.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  6855. }, undefined);
  6856. }
  6857. }
  6858. getLiteralValueAtPath(path, recursionTracker, origin) {
  6859. const returnExpression = this.getReturnExpression(recursionTracker);
  6860. if (returnExpression === UNKNOWN_EXPRESSION) {
  6861. return UnknownValue;
  6862. }
  6863. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  6864. this.deoptimizableDependentExpressions.push(origin);
  6865. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6866. }, UnknownValue);
  6867. }
  6868. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  6869. const returnExpression = this.getReturnExpression(recursionTracker);
  6870. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  6871. return UNKNOWN_EXPRESSION;
  6872. }
  6873. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  6874. this.deoptimizableDependentExpressions.push(origin);
  6875. return returnExpression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  6876. }, UNKNOWN_EXPRESSION);
  6877. }
  6878. hasEffects(context) {
  6879. try {
  6880. for (const argument of this.arguments) {
  6881. if (argument.hasEffects(context))
  6882. return true;
  6883. }
  6884. if (this.context.options.treeshake.annotations &&
  6885. this.annotations)
  6886. return false;
  6887. return (this.callee.hasEffects(context) ||
  6888. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  6889. }
  6890. finally {
  6891. if (!this.deoptimized)
  6892. this.applyDeoptimizations();
  6893. }
  6894. }
  6895. hasEffectsWhenAccessedAtPath(path, context) {
  6896. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  6897. this.getReturnExpression().hasEffectsWhenAccessedAtPath(path, context));
  6898. }
  6899. hasEffectsWhenAssignedAtPath(path, context) {
  6900. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  6901. this.getReturnExpression().hasEffectsWhenAssignedAtPath(path, context));
  6902. }
  6903. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6904. return (!(callOptions.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, callOptions, this) &&
  6905. this.getReturnExpression().hasEffectsWhenCalledAtPath(path, callOptions, context));
  6906. }
  6907. include(context, includeChildrenRecursively) {
  6908. if (!this.deoptimized)
  6909. this.applyDeoptimizations();
  6910. if (includeChildrenRecursively) {
  6911. super.include(context, includeChildrenRecursively);
  6912. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  6913. this.callee instanceof Identifier &&
  6914. this.callee.variable) {
  6915. this.callee.variable.markCalledFromTryStatement();
  6916. }
  6917. }
  6918. else {
  6919. this.included = true;
  6920. this.callee.include(context, false);
  6921. }
  6922. this.callee.includeCallArguments(context, this.arguments);
  6923. const returnExpression = this.getReturnExpression();
  6924. if (!returnExpression.included) {
  6925. returnExpression.include(context, false);
  6926. }
  6927. }
  6928. render(code, options, { renderedSurroundingElement } = BLANK) {
  6929. this.callee.render(code, options, {
  6930. isCalleeOfRenderedParent: true,
  6931. renderedSurroundingElement
  6932. });
  6933. if (this.arguments.length > 0) {
  6934. if (this.arguments[this.arguments.length - 1].included) {
  6935. for (const arg of this.arguments) {
  6936. arg.render(code, options);
  6937. }
  6938. }
  6939. else {
  6940. let lastIncludedIndex = this.arguments.length - 2;
  6941. while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
  6942. lastIncludedIndex--;
  6943. }
  6944. if (lastIncludedIndex >= 0) {
  6945. for (let index = 0; index <= lastIncludedIndex; index++) {
  6946. this.arguments[index].render(code, options);
  6947. }
  6948. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
  6949. }
  6950. else {
  6951. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
  6952. }
  6953. }
  6954. }
  6955. }
  6956. applyDeoptimizations() {
  6957. this.deoptimized = true;
  6958. const { thisParam } = this.callOptions;
  6959. if (thisParam) {
  6960. this.callee.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParam, SHARED_RECURSION_TRACKER);
  6961. }
  6962. for (const argument of this.arguments) {
  6963. // This will make sure all properties of parameters behave as "unknown"
  6964. argument.deoptimizePath(UNKNOWN_PATH);
  6965. }
  6966. this.context.requestTreeshakingPass();
  6967. }
  6968. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  6969. if (this.returnExpression === null) {
  6970. this.returnExpression = UNKNOWN_EXPRESSION;
  6971. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.callOptions, recursionTracker, this));
  6972. }
  6973. return this.returnExpression;
  6974. }
  6975. }
  6976. class CatchScope extends ParameterScope {
  6977. addDeclaration(identifier, context, init, isHoisted) {
  6978. const existingParameter = this.variables.get(identifier.name);
  6979. if (existingParameter) {
  6980. // While we still create a hoisted declaration, the initializer goes to
  6981. // the parameter. Note that technically, the declaration now belongs to
  6982. // two variables, which is not correct but should not cause issues.
  6983. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  6984. existingParameter.addDeclaration(identifier, init);
  6985. return existingParameter;
  6986. }
  6987. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6988. }
  6989. }
  6990. class CatchClause extends NodeBase {
  6991. createScope(parentScope) {
  6992. this.scope = new CatchScope(parentScope, this.context);
  6993. }
  6994. parseNode(esTreeNode) {
  6995. // Parameters need to be declared first as the logic is that initializers
  6996. // of hoisted body variables are associated with parameters of the same
  6997. // name instead of the variable
  6998. const { param } = esTreeNode;
  6999. if (param) {
  7000. this.param = new (this.context.nodeConstructors[param.type] ||
  7001. this.context.nodeConstructors.UnknownNode)(param, this, this.scope);
  7002. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  7003. }
  7004. super.parseNode(esTreeNode);
  7005. }
  7006. }
  7007. class ChainExpression extends NodeBase {
  7008. }
  7009. class ClassBodyScope extends ChildScope {
  7010. constructor(parent, classNode, context) {
  7011. super(parent);
  7012. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  7013. this.instanceScope = new ChildScope(this);
  7014. this.instanceScope.variables.set('this', new ThisVariable(context));
  7015. }
  7016. findLexicalBoundary() {
  7017. return this;
  7018. }
  7019. }
  7020. class ClassBody extends NodeBase {
  7021. createScope(parentScope) {
  7022. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  7023. }
  7024. include(context, includeChildrenRecursively) {
  7025. this.included = true;
  7026. this.context.includeVariableInModule(this.scope.thisVariable);
  7027. for (const definition of this.body) {
  7028. definition.include(context, includeChildrenRecursively);
  7029. }
  7030. }
  7031. parseNode(esTreeNode) {
  7032. const body = (this.body = []);
  7033. for (const definition of esTreeNode.body) {
  7034. body.push(new this.context.nodeConstructors[definition.type](definition, this, definition.static ? this.scope : this.scope.instanceScope));
  7035. }
  7036. super.parseNode(esTreeNode);
  7037. }
  7038. }
  7039. class ClassExpression extends ClassNode {
  7040. render(code, options, { renderedSurroundingElement } = BLANK) {
  7041. super.render(code, options);
  7042. if (renderedSurroundingElement === ExpressionStatement$1) {
  7043. code.appendRight(this.start, '(');
  7044. code.prependLeft(this.end, ')');
  7045. }
  7046. }
  7047. }
  7048. class MultiExpression extends ExpressionEntity {
  7049. constructor(expressions) {
  7050. super();
  7051. this.expressions = expressions;
  7052. this.included = false;
  7053. }
  7054. deoptimizePath(path) {
  7055. for (const expression of this.expressions) {
  7056. expression.deoptimizePath(path);
  7057. }
  7058. }
  7059. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  7060. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)));
  7061. }
  7062. hasEffectsWhenAccessedAtPath(path, context) {
  7063. for (const expression of this.expressions) {
  7064. if (expression.hasEffectsWhenAccessedAtPath(path, context))
  7065. return true;
  7066. }
  7067. return false;
  7068. }
  7069. hasEffectsWhenAssignedAtPath(path, context) {
  7070. for (const expression of this.expressions) {
  7071. if (expression.hasEffectsWhenAssignedAtPath(path, context))
  7072. return true;
  7073. }
  7074. return false;
  7075. }
  7076. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7077. for (const expression of this.expressions) {
  7078. if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
  7079. return true;
  7080. }
  7081. return false;
  7082. }
  7083. include(context, includeChildrenRecursively) {
  7084. // This is only relevant to include values that do not have an AST representation,
  7085. // such as UnknownArrayExpression. Thus we only need to include them once.
  7086. for (const expression of this.expressions) {
  7087. if (!expression.included) {
  7088. expression.include(context, includeChildrenRecursively);
  7089. }
  7090. }
  7091. }
  7092. }
  7093. class ConditionalExpression extends NodeBase {
  7094. constructor() {
  7095. super(...arguments);
  7096. this.expressionsToBeDeoptimized = [];
  7097. this.isBranchResolutionAnalysed = false;
  7098. this.usedBranch = null;
  7099. }
  7100. deoptimizeCache() {
  7101. if (this.usedBranch !== null) {
  7102. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  7103. this.usedBranch = null;
  7104. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7105. for (const expression of this.expressionsToBeDeoptimized) {
  7106. expression.deoptimizeCache();
  7107. }
  7108. }
  7109. }
  7110. deoptimizePath(path) {
  7111. const usedBranch = this.getUsedBranch();
  7112. if (usedBranch === null) {
  7113. this.consequent.deoptimizePath(path);
  7114. this.alternate.deoptimizePath(path);
  7115. }
  7116. else {
  7117. usedBranch.deoptimizePath(path);
  7118. }
  7119. }
  7120. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  7121. this.consequent.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  7122. this.alternate.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  7123. }
  7124. getLiteralValueAtPath(path, recursionTracker, origin) {
  7125. const usedBranch = this.getUsedBranch();
  7126. if (usedBranch === null)
  7127. return UnknownValue;
  7128. this.expressionsToBeDeoptimized.push(origin);
  7129. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7130. }
  7131. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  7132. const usedBranch = this.getUsedBranch();
  7133. if (usedBranch === null)
  7134. return new MultiExpression([
  7135. this.consequent.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin),
  7136. this.alternate.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
  7137. ]);
  7138. this.expressionsToBeDeoptimized.push(origin);
  7139. return usedBranch.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  7140. }
  7141. hasEffects(context) {
  7142. if (this.test.hasEffects(context))
  7143. return true;
  7144. const usedBranch = this.getUsedBranch();
  7145. if (usedBranch === null) {
  7146. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  7147. }
  7148. return usedBranch.hasEffects(context);
  7149. }
  7150. hasEffectsWhenAccessedAtPath(path, context) {
  7151. const usedBranch = this.getUsedBranch();
  7152. if (usedBranch === null) {
  7153. return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
  7154. this.alternate.hasEffectsWhenAccessedAtPath(path, context));
  7155. }
  7156. return usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7157. }
  7158. hasEffectsWhenAssignedAtPath(path, context) {
  7159. const usedBranch = this.getUsedBranch();
  7160. if (usedBranch === null) {
  7161. return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
  7162. this.alternate.hasEffectsWhenAssignedAtPath(path, context));
  7163. }
  7164. return usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7165. }
  7166. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7167. const usedBranch = this.getUsedBranch();
  7168. if (usedBranch === null) {
  7169. return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7170. this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7171. }
  7172. return usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7173. }
  7174. include(context, includeChildrenRecursively) {
  7175. this.included = true;
  7176. const usedBranch = this.getUsedBranch();
  7177. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  7178. this.test.include(context, includeChildrenRecursively);
  7179. this.consequent.include(context, includeChildrenRecursively);
  7180. this.alternate.include(context, includeChildrenRecursively);
  7181. }
  7182. else {
  7183. usedBranch.include(context, includeChildrenRecursively);
  7184. }
  7185. }
  7186. includeCallArguments(context, args) {
  7187. const usedBranch = this.getUsedBranch();
  7188. if (usedBranch === null) {
  7189. this.consequent.includeCallArguments(context, args);
  7190. this.alternate.includeCallArguments(context, args);
  7191. }
  7192. else {
  7193. usedBranch.includeCallArguments(context, args);
  7194. }
  7195. }
  7196. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7197. const usedBranch = this.getUsedBranch();
  7198. if (!this.test.included) {
  7199. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  7200. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  7201. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  7202. : colonPos) + 1);
  7203. if (preventASI) {
  7204. removeLineBreaks(code, inclusionStart, usedBranch.start);
  7205. }
  7206. code.remove(this.start, inclusionStart);
  7207. if (this.consequent.included) {
  7208. code.remove(colonPos, this.end);
  7209. }
  7210. removeAnnotations(this, code);
  7211. usedBranch.render(code, options, {
  7212. isCalleeOfRenderedParent,
  7213. preventASI: true,
  7214. renderedParentType: renderedParentType || this.parent.type,
  7215. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  7216. });
  7217. }
  7218. else {
  7219. this.test.render(code, options, { renderedSurroundingElement });
  7220. this.consequent.render(code, options);
  7221. this.alternate.render(code, options);
  7222. }
  7223. }
  7224. getUsedBranch() {
  7225. if (this.isBranchResolutionAnalysed) {
  7226. return this.usedBranch;
  7227. }
  7228. this.isBranchResolutionAnalysed = true;
  7229. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7230. return testValue === UnknownValue
  7231. ? null
  7232. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  7233. }
  7234. }
  7235. class ContinueStatement extends NodeBase {
  7236. hasEffects(context) {
  7237. if (this.label) {
  7238. if (!context.ignore.labels.has(this.label.name))
  7239. return true;
  7240. context.includedLabels.add(this.label.name);
  7241. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7242. }
  7243. else {
  7244. if (!context.ignore.continues)
  7245. return true;
  7246. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7247. }
  7248. return false;
  7249. }
  7250. include(context) {
  7251. this.included = true;
  7252. if (this.label) {
  7253. this.label.include();
  7254. context.includedLabels.add(this.label.name);
  7255. }
  7256. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7257. }
  7258. }
  7259. class DoWhileStatement extends NodeBase {
  7260. hasEffects(context) {
  7261. if (this.test.hasEffects(context))
  7262. return true;
  7263. const { brokenFlow, ignore: { breaks, continues } } = context;
  7264. context.ignore.breaks = true;
  7265. context.ignore.continues = true;
  7266. if (this.body.hasEffects(context))
  7267. return true;
  7268. context.ignore.breaks = breaks;
  7269. context.ignore.continues = continues;
  7270. context.brokenFlow = brokenFlow;
  7271. return false;
  7272. }
  7273. include(context, includeChildrenRecursively) {
  7274. this.included = true;
  7275. this.test.include(context, includeChildrenRecursively);
  7276. const { brokenFlow } = context;
  7277. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  7278. context.brokenFlow = brokenFlow;
  7279. }
  7280. }
  7281. class EmptyStatement extends NodeBase {
  7282. hasEffects() {
  7283. return false;
  7284. }
  7285. }
  7286. class ExportNamedDeclaration extends NodeBase {
  7287. bind() {
  7288. // Do not bind specifiers
  7289. if (this.declaration !== null)
  7290. this.declaration.bind();
  7291. }
  7292. hasEffects(context) {
  7293. return this.declaration !== null && this.declaration.hasEffects(context);
  7294. }
  7295. initialise() {
  7296. this.context.addExport(this);
  7297. }
  7298. render(code, options, nodeRenderOptions) {
  7299. const { start, end } = nodeRenderOptions;
  7300. if (this.declaration === null) {
  7301. code.remove(start, end);
  7302. }
  7303. else {
  7304. code.remove(this.start, this.declaration.start);
  7305. this.declaration.render(code, options, { end, start });
  7306. }
  7307. }
  7308. }
  7309. ExportNamedDeclaration.prototype.needsBoundaries = true;
  7310. class ExportSpecifier extends NodeBase {
  7311. }
  7312. class ForInStatement extends NodeBase {
  7313. constructor() {
  7314. super(...arguments);
  7315. this.deoptimized = false;
  7316. }
  7317. createScope(parentScope) {
  7318. this.scope = new BlockScope(parentScope);
  7319. }
  7320. hasEffects(context) {
  7321. if (!this.deoptimized)
  7322. this.applyDeoptimizations();
  7323. if ((this.left &&
  7324. (this.left.hasEffects(context) ||
  7325. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
  7326. (this.right && this.right.hasEffects(context)))
  7327. return true;
  7328. const { brokenFlow, ignore: { breaks, continues } } = context;
  7329. context.ignore.breaks = true;
  7330. context.ignore.continues = true;
  7331. if (this.body.hasEffects(context))
  7332. return true;
  7333. context.ignore.breaks = breaks;
  7334. context.ignore.continues = continues;
  7335. context.brokenFlow = brokenFlow;
  7336. return false;
  7337. }
  7338. include(context, includeChildrenRecursively) {
  7339. if (!this.deoptimized)
  7340. this.applyDeoptimizations();
  7341. this.included = true;
  7342. this.left.include(context, includeChildrenRecursively || true);
  7343. this.right.include(context, includeChildrenRecursively);
  7344. const { brokenFlow } = context;
  7345. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  7346. context.brokenFlow = brokenFlow;
  7347. }
  7348. render(code, options) {
  7349. this.left.render(code, options, NO_SEMICOLON);
  7350. this.right.render(code, options, NO_SEMICOLON);
  7351. // handle no space between "in" and the right side
  7352. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  7353. code.prependLeft(this.right.start, ' ');
  7354. }
  7355. this.body.render(code, options);
  7356. }
  7357. applyDeoptimizations() {
  7358. this.deoptimized = true;
  7359. this.left.deoptimizePath(EMPTY_PATH);
  7360. this.context.requestTreeshakingPass();
  7361. }
  7362. }
  7363. class ForOfStatement extends NodeBase {
  7364. constructor() {
  7365. super(...arguments);
  7366. this.deoptimized = false;
  7367. }
  7368. createScope(parentScope) {
  7369. this.scope = new BlockScope(parentScope);
  7370. }
  7371. hasEffects() {
  7372. if (!this.deoptimized)
  7373. this.applyDeoptimizations();
  7374. // Placeholder until proper Symbol.Iterator support
  7375. return true;
  7376. }
  7377. include(context, includeChildrenRecursively) {
  7378. if (!this.deoptimized)
  7379. this.applyDeoptimizations();
  7380. this.included = true;
  7381. this.left.include(context, includeChildrenRecursively || true);
  7382. this.right.include(context, includeChildrenRecursively);
  7383. const { brokenFlow } = context;
  7384. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  7385. context.brokenFlow = brokenFlow;
  7386. }
  7387. render(code, options) {
  7388. this.left.render(code, options, NO_SEMICOLON);
  7389. this.right.render(code, options, NO_SEMICOLON);
  7390. // handle no space between "of" and the right side
  7391. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  7392. code.prependLeft(this.right.start, ' ');
  7393. }
  7394. this.body.render(code, options);
  7395. }
  7396. applyDeoptimizations() {
  7397. this.deoptimized = true;
  7398. this.left.deoptimizePath(EMPTY_PATH);
  7399. this.context.requestTreeshakingPass();
  7400. }
  7401. }
  7402. class ForStatement extends NodeBase {
  7403. createScope(parentScope) {
  7404. this.scope = new BlockScope(parentScope);
  7405. }
  7406. hasEffects(context) {
  7407. if ((this.init && this.init.hasEffects(context)) ||
  7408. (this.test && this.test.hasEffects(context)) ||
  7409. (this.update && this.update.hasEffects(context)))
  7410. return true;
  7411. const { brokenFlow, ignore: { breaks, continues } } = context;
  7412. context.ignore.breaks = true;
  7413. context.ignore.continues = true;
  7414. if (this.body.hasEffects(context))
  7415. return true;
  7416. context.ignore.breaks = breaks;
  7417. context.ignore.continues = continues;
  7418. context.brokenFlow = brokenFlow;
  7419. return false;
  7420. }
  7421. include(context, includeChildrenRecursively) {
  7422. this.included = true;
  7423. if (this.init)
  7424. this.init.includeAsSingleStatement(context, includeChildrenRecursively);
  7425. if (this.test)
  7426. this.test.include(context, includeChildrenRecursively);
  7427. const { brokenFlow } = context;
  7428. if (this.update)
  7429. this.update.include(context, includeChildrenRecursively);
  7430. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  7431. context.brokenFlow = brokenFlow;
  7432. }
  7433. render(code, options) {
  7434. if (this.init)
  7435. this.init.render(code, options, NO_SEMICOLON);
  7436. if (this.test)
  7437. this.test.render(code, options, NO_SEMICOLON);
  7438. if (this.update)
  7439. this.update.render(code, options, NO_SEMICOLON);
  7440. this.body.render(code, options);
  7441. }
  7442. }
  7443. class FunctionExpression extends FunctionNode {
  7444. render(code, options, { renderedSurroundingElement } = BLANK) {
  7445. super.render(code, options);
  7446. if (renderedSurroundingElement === ExpressionStatement$1) {
  7447. code.appendRight(this.start, '(');
  7448. code.prependLeft(this.end, ')');
  7449. }
  7450. }
  7451. }
  7452. class TrackingScope extends BlockScope {
  7453. constructor() {
  7454. super(...arguments);
  7455. this.hoistedDeclarations = [];
  7456. }
  7457. addDeclaration(identifier, context, init, isHoisted) {
  7458. this.hoistedDeclarations.push(identifier);
  7459. return super.addDeclaration(identifier, context, init, isHoisted);
  7460. }
  7461. }
  7462. const unset = Symbol('unset');
  7463. class IfStatement extends NodeBase {
  7464. constructor() {
  7465. super(...arguments);
  7466. this.testValue = unset;
  7467. }
  7468. deoptimizeCache() {
  7469. this.testValue = UnknownValue;
  7470. }
  7471. hasEffects(context) {
  7472. if (this.test.hasEffects(context)) {
  7473. return true;
  7474. }
  7475. const testValue = this.getTestValue();
  7476. if (testValue === UnknownValue) {
  7477. const { brokenFlow } = context;
  7478. if (this.consequent.hasEffects(context))
  7479. return true;
  7480. const consequentBrokenFlow = context.brokenFlow;
  7481. context.brokenFlow = brokenFlow;
  7482. if (this.alternate === null)
  7483. return false;
  7484. if (this.alternate.hasEffects(context))
  7485. return true;
  7486. context.brokenFlow =
  7487. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7488. return false;
  7489. }
  7490. return testValue
  7491. ? this.consequent.hasEffects(context)
  7492. : this.alternate !== null && this.alternate.hasEffects(context);
  7493. }
  7494. include(context, includeChildrenRecursively) {
  7495. this.included = true;
  7496. if (includeChildrenRecursively) {
  7497. this.includeRecursively(includeChildrenRecursively, context);
  7498. }
  7499. else {
  7500. const testValue = this.getTestValue();
  7501. if (testValue === UnknownValue) {
  7502. this.includeUnknownTest(context);
  7503. }
  7504. else {
  7505. this.includeKnownTest(context, testValue);
  7506. }
  7507. }
  7508. }
  7509. parseNode(esTreeNode) {
  7510. this.consequentScope = new TrackingScope(this.scope);
  7511. this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
  7512. this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
  7513. if (esTreeNode.alternate) {
  7514. this.alternateScope = new TrackingScope(this.scope);
  7515. this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
  7516. this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
  7517. }
  7518. super.parseNode(esTreeNode);
  7519. }
  7520. render(code, options) {
  7521. // Note that unknown test values are always included
  7522. const testValue = this.getTestValue();
  7523. const hoistedDeclarations = [];
  7524. const includesIfElse = this.test.included;
  7525. const noTreeshake = !this.context.options.treeshake;
  7526. if (includesIfElse) {
  7527. this.test.render(code, options);
  7528. }
  7529. else {
  7530. code.remove(this.start, this.consequent.start);
  7531. }
  7532. if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
  7533. this.consequent.render(code, options);
  7534. }
  7535. else {
  7536. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  7537. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  7538. }
  7539. if (this.alternate) {
  7540. if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
  7541. if (includesIfElse) {
  7542. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  7543. code.prependLeft(this.alternate.start, ' ');
  7544. }
  7545. }
  7546. else {
  7547. code.remove(this.consequent.end, this.alternate.start);
  7548. }
  7549. this.alternate.render(code, options);
  7550. }
  7551. else {
  7552. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  7553. code.overwrite(this.alternate.start, this.end, ';');
  7554. }
  7555. else {
  7556. code.remove(this.consequent.end, this.end);
  7557. }
  7558. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  7559. }
  7560. }
  7561. this.renderHoistedDeclarations(hoistedDeclarations, code);
  7562. }
  7563. getTestValue() {
  7564. if (this.testValue === unset) {
  7565. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  7566. }
  7567. return this.testValue;
  7568. }
  7569. includeKnownTest(context, testValue) {
  7570. if (this.test.shouldBeIncluded(context)) {
  7571. this.test.include(context, false);
  7572. }
  7573. if (testValue && this.consequent.shouldBeIncluded(context)) {
  7574. this.consequent.includeAsSingleStatement(context, false);
  7575. }
  7576. if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
  7577. this.alternate.includeAsSingleStatement(context, false);
  7578. }
  7579. }
  7580. includeRecursively(includeChildrenRecursively, context) {
  7581. this.test.include(context, includeChildrenRecursively);
  7582. this.consequent.include(context, includeChildrenRecursively);
  7583. if (this.alternate !== null) {
  7584. this.alternate.include(context, includeChildrenRecursively);
  7585. }
  7586. }
  7587. includeUnknownTest(context) {
  7588. this.test.include(context, false);
  7589. const { brokenFlow } = context;
  7590. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  7591. if (this.consequent.shouldBeIncluded(context)) {
  7592. this.consequent.includeAsSingleStatement(context, false);
  7593. consequentBrokenFlow = context.brokenFlow;
  7594. context.brokenFlow = brokenFlow;
  7595. }
  7596. if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
  7597. this.alternate.includeAsSingleStatement(context, false);
  7598. context.brokenFlow =
  7599. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7600. }
  7601. }
  7602. renderHoistedDeclarations(hoistedDeclarations, code) {
  7603. const hoistedVars = [
  7604. ...new Set(hoistedDeclarations.map(identifier => {
  7605. const variable = identifier.variable;
  7606. return variable.included ? variable.getName() : '';
  7607. }))
  7608. ]
  7609. .filter(Boolean)
  7610. .join(', ');
  7611. if (hoistedVars) {
  7612. const parentType = this.parent.type;
  7613. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  7614. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  7615. if (needsBraces) {
  7616. code.appendLeft(this.end, ` }`);
  7617. }
  7618. }
  7619. }
  7620. shouldKeepAlternateBranch() {
  7621. let currentParent = this.parent;
  7622. do {
  7623. if (currentParent instanceof IfStatement && currentParent.alternate) {
  7624. return true;
  7625. }
  7626. if (currentParent instanceof BlockStatement) {
  7627. return false;
  7628. }
  7629. currentParent = currentParent.parent;
  7630. } while (currentParent);
  7631. return false;
  7632. }
  7633. }
  7634. class ImportDeclaration extends NodeBase {
  7635. // Do not bind specifiers
  7636. bind() { }
  7637. hasEffects() {
  7638. return false;
  7639. }
  7640. initialise() {
  7641. this.context.addImport(this);
  7642. }
  7643. render(code, _options, nodeRenderOptions) {
  7644. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  7645. }
  7646. }
  7647. ImportDeclaration.prototype.needsBoundaries = true;
  7648. class ImportDefaultSpecifier extends NodeBase {
  7649. }
  7650. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  7651. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  7652. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  7653. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  7654. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  7655. const defaultInteropHelpersByInteropType = {
  7656. auto: INTEROP_DEFAULT_VARIABLE,
  7657. default: null,
  7658. defaultOnly: null,
  7659. esModule: null,
  7660. false: null,
  7661. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  7662. };
  7663. function isDefaultAProperty(interopType, externalLiveBindings) {
  7664. return (interopType === 'esModule' ||
  7665. (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
  7666. }
  7667. const namespaceInteropHelpersByInteropType = {
  7668. auto: INTEROP_NAMESPACE_VARIABLE,
  7669. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  7670. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  7671. esModule: null,
  7672. false: null,
  7673. true: INTEROP_NAMESPACE_VARIABLE
  7674. };
  7675. function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
  7676. return (isDefaultAProperty(interopType, externalLiveBindings) &&
  7677. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
  7678. }
  7679. function getDefaultOnlyHelper() {
  7680. return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
  7681. }
  7682. function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
  7683. return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
  7684. ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  7685. : '').join('');
  7686. }
  7687. const HELPER_GENERATORS = {
  7688. [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
  7689. `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  7690. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  7691. [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
  7692. `e${_}&&${_}e.__esModule${_}?${_}` +
  7693. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  7694. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
  7695. `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
  7696. `}${n}${n}`,
  7697. [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  7698. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
  7699. `}${n}${n}`,
  7700. [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  7701. (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
  7702. ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
  7703. : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  7704. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
  7705. `}${n}${n}`
  7706. };
  7707. function getDefaultLiveBinding(_) {
  7708. return `e${_}:${_}{${_}'default':${_}e${_}}`;
  7709. }
  7710. function getDefaultStatic(_) {
  7711. return `e['default']${_}:${_}e`;
  7712. }
  7713. function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
  7714. return (`${i}var n${_}=${_}${namespaceToStringTag
  7715. ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
  7716. : 'Object.create(null)'};${n}` +
  7717. `${i}if${_}(e)${_}{${n}` +
  7718. `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
  7719. (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
  7720. `${i}${t}});${n}` +
  7721. `${i}}${n}` +
  7722. `${i}n['default']${_}=${_}e;${n}` +
  7723. `${i}return ${getFrozen('n', freeze)};${n}`);
  7724. }
  7725. function copyPropertyLiveBinding(_, n, t, i) {
  7726. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  7727. `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  7728. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  7729. `${i}${t}${t}enumerable:${_}true,${n}` +
  7730. `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
  7731. `${i}${t}${t}${t}return e[k];${n}` +
  7732. `${i}${t}${t}}${n}` +
  7733. `${i}${t}});${n}` +
  7734. `${i}}${n}`);
  7735. }
  7736. function copyPropertyStatic(_, n, _t, i) {
  7737. return `${i}n[k]${_}=${_}e[k];${n}`;
  7738. }
  7739. function getFrozen(fragment, freeze) {
  7740. return freeze ? `Object.freeze(${fragment})` : fragment;
  7741. }
  7742. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  7743. class ImportExpression extends NodeBase {
  7744. constructor() {
  7745. super(...arguments);
  7746. this.inlineNamespace = null;
  7747. this.mechanism = null;
  7748. this.resolution = null;
  7749. }
  7750. hasEffects() {
  7751. return true;
  7752. }
  7753. include(context, includeChildrenRecursively) {
  7754. if (!this.included) {
  7755. this.included = true;
  7756. this.context.includeDynamicImport(this);
  7757. this.scope.addAccessedDynamicImport(this);
  7758. }
  7759. this.source.include(context, includeChildrenRecursively);
  7760. }
  7761. initialise() {
  7762. this.context.addDynamicImport(this);
  7763. }
  7764. render(code, options) {
  7765. if (this.inlineNamespace) {
  7766. const _ = options.compact ? '' : ' ';
  7767. const s = options.compact ? '' : ';';
  7768. code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`, { contentOnly: true });
  7769. return;
  7770. }
  7771. if (this.mechanism) {
  7772. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  7773. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  7774. }
  7775. this.source.render(code, options);
  7776. }
  7777. renderFinalResolution(code, resolution, namespaceExportName, options) {
  7778. code.overwrite(this.source.start, this.source.end, resolution);
  7779. if (namespaceExportName) {
  7780. const _ = options.compact ? '' : ' ';
  7781. const s = options.compact ? '' : ';';
  7782. code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
  7783. }
  7784. }
  7785. setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
  7786. this.resolution = resolution;
  7787. const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
  7788. let helper;
  7789. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
  7790. if (helper) {
  7791. accessedGlobals.push(helper);
  7792. }
  7793. if (accessedGlobals.length > 0) {
  7794. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7795. }
  7796. }
  7797. setInternalResolution(inlineNamespace) {
  7798. this.inlineNamespace = inlineNamespace;
  7799. }
  7800. getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
  7801. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  7802. {
  7803. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  7804. format: options.format,
  7805. moduleId: this.context.module.id,
  7806. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  7807. }
  7808. ]);
  7809. if (mechanism) {
  7810. return { helper: null, mechanism };
  7811. }
  7812. switch (options.format) {
  7813. case 'cjs': {
  7814. const _ = options.compact ? '' : ' ';
  7815. const s = options.compact ? '' : ';';
  7816. const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
  7817. const helper = getInteropHelper(resolution, exportMode, options.interop);
  7818. return {
  7819. helper,
  7820. mechanism: helper
  7821. ? {
  7822. left: `${leftStart} /*#__PURE__*/${helper}(require(`,
  7823. right: `))${s}${_}})`
  7824. }
  7825. : {
  7826. left: `${leftStart} require(`,
  7827. right: `)${s}${_}})`
  7828. }
  7829. };
  7830. }
  7831. case 'amd': {
  7832. const _ = options.compact ? '' : ' ';
  7833. const resolve = options.compact ? 'c' : 'resolve';
  7834. const reject = options.compact ? 'e' : 'reject';
  7835. const helper = getInteropHelper(resolution, exportMode, options.interop);
  7836. const resolveNamespace = helper
  7837. ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
  7838. : resolve;
  7839. return {
  7840. helper,
  7841. mechanism: {
  7842. left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
  7843. right: `],${_}${resolveNamespace},${_}${reject})${_}})`
  7844. }
  7845. };
  7846. }
  7847. case 'system':
  7848. return {
  7849. helper: null,
  7850. mechanism: {
  7851. left: 'module.import(',
  7852. right: ')'
  7853. }
  7854. };
  7855. case 'es':
  7856. if (options.dynamicImportFunction) {
  7857. return {
  7858. helper: null,
  7859. mechanism: {
  7860. left: `${options.dynamicImportFunction}(`,
  7861. right: ')'
  7862. }
  7863. };
  7864. }
  7865. }
  7866. return { helper: null, mechanism: null };
  7867. }
  7868. }
  7869. function getInteropHelper(resolution, exportMode, interop) {
  7870. return exportMode === 'external'
  7871. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  7872. : exportMode === 'default'
  7873. ? getDefaultOnlyHelper()
  7874. : null;
  7875. }
  7876. const accessedImportGlobals = {
  7877. amd: ['require'],
  7878. cjs: ['require'],
  7879. system: ['module']
  7880. };
  7881. class ImportNamespaceSpecifier extends NodeBase {
  7882. }
  7883. class ImportSpecifier extends NodeBase {
  7884. }
  7885. class LabeledStatement extends NodeBase {
  7886. hasEffects(context) {
  7887. const brokenFlow = context.brokenFlow;
  7888. context.ignore.labels.add(this.label.name);
  7889. if (this.body.hasEffects(context))
  7890. return true;
  7891. context.ignore.labels.delete(this.label.name);
  7892. if (context.includedLabels.has(this.label.name)) {
  7893. context.includedLabels.delete(this.label.name);
  7894. context.brokenFlow = brokenFlow;
  7895. }
  7896. return false;
  7897. }
  7898. include(context, includeChildrenRecursively) {
  7899. this.included = true;
  7900. const brokenFlow = context.brokenFlow;
  7901. this.body.include(context, includeChildrenRecursively);
  7902. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  7903. this.label.include();
  7904. context.includedLabels.delete(this.label.name);
  7905. context.brokenFlow = brokenFlow;
  7906. }
  7907. }
  7908. render(code, options) {
  7909. if (this.label.included) {
  7910. this.label.render(code, options);
  7911. }
  7912. else {
  7913. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  7914. }
  7915. this.body.render(code, options);
  7916. }
  7917. }
  7918. class LogicalExpression extends NodeBase {
  7919. constructor() {
  7920. super(...arguments);
  7921. // We collect deoptimization information if usedBranch !== null
  7922. this.expressionsToBeDeoptimized = [];
  7923. this.isBranchResolutionAnalysed = false;
  7924. this.usedBranch = null;
  7925. }
  7926. deoptimizeCache() {
  7927. if (this.usedBranch !== null) {
  7928. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  7929. this.usedBranch = null;
  7930. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7931. for (const expression of this.expressionsToBeDeoptimized) {
  7932. expression.deoptimizeCache();
  7933. }
  7934. }
  7935. }
  7936. deoptimizePath(path) {
  7937. const usedBranch = this.getUsedBranch();
  7938. if (usedBranch === null) {
  7939. this.left.deoptimizePath(path);
  7940. this.right.deoptimizePath(path);
  7941. }
  7942. else {
  7943. usedBranch.deoptimizePath(path);
  7944. }
  7945. }
  7946. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  7947. this.left.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  7948. this.right.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  7949. }
  7950. getLiteralValueAtPath(path, recursionTracker, origin) {
  7951. const usedBranch = this.getUsedBranch();
  7952. if (usedBranch === null)
  7953. return UnknownValue;
  7954. this.expressionsToBeDeoptimized.push(origin);
  7955. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7956. }
  7957. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  7958. const usedBranch = this.getUsedBranch();
  7959. if (usedBranch === null)
  7960. return new MultiExpression([
  7961. this.left.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin),
  7962. this.right.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
  7963. ]);
  7964. this.expressionsToBeDeoptimized.push(origin);
  7965. return usedBranch.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  7966. }
  7967. hasEffects(context) {
  7968. if (this.left.hasEffects(context)) {
  7969. return true;
  7970. }
  7971. if (this.getUsedBranch() !== this.left) {
  7972. return this.right.hasEffects(context);
  7973. }
  7974. return false;
  7975. }
  7976. hasEffectsWhenAccessedAtPath(path, context) {
  7977. const usedBranch = this.getUsedBranch();
  7978. if (usedBranch === null) {
  7979. return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
  7980. this.right.hasEffectsWhenAccessedAtPath(path, context));
  7981. }
  7982. return usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7983. }
  7984. hasEffectsWhenAssignedAtPath(path, context) {
  7985. const usedBranch = this.getUsedBranch();
  7986. if (usedBranch === null) {
  7987. return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
  7988. this.right.hasEffectsWhenAssignedAtPath(path, context));
  7989. }
  7990. return usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7991. }
  7992. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7993. const usedBranch = this.getUsedBranch();
  7994. if (usedBranch === null) {
  7995. return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7996. this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7997. }
  7998. return usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7999. }
  8000. include(context, includeChildrenRecursively) {
  8001. this.included = true;
  8002. const usedBranch = this.getUsedBranch();
  8003. if (includeChildrenRecursively ||
  8004. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  8005. usedBranch === null) {
  8006. this.left.include(context, includeChildrenRecursively);
  8007. this.right.include(context, includeChildrenRecursively);
  8008. }
  8009. else {
  8010. usedBranch.include(context, includeChildrenRecursively);
  8011. }
  8012. }
  8013. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8014. if (!this.left.included || !this.right.included) {
  8015. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  8016. if (this.right.included) {
  8017. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  8018. code.remove(this.start, removePos);
  8019. if (preventASI) {
  8020. removeLineBreaks(code, removePos, this.right.start);
  8021. }
  8022. }
  8023. else {
  8024. code.remove(operatorPos, this.end);
  8025. }
  8026. removeAnnotations(this, code);
  8027. this.getUsedBranch().render(code, options, {
  8028. isCalleeOfRenderedParent,
  8029. preventASI,
  8030. renderedParentType: renderedParentType || this.parent.type,
  8031. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8032. });
  8033. }
  8034. else {
  8035. this.left.render(code, options, {
  8036. preventASI,
  8037. renderedSurroundingElement
  8038. });
  8039. this.right.render(code, options);
  8040. }
  8041. }
  8042. getUsedBranch() {
  8043. if (!this.isBranchResolutionAnalysed) {
  8044. this.isBranchResolutionAnalysed = true;
  8045. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8046. if (leftValue === UnknownValue) {
  8047. return null;
  8048. }
  8049. else {
  8050. this.usedBranch =
  8051. (this.operator === '||' && leftValue) ||
  8052. (this.operator === '&&' && !leftValue) ||
  8053. (this.operator === '??' && leftValue != null)
  8054. ? this.left
  8055. : this.right;
  8056. }
  8057. }
  8058. return this.usedBranch;
  8059. }
  8060. }
  8061. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  8062. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  8063. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  8064. class MetaProperty extends NodeBase {
  8065. addAccessedGlobals(format, accessedGlobalsByScope) {
  8066. const metaProperty = this.metaProperty;
  8067. const accessedGlobals = (metaProperty &&
  8068. (metaProperty.startsWith(FILE_PREFIX) ||
  8069. metaProperty.startsWith(ASSET_PREFIX) ||
  8070. metaProperty.startsWith(CHUNK_PREFIX))
  8071. ? accessedFileUrlGlobals
  8072. : accessedMetaUrlGlobals)[format];
  8073. if (accessedGlobals.length > 0) {
  8074. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  8075. }
  8076. }
  8077. getReferencedFileName(outputPluginDriver) {
  8078. const metaProperty = this.metaProperty;
  8079. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  8080. return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
  8081. }
  8082. return null;
  8083. }
  8084. hasEffects() {
  8085. return false;
  8086. }
  8087. hasEffectsWhenAccessedAtPath(path) {
  8088. return path.length > 1;
  8089. }
  8090. include() {
  8091. if (!this.included) {
  8092. this.included = true;
  8093. if (this.meta.name === 'import') {
  8094. this.context.addImportMeta(this);
  8095. const parent = this.parent;
  8096. this.metaProperty =
  8097. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  8098. ? parent.propertyKey
  8099. : null;
  8100. }
  8101. }
  8102. }
  8103. renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
  8104. var _a;
  8105. const parent = this.parent;
  8106. const metaProperty = this.metaProperty;
  8107. if (metaProperty &&
  8108. (metaProperty.startsWith(FILE_PREFIX) ||
  8109. metaProperty.startsWith(ASSET_PREFIX) ||
  8110. metaProperty.startsWith(CHUNK_PREFIX))) {
  8111. let referenceId = null;
  8112. let assetReferenceId = null;
  8113. let chunkReferenceId = null;
  8114. let fileName;
  8115. if (metaProperty.startsWith(FILE_PREFIX)) {
  8116. referenceId = metaProperty.substr(FILE_PREFIX.length);
  8117. fileName = outputPluginDriver.getFileName(referenceId);
  8118. }
  8119. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  8120. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  8121. assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
  8122. fileName = outputPluginDriver.getFileName(assetReferenceId);
  8123. }
  8124. else {
  8125. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  8126. chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
  8127. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  8128. }
  8129. const relativePath = normalize(path.relative(path.dirname(chunkId), fileName));
  8130. let replacement;
  8131. if (assetReferenceId !== null) {
  8132. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  8133. {
  8134. assetFileName: fileName,
  8135. chunkId,
  8136. format,
  8137. moduleId: this.context.module.id,
  8138. relativeAssetPath: relativePath
  8139. }
  8140. ]);
  8141. }
  8142. if (!replacement) {
  8143. replacement =
  8144. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  8145. {
  8146. assetReferenceId,
  8147. chunkId,
  8148. chunkReferenceId,
  8149. fileName,
  8150. format,
  8151. moduleId: this.context.module.id,
  8152. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  8153. relativePath
  8154. }
  8155. ]) || relativeUrlMechanisms[format](relativePath);
  8156. }
  8157. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8158. return;
  8159. }
  8160. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  8161. metaProperty,
  8162. {
  8163. chunkId,
  8164. format,
  8165. moduleId: this.context.module.id
  8166. }
  8167. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
  8168. if (typeof replacement === 'string') {
  8169. if (parent instanceof MemberExpression) {
  8170. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8171. }
  8172. else {
  8173. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  8174. }
  8175. }
  8176. }
  8177. }
  8178. const accessedMetaUrlGlobals = {
  8179. amd: ['document', 'module', 'URL'],
  8180. cjs: ['document', 'require', 'URL'],
  8181. es: [],
  8182. iife: ['document', 'URL'],
  8183. system: ['module'],
  8184. umd: ['document', 'require', 'URL']
  8185. };
  8186. const accessedFileUrlGlobals = {
  8187. amd: ['document', 'require', 'URL'],
  8188. cjs: ['document', 'require', 'URL'],
  8189. es: [],
  8190. iife: ['document', 'URL'],
  8191. system: ['module', 'URL'],
  8192. umd: ['document', 'require', 'URL']
  8193. };
  8194. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  8195. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  8196. const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
  8197. const urlMechanism = getUrl(chunkId);
  8198. return prop === null
  8199. ? `({ url: ${urlMechanism} })`
  8200. : prop === 'url'
  8201. ? urlMechanism
  8202. : 'undefined';
  8203. };
  8204. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  8205. const relativeUrlMechanisms = {
  8206. amd: relativePath => {
  8207. if (relativePath[0] !== '.')
  8208. relativePath = './' + relativePath;
  8209. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  8210. },
  8211. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  8212. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  8213. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  8214. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  8215. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  8216. };
  8217. const importMetaMechanisms = {
  8218. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  8219. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  8220. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  8221. system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
  8222. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  8223. };
  8224. class NewExpression extends NodeBase {
  8225. constructor() {
  8226. super(...arguments);
  8227. this.deoptimized = false;
  8228. }
  8229. hasEffects(context) {
  8230. if (!this.deoptimized)
  8231. this.applyDeoptimizations();
  8232. for (const argument of this.arguments) {
  8233. if (argument.hasEffects(context))
  8234. return true;
  8235. }
  8236. if (this.context.options.treeshake.annotations &&
  8237. this.annotations)
  8238. return false;
  8239. return (this.callee.hasEffects(context) ||
  8240. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8241. }
  8242. hasEffectsWhenAccessedAtPath(path) {
  8243. return path.length > 0;
  8244. }
  8245. initialise() {
  8246. this.callOptions = {
  8247. args: this.arguments,
  8248. thisParam: null,
  8249. withNew: true
  8250. };
  8251. }
  8252. applyDeoptimizations() {
  8253. this.deoptimized = true;
  8254. for (const argument of this.arguments) {
  8255. // This will make sure all properties of parameters behave as "unknown"
  8256. argument.deoptimizePath(UNKNOWN_PATH);
  8257. }
  8258. this.context.requestTreeshakingPass();
  8259. }
  8260. }
  8261. class ObjectExpression extends NodeBase {
  8262. constructor() {
  8263. super(...arguments);
  8264. this.objectEntity = null;
  8265. }
  8266. deoptimizeCache() {
  8267. this.getObjectEntity().deoptimizeAllProperties();
  8268. }
  8269. deoptimizePath(path) {
  8270. this.getObjectEntity().deoptimizePath(path);
  8271. }
  8272. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8273. this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  8274. }
  8275. getLiteralValueAtPath(path, recursionTracker, origin) {
  8276. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8277. }
  8278. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  8279. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  8280. }
  8281. hasEffectsWhenAccessedAtPath(path, context) {
  8282. return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
  8283. }
  8284. hasEffectsWhenAssignedAtPath(path, context) {
  8285. return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
  8286. }
  8287. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8288. return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
  8289. }
  8290. render(code, options, { renderedSurroundingElement } = BLANK) {
  8291. super.render(code, options);
  8292. if (renderedSurroundingElement === ExpressionStatement$1 ||
  8293. renderedSurroundingElement === ArrowFunctionExpression$1) {
  8294. code.appendRight(this.start, '(');
  8295. code.prependLeft(this.end, ')');
  8296. }
  8297. }
  8298. getObjectEntity() {
  8299. if (this.objectEntity !== null) {
  8300. return this.objectEntity;
  8301. }
  8302. let prototype = OBJECT_PROTOTYPE;
  8303. const properties = [];
  8304. for (const property of this.properties) {
  8305. if (property instanceof SpreadElement) {
  8306. properties.push({ key: UnknownKey, kind: 'init', property });
  8307. continue;
  8308. }
  8309. let key;
  8310. if (property.computed) {
  8311. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8312. if (keyValue === UnknownValue) {
  8313. properties.push({ key: UnknownKey, kind: property.kind, property });
  8314. continue;
  8315. }
  8316. else {
  8317. key = String(keyValue);
  8318. }
  8319. }
  8320. else {
  8321. key =
  8322. property.key instanceof Identifier
  8323. ? property.key.name
  8324. : String(property.key.value);
  8325. if (key === '__proto__' && property.kind === 'init') {
  8326. prototype =
  8327. property.value instanceof Literal && property.value.value === null
  8328. ? null
  8329. : property.value;
  8330. continue;
  8331. }
  8332. }
  8333. properties.push({ key, kind: property.kind, property });
  8334. }
  8335. return (this.objectEntity = new ObjectEntity(properties, prototype));
  8336. }
  8337. }
  8338. class PrivateIdentifier extends NodeBase {
  8339. }
  8340. class Property extends MethodBase {
  8341. constructor() {
  8342. super(...arguments);
  8343. this.deoptimized = false;
  8344. this.declarationInit = null;
  8345. }
  8346. declare(kind, init) {
  8347. this.declarationInit = init;
  8348. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  8349. }
  8350. hasEffects(context) {
  8351. if (!this.deoptimized)
  8352. this.applyDeoptimizations();
  8353. const propertyReadSideEffects = this.context.options.treeshake
  8354. .propertyReadSideEffects;
  8355. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  8356. this.key.hasEffects(context) ||
  8357. this.value.hasEffects(context));
  8358. }
  8359. markDeclarationReached() {
  8360. this.value.markDeclarationReached();
  8361. }
  8362. render(code, options) {
  8363. if (!this.shorthand) {
  8364. this.key.render(code, options);
  8365. }
  8366. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  8367. }
  8368. applyDeoptimizations() {
  8369. this.deoptimized = true;
  8370. if (this.declarationInit !== null) {
  8371. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8372. this.context.requestTreeshakingPass();
  8373. }
  8374. }
  8375. }
  8376. class PropertyDefinition extends NodeBase {
  8377. deoptimizePath(path) {
  8378. var _a;
  8379. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  8380. }
  8381. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8382. var _a;
  8383. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  8384. }
  8385. getLiteralValueAtPath(path, recursionTracker, origin) {
  8386. return this.value
  8387. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  8388. : UnknownValue;
  8389. }
  8390. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  8391. return this.value
  8392. ? this.value.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
  8393. : UNKNOWN_EXPRESSION;
  8394. }
  8395. hasEffects(context) {
  8396. return (this.key.hasEffects(context) ||
  8397. (this.static && this.value !== null && this.value.hasEffects(context)));
  8398. }
  8399. hasEffectsWhenAccessedAtPath(path, context) {
  8400. return !this.value || this.value.hasEffectsWhenAccessedAtPath(path, context);
  8401. }
  8402. hasEffectsWhenAssignedAtPath(path, context) {
  8403. return !this.value || this.value.hasEffectsWhenAssignedAtPath(path, context);
  8404. }
  8405. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8406. return !this.value || this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8407. }
  8408. }
  8409. class ReturnStatement extends NodeBase {
  8410. hasEffects(context) {
  8411. if (!context.ignore.returnYield ||
  8412. (this.argument !== null && this.argument.hasEffects(context)))
  8413. return true;
  8414. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8415. return false;
  8416. }
  8417. include(context, includeChildrenRecursively) {
  8418. this.included = true;
  8419. if (this.argument) {
  8420. this.argument.include(context, includeChildrenRecursively);
  8421. }
  8422. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8423. }
  8424. initialise() {
  8425. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  8426. }
  8427. render(code, options) {
  8428. if (this.argument) {
  8429. this.argument.render(code, options, { preventASI: true });
  8430. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  8431. code.prependLeft(this.start + 6, ' ');
  8432. }
  8433. }
  8434. }
  8435. }
  8436. class SequenceExpression extends NodeBase {
  8437. deoptimizePath(path) {
  8438. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  8439. }
  8440. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8441. this.expressions[this.expressions.length - 1].deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  8442. }
  8443. getLiteralValueAtPath(path, recursionTracker, origin) {
  8444. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  8445. }
  8446. hasEffects(context) {
  8447. for (const expression of this.expressions) {
  8448. if (expression.hasEffects(context))
  8449. return true;
  8450. }
  8451. return false;
  8452. }
  8453. hasEffectsWhenAccessedAtPath(path, context) {
  8454. return (path.length > 0 &&
  8455. this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
  8456. }
  8457. hasEffectsWhenAssignedAtPath(path, context) {
  8458. return this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context);
  8459. }
  8460. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8461. return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
  8462. }
  8463. include(context, includeChildrenRecursively) {
  8464. this.included = true;
  8465. const lastExpression = this.expressions[this.expressions.length - 1];
  8466. for (const expression of this.expressions) {
  8467. if (includeChildrenRecursively ||
  8468. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  8469. expression.shouldBeIncluded(context))
  8470. expression.include(context, includeChildrenRecursively);
  8471. }
  8472. }
  8473. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  8474. let includedNodes = 0;
  8475. let lastSeparatorPos = null;
  8476. const lastNode = this.expressions[this.expressions.length - 1];
  8477. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  8478. if (!node.included) {
  8479. treeshakeNode(node, code, start, end);
  8480. continue;
  8481. }
  8482. includedNodes++;
  8483. lastSeparatorPos = separator;
  8484. if (includedNodes === 1 && preventASI) {
  8485. removeLineBreaks(code, start, node.start);
  8486. }
  8487. if (includedNodes === 1) {
  8488. const parentType = renderedParentType || this.parent.type;
  8489. node.render(code, options, {
  8490. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  8491. renderedParentType: parentType,
  8492. renderedSurroundingElement: parentType
  8493. });
  8494. }
  8495. else {
  8496. node.render(code, options);
  8497. }
  8498. }
  8499. if (lastSeparatorPos) {
  8500. code.remove(lastSeparatorPos, this.end);
  8501. }
  8502. }
  8503. }
  8504. class Super extends NodeBase {
  8505. bind() {
  8506. this.variable = this.scope.findVariable('this');
  8507. }
  8508. deoptimizePath(path) {
  8509. this.variable.deoptimizePath(path);
  8510. }
  8511. include() {
  8512. if (!this.included) {
  8513. this.included = true;
  8514. this.context.includeVariableInModule(this.variable);
  8515. }
  8516. }
  8517. }
  8518. class SwitchCase extends NodeBase {
  8519. hasEffects(context) {
  8520. if (this.test && this.test.hasEffects(context))
  8521. return true;
  8522. for (const node of this.consequent) {
  8523. if (context.brokenFlow)
  8524. break;
  8525. if (node.hasEffects(context))
  8526. return true;
  8527. }
  8528. return false;
  8529. }
  8530. include(context, includeChildrenRecursively) {
  8531. this.included = true;
  8532. if (this.test)
  8533. this.test.include(context, includeChildrenRecursively);
  8534. for (const node of this.consequent) {
  8535. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8536. node.include(context, includeChildrenRecursively);
  8537. }
  8538. }
  8539. render(code, options, nodeRenderOptions) {
  8540. if (this.consequent.length) {
  8541. this.test && this.test.render(code, options);
  8542. const testEnd = this.test
  8543. ? this.test.end
  8544. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  8545. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  8546. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  8547. }
  8548. else {
  8549. super.render(code, options);
  8550. }
  8551. }
  8552. }
  8553. SwitchCase.prototype.needsBoundaries = true;
  8554. class SwitchStatement extends NodeBase {
  8555. createScope(parentScope) {
  8556. this.scope = new BlockScope(parentScope);
  8557. }
  8558. hasEffects(context) {
  8559. if (this.discriminant.hasEffects(context))
  8560. return true;
  8561. const { brokenFlow, ignore: { breaks } } = context;
  8562. let minBrokenFlow = Infinity;
  8563. context.ignore.breaks = true;
  8564. for (const switchCase of this.cases) {
  8565. if (switchCase.hasEffects(context))
  8566. return true;
  8567. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  8568. context.brokenFlow = brokenFlow;
  8569. }
  8570. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8571. context.brokenFlow = minBrokenFlow;
  8572. }
  8573. context.ignore.breaks = breaks;
  8574. return false;
  8575. }
  8576. include(context, includeChildrenRecursively) {
  8577. this.included = true;
  8578. this.discriminant.include(context, includeChildrenRecursively);
  8579. const { brokenFlow } = context;
  8580. let minBrokenFlow = Infinity;
  8581. let isCaseIncluded = includeChildrenRecursively ||
  8582. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  8583. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  8584. const switchCase = this.cases[caseIndex];
  8585. if (switchCase.included) {
  8586. isCaseIncluded = true;
  8587. }
  8588. if (!isCaseIncluded) {
  8589. const hasEffectsContext = createHasEffectsContext();
  8590. hasEffectsContext.ignore.breaks = true;
  8591. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  8592. }
  8593. if (isCaseIncluded) {
  8594. switchCase.include(context, includeChildrenRecursively);
  8595. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  8596. context.brokenFlow = brokenFlow;
  8597. }
  8598. else {
  8599. minBrokenFlow = brokenFlow;
  8600. }
  8601. }
  8602. if (isCaseIncluded &&
  8603. this.defaultCase !== null &&
  8604. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8605. context.brokenFlow = minBrokenFlow;
  8606. }
  8607. }
  8608. initialise() {
  8609. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  8610. if (this.cases[caseIndex].test === null) {
  8611. this.defaultCase = caseIndex;
  8612. return;
  8613. }
  8614. }
  8615. this.defaultCase = null;
  8616. }
  8617. render(code, options) {
  8618. this.discriminant.render(code, options);
  8619. if (this.cases.length > 0) {
  8620. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  8621. }
  8622. }
  8623. }
  8624. class TaggedTemplateExpression extends NodeBase {
  8625. bind() {
  8626. super.bind();
  8627. if (this.tag.type === Identifier$1) {
  8628. const name = this.tag.name;
  8629. const variable = this.scope.findVariable(name);
  8630. if (variable.isNamespace) {
  8631. this.context.warn({
  8632. code: 'CANNOT_CALL_NAMESPACE',
  8633. message: `Cannot call a namespace ('${name}')`
  8634. }, this.start);
  8635. }
  8636. }
  8637. }
  8638. hasEffects(context) {
  8639. return (super.hasEffects(context) ||
  8640. this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8641. }
  8642. initialise() {
  8643. this.callOptions = {
  8644. args: NO_ARGS,
  8645. thisParam: null,
  8646. withNew: false
  8647. };
  8648. }
  8649. render(code, options) {
  8650. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  8651. this.quasi.render(code, options);
  8652. }
  8653. }
  8654. class TemplateElement extends NodeBase {
  8655. // Do not try to bind value
  8656. bind() { }
  8657. hasEffects() {
  8658. return false;
  8659. }
  8660. include() {
  8661. this.included = true;
  8662. }
  8663. parseNode(esTreeNode) {
  8664. this.value = esTreeNode.value;
  8665. super.parseNode(esTreeNode);
  8666. }
  8667. render() { }
  8668. }
  8669. class UndefinedVariable extends Variable {
  8670. constructor() {
  8671. super('undefined');
  8672. }
  8673. getLiteralValueAtPath() {
  8674. return undefined;
  8675. }
  8676. }
  8677. class ExportDefaultVariable extends LocalVariable {
  8678. constructor(name, exportDefaultDeclaration, context) {
  8679. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  8680. this.hasId = false;
  8681. this.originalId = null;
  8682. this.originalVariable = null;
  8683. const declaration = exportDefaultDeclaration.declaration;
  8684. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  8685. declaration.id) {
  8686. this.hasId = true;
  8687. this.originalId = declaration.id;
  8688. }
  8689. else if (declaration instanceof Identifier) {
  8690. this.originalId = declaration;
  8691. }
  8692. }
  8693. addReference(identifier) {
  8694. if (!this.hasId) {
  8695. this.name = identifier.name;
  8696. }
  8697. }
  8698. getAssignedVariableName() {
  8699. return (this.originalId && this.originalId.name) || null;
  8700. }
  8701. getBaseVariableName() {
  8702. const original = this.getOriginalVariable();
  8703. if (original === this) {
  8704. return super.getBaseVariableName();
  8705. }
  8706. else {
  8707. return original.getBaseVariableName();
  8708. }
  8709. }
  8710. getDirectOriginalVariable() {
  8711. return this.originalId &&
  8712. (this.hasId ||
  8713. !(this.originalId.isPossibleTDZ() ||
  8714. this.originalId.variable.isReassigned ||
  8715. this.originalId.variable instanceof UndefinedVariable ||
  8716. // this avoids a circular dependency
  8717. 'syntheticNamespace' in this.originalId.variable))
  8718. ? this.originalId.variable
  8719. : null;
  8720. }
  8721. getName() {
  8722. const original = this.getOriginalVariable();
  8723. if (original === this) {
  8724. return super.getName();
  8725. }
  8726. else {
  8727. return original.getName();
  8728. }
  8729. }
  8730. getOriginalVariable() {
  8731. if (this.originalVariable)
  8732. return this.originalVariable;
  8733. // eslint-disable-next-line @typescript-eslint/no-this-alias
  8734. let original = this;
  8735. let currentVariable;
  8736. const checkedVariables = new Set();
  8737. do {
  8738. checkedVariables.add(original);
  8739. currentVariable = original;
  8740. original = currentVariable.getDirectOriginalVariable();
  8741. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  8742. return (this.originalVariable = original || currentVariable);
  8743. }
  8744. }
  8745. class ModuleScope extends ChildScope {
  8746. constructor(parent, context) {
  8747. super(parent);
  8748. this.context = context;
  8749. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  8750. }
  8751. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  8752. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  8753. this.variables.set('default', variable);
  8754. return variable;
  8755. }
  8756. addNamespaceMemberAccess() { }
  8757. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8758. // all module level variables are already deconflicted when deconflicting the chunk
  8759. for (const scope of this.children)
  8760. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8761. }
  8762. findLexicalBoundary() {
  8763. return this;
  8764. }
  8765. findVariable(name) {
  8766. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8767. if (knownVariable) {
  8768. return knownVariable;
  8769. }
  8770. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  8771. if (variable instanceof GlobalVariable) {
  8772. this.accessedOutsideVariables.set(name, variable);
  8773. }
  8774. return variable;
  8775. }
  8776. }
  8777. class ThisExpression extends NodeBase {
  8778. bind() {
  8779. this.variable = this.scope.findVariable('this');
  8780. }
  8781. deoptimizePath(path) {
  8782. this.variable.deoptimizePath(path);
  8783. }
  8784. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8785. this.variable.deoptimizeThisOnEventAtPath(event, path,
  8786. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  8787. thisParameter === this ? this.variable : thisParameter, recursionTracker);
  8788. }
  8789. hasEffectsWhenAccessedAtPath(path, context) {
  8790. return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  8791. }
  8792. hasEffectsWhenAssignedAtPath(path, context) {
  8793. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  8794. }
  8795. include() {
  8796. if (!this.included) {
  8797. this.included = true;
  8798. this.context.includeVariableInModule(this.variable);
  8799. }
  8800. }
  8801. initialise() {
  8802. this.alias =
  8803. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  8804. if (this.alias === 'undefined') {
  8805. this.context.warn({
  8806. code: 'THIS_IS_UNDEFINED',
  8807. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  8808. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  8809. }, this.start);
  8810. }
  8811. }
  8812. render(code) {
  8813. if (this.alias !== null) {
  8814. code.overwrite(this.start, this.end, this.alias, {
  8815. contentOnly: false,
  8816. storeName: true
  8817. });
  8818. }
  8819. }
  8820. }
  8821. class ThrowStatement extends NodeBase {
  8822. hasEffects() {
  8823. return true;
  8824. }
  8825. include(context, includeChildrenRecursively) {
  8826. this.included = true;
  8827. this.argument.include(context, includeChildrenRecursively);
  8828. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8829. }
  8830. render(code, options) {
  8831. this.argument.render(code, options, { preventASI: true });
  8832. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  8833. code.prependLeft(this.start + 5, ' ');
  8834. }
  8835. }
  8836. }
  8837. class TryStatement extends NodeBase {
  8838. constructor() {
  8839. super(...arguments);
  8840. this.directlyIncluded = false;
  8841. this.includedLabelsAfterBlock = null;
  8842. }
  8843. hasEffects(context) {
  8844. return ((this.context.options.treeshake.tryCatchDeoptimization
  8845. ? this.block.body.length > 0
  8846. : this.block.hasEffects(context)) ||
  8847. (this.finalizer !== null && this.finalizer.hasEffects(context)));
  8848. }
  8849. include(context, includeChildrenRecursively) {
  8850. var _a;
  8851. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  8852. const { brokenFlow } = context;
  8853. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  8854. this.included = true;
  8855. this.directlyIncluded = true;
  8856. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  8857. if (context.includedLabels.size > 0) {
  8858. this.includedLabelsAfterBlock = [...context.includedLabels];
  8859. }
  8860. context.brokenFlow = brokenFlow;
  8861. }
  8862. else if (this.includedLabelsAfterBlock) {
  8863. for (const label of this.includedLabelsAfterBlock) {
  8864. context.includedLabels.add(label);
  8865. }
  8866. }
  8867. if (this.handler !== null) {
  8868. this.handler.include(context, includeChildrenRecursively);
  8869. context.brokenFlow = brokenFlow;
  8870. }
  8871. if (this.finalizer !== null) {
  8872. this.finalizer.include(context, includeChildrenRecursively);
  8873. }
  8874. }
  8875. }
  8876. const unaryOperators = {
  8877. '!': value => !value,
  8878. '+': value => +value,
  8879. '-': value => -value,
  8880. delete: () => UnknownValue,
  8881. typeof: value => typeof value,
  8882. void: () => undefined,
  8883. '~': value => ~value
  8884. };
  8885. class UnaryExpression extends NodeBase {
  8886. constructor() {
  8887. super(...arguments);
  8888. this.deoptimized = false;
  8889. }
  8890. getLiteralValueAtPath(path, recursionTracker, origin) {
  8891. if (path.length > 0)
  8892. return UnknownValue;
  8893. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8894. if (argumentValue === UnknownValue)
  8895. return UnknownValue;
  8896. return unaryOperators[this.operator](argumentValue);
  8897. }
  8898. hasEffects(context) {
  8899. if (!this.deoptimized)
  8900. this.applyDeoptimizations();
  8901. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  8902. return false;
  8903. return (this.argument.hasEffects(context) ||
  8904. (this.operator === 'delete' &&
  8905. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
  8906. }
  8907. hasEffectsWhenAccessedAtPath(path) {
  8908. if (this.operator === 'void') {
  8909. return path.length > 0;
  8910. }
  8911. return path.length > 1;
  8912. }
  8913. applyDeoptimizations() {
  8914. this.deoptimized = true;
  8915. if (this.operator === 'delete') {
  8916. this.argument.deoptimizePath(EMPTY_PATH);
  8917. this.context.requestTreeshakingPass();
  8918. }
  8919. }
  8920. }
  8921. class UnknownNode extends NodeBase {
  8922. hasEffects() {
  8923. return true;
  8924. }
  8925. include(context) {
  8926. super.include(context, true);
  8927. }
  8928. }
  8929. class UpdateExpression extends NodeBase {
  8930. constructor() {
  8931. super(...arguments);
  8932. this.deoptimized = false;
  8933. }
  8934. hasEffects(context) {
  8935. if (!this.deoptimized)
  8936. this.applyDeoptimizations();
  8937. return (this.argument.hasEffects(context) ||
  8938. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  8939. }
  8940. hasEffectsWhenAccessedAtPath(path) {
  8941. return path.length > 1;
  8942. }
  8943. render(code, options) {
  8944. this.argument.render(code, options);
  8945. if (options.format === 'system') {
  8946. const variable = this.argument.variable;
  8947. const exportNames = options.exportNamesByVariable.get(variable);
  8948. if (exportNames) {
  8949. const _ = options.compact ? '' : ' ';
  8950. if (this.prefix) {
  8951. if (exportNames.length === 1) {
  8952. renderSystemExportExpression(variable, this.start, this.end, code, options);
  8953. }
  8954. else {
  8955. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  8956. }
  8957. }
  8958. else {
  8959. const operator = this.operator[0];
  8960. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  8961. }
  8962. }
  8963. }
  8964. }
  8965. applyDeoptimizations() {
  8966. this.deoptimized = true;
  8967. this.argument.deoptimizePath(EMPTY_PATH);
  8968. if (this.argument instanceof Identifier) {
  8969. const variable = this.scope.findVariable(this.argument.name);
  8970. variable.isReassigned = true;
  8971. }
  8972. this.context.requestTreeshakingPass();
  8973. }
  8974. }
  8975. class VariableDeclarator extends NodeBase {
  8976. declareDeclarator(kind) {
  8977. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  8978. }
  8979. deoptimizePath(path) {
  8980. this.id.deoptimizePath(path);
  8981. }
  8982. hasEffects(context) {
  8983. const initEffect = this.init !== null && this.init.hasEffects(context);
  8984. this.id.markDeclarationReached();
  8985. return initEffect || this.id.hasEffects(context);
  8986. }
  8987. include(context, includeChildrenRecursively) {
  8988. this.included = true;
  8989. if (this.init) {
  8990. this.init.include(context, includeChildrenRecursively);
  8991. }
  8992. this.id.markDeclarationReached();
  8993. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  8994. this.id.include(context, includeChildrenRecursively);
  8995. }
  8996. }
  8997. render(code, options) {
  8998. const renderId = this.id.included;
  8999. if (renderId) {
  9000. this.id.render(code, options);
  9001. }
  9002. else {
  9003. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  9004. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  9005. }
  9006. if (this.init) {
  9007. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  9008. }
  9009. else if (this.id instanceof Identifier &&
  9010. isReassignedExportsMember(this.id.variable, options.exportNamesByVariable)) {
  9011. const _ = options.compact ? '' : ' ';
  9012. code.appendLeft(this.end, `${_}=${_}void 0`);
  9013. }
  9014. }
  9015. }
  9016. class WhileStatement extends NodeBase {
  9017. hasEffects(context) {
  9018. if (this.test.hasEffects(context))
  9019. return true;
  9020. const { brokenFlow, ignore: { breaks, continues } } = context;
  9021. context.ignore.breaks = true;
  9022. context.ignore.continues = true;
  9023. if (this.body.hasEffects(context))
  9024. return true;
  9025. context.ignore.breaks = breaks;
  9026. context.ignore.continues = continues;
  9027. context.brokenFlow = brokenFlow;
  9028. return false;
  9029. }
  9030. include(context, includeChildrenRecursively) {
  9031. this.included = true;
  9032. this.test.include(context, includeChildrenRecursively);
  9033. const { brokenFlow } = context;
  9034. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  9035. context.brokenFlow = brokenFlow;
  9036. }
  9037. }
  9038. class YieldExpression extends NodeBase {
  9039. constructor() {
  9040. super(...arguments);
  9041. this.deoptimized = false;
  9042. }
  9043. hasEffects(context) {
  9044. if (!this.deoptimized)
  9045. this.applyDeoptimizations();
  9046. return (!context.ignore.returnYield || (this.argument !== null && this.argument.hasEffects(context)));
  9047. }
  9048. render(code, options) {
  9049. if (this.argument) {
  9050. this.argument.render(code, options, { preventASI: true });
  9051. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  9052. code.prependLeft(this.start + 5, ' ');
  9053. }
  9054. }
  9055. }
  9056. applyDeoptimizations() {
  9057. this.deoptimized = true;
  9058. const { argument } = this;
  9059. if (argument) {
  9060. argument.deoptimizePath(UNKNOWN_PATH);
  9061. this.context.requestTreeshakingPass();
  9062. }
  9063. }
  9064. }
  9065. const nodeConstructors = {
  9066. ArrayExpression,
  9067. ArrayPattern,
  9068. ArrowFunctionExpression,
  9069. AssignmentExpression,
  9070. AssignmentPattern,
  9071. AwaitExpression,
  9072. BinaryExpression,
  9073. BlockStatement,
  9074. BreakStatement,
  9075. CallExpression,
  9076. CatchClause,
  9077. ChainExpression,
  9078. ClassBody,
  9079. ClassDeclaration,
  9080. ClassExpression,
  9081. ConditionalExpression,
  9082. ContinueStatement,
  9083. DoWhileStatement,
  9084. EmptyStatement,
  9085. ExportAllDeclaration,
  9086. ExportDefaultDeclaration,
  9087. ExportNamedDeclaration,
  9088. ExportSpecifier,
  9089. ExpressionStatement,
  9090. ForInStatement,
  9091. ForOfStatement,
  9092. ForStatement,
  9093. FunctionDeclaration,
  9094. FunctionExpression,
  9095. Identifier,
  9096. IfStatement,
  9097. ImportDeclaration,
  9098. ImportDefaultSpecifier,
  9099. ImportExpression,
  9100. ImportNamespaceSpecifier,
  9101. ImportSpecifier,
  9102. LabeledStatement,
  9103. Literal,
  9104. LogicalExpression,
  9105. MemberExpression,
  9106. MetaProperty,
  9107. MethodDefinition,
  9108. NewExpression,
  9109. ObjectExpression,
  9110. ObjectPattern,
  9111. PrivateIdentifier,
  9112. Program,
  9113. Property,
  9114. PropertyDefinition,
  9115. RestElement,
  9116. ReturnStatement,
  9117. SequenceExpression,
  9118. SpreadElement,
  9119. Super,
  9120. SwitchCase,
  9121. SwitchStatement,
  9122. TaggedTemplateExpression,
  9123. TemplateElement,
  9124. TemplateLiteral,
  9125. ThisExpression,
  9126. ThrowStatement,
  9127. TryStatement,
  9128. UnaryExpression,
  9129. UnknownNode,
  9130. UpdateExpression,
  9131. VariableDeclaration,
  9132. VariableDeclarator,
  9133. WhileStatement,
  9134. YieldExpression
  9135. };
  9136. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  9137. class ExportShimVariable extends Variable {
  9138. constructor(module) {
  9139. super(MISSING_EXPORT_SHIM_VARIABLE);
  9140. this.module = module;
  9141. }
  9142. }
  9143. class NamespaceVariable extends Variable {
  9144. constructor(context, syntheticNamedExports) {
  9145. super(context.getModuleName());
  9146. this.memberVariables = null;
  9147. this.mergedNamespaces = [];
  9148. this.referencedEarly = false;
  9149. this.references = [];
  9150. this.context = context;
  9151. this.module = context.module;
  9152. this.syntheticNamedExports = syntheticNamedExports;
  9153. }
  9154. addReference(identifier) {
  9155. this.references.push(identifier);
  9156. this.name = identifier.name;
  9157. }
  9158. getMemberVariables() {
  9159. if (this.memberVariables) {
  9160. return this.memberVariables;
  9161. }
  9162. const memberVariables = Object.create(null);
  9163. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  9164. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  9165. const exportedVariable = this.context.traceExport(name);
  9166. if (exportedVariable) {
  9167. memberVariables[name] = exportedVariable;
  9168. }
  9169. }
  9170. }
  9171. return (this.memberVariables = memberVariables);
  9172. }
  9173. include() {
  9174. this.included = true;
  9175. this.context.includeAllExports();
  9176. }
  9177. prepareNamespace(mergedNamespaces) {
  9178. this.mergedNamespaces = mergedNamespaces;
  9179. const moduleExecIndex = this.context.getModuleExecIndex();
  9180. for (const identifier of this.references) {
  9181. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  9182. this.referencedEarly = true;
  9183. break;
  9184. }
  9185. }
  9186. }
  9187. renderBlock(options) {
  9188. const _ = options.compact ? '' : ' ';
  9189. const n = options.compact ? '' : '\n';
  9190. const t = options.indent;
  9191. const memberVariables = this.getMemberVariables();
  9192. const members = Object.entries(memberVariables).map(([name, original]) => {
  9193. if (this.referencedEarly || original.isReassigned) {
  9194. return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
  9195. }
  9196. const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
  9197. return `${t}${safeName}: ${original.getName()}`;
  9198. });
  9199. if (options.namespaceToStringTag) {
  9200. members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
  9201. }
  9202. const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
  9203. if (!needsObjectAssign)
  9204. members.unshift(`${t}__proto__:${_}null`);
  9205. let output = `{${n}${members.join(`,${n}`)}${n}}`;
  9206. if (needsObjectAssign) {
  9207. const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
  9208. if (this.mergedNamespaces.length > 0) {
  9209. assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
  9210. }
  9211. if (this.syntheticNamedExports) {
  9212. assignmentArgs.push(this.module.getSyntheticNamespace().getName());
  9213. }
  9214. if (members.length > 0) {
  9215. assignmentArgs.push(output);
  9216. }
  9217. output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
  9218. }
  9219. if (options.freeze) {
  9220. output = `/*#__PURE__*/Object.freeze(${output})`;
  9221. }
  9222. const name = this.getName();
  9223. output = `${options.varOrConst} ${name}${_}=${_}${output};`;
  9224. if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
  9225. output += `${n}${getSystemExportStatement([this], options)};`;
  9226. }
  9227. return output;
  9228. }
  9229. renderFirst() {
  9230. return this.referencedEarly;
  9231. }
  9232. }
  9233. NamespaceVariable.prototype.isNamespace = true;
  9234. class SyntheticNamedExportVariable extends Variable {
  9235. constructor(context, name, syntheticNamespace) {
  9236. super(name);
  9237. this.baseVariable = null;
  9238. this.context = context;
  9239. this.module = context.module;
  9240. this.syntheticNamespace = syntheticNamespace;
  9241. }
  9242. getBaseVariable() {
  9243. if (this.baseVariable)
  9244. return this.baseVariable;
  9245. let baseVariable = this.syntheticNamespace;
  9246. while (baseVariable instanceof ExportDefaultVariable ||
  9247. baseVariable instanceof SyntheticNamedExportVariable) {
  9248. if (baseVariable instanceof ExportDefaultVariable) {
  9249. const original = baseVariable.getOriginalVariable();
  9250. if (original === baseVariable)
  9251. break;
  9252. baseVariable = original;
  9253. }
  9254. if (baseVariable instanceof SyntheticNamedExportVariable) {
  9255. baseVariable = baseVariable.syntheticNamespace;
  9256. }
  9257. }
  9258. return (this.baseVariable = baseVariable);
  9259. }
  9260. getBaseVariableName() {
  9261. return this.syntheticNamespace.getBaseVariableName();
  9262. }
  9263. getName() {
  9264. const name = this.name;
  9265. return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
  9266. }
  9267. include() {
  9268. if (!this.included) {
  9269. this.included = true;
  9270. this.context.includeVariableInModule(this.syntheticNamespace);
  9271. }
  9272. }
  9273. setRenderNames(baseName, name) {
  9274. super.setRenderNames(baseName, name);
  9275. }
  9276. }
  9277. const getPropertyAccess = (name) => {
  9278. return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
  9279. ? `.${name}`
  9280. : `[${JSON.stringify(name)}]`;
  9281. };
  9282. function getId(m) {
  9283. return m.id;
  9284. }
  9285. function getOriginalLocation(sourcemapChain, location) {
  9286. // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
  9287. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
  9288. while (filteredSourcemapChain.length > 0) {
  9289. const sourcemap = filteredSourcemapChain.pop();
  9290. const line = sourcemap.mappings[location.line - 1];
  9291. let locationFound = false;
  9292. if (line !== undefined) {
  9293. for (const segment of line) {
  9294. if (segment[0] >= location.column) {
  9295. if (segment.length === 1)
  9296. break;
  9297. location = {
  9298. column: segment[3],
  9299. line: segment[2] + 1,
  9300. name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
  9301. source: sourcemap.sources[segment[1]]
  9302. };
  9303. locationFound = true;
  9304. break;
  9305. }
  9306. }
  9307. }
  9308. if (!locationFound) {
  9309. throw new Error("Can't resolve original location of error.");
  9310. }
  9311. }
  9312. return location;
  9313. }
  9314. const NOOP = () => { };
  9315. let getStartTime = () => [0, 0];
  9316. let getElapsedTime = () => 0;
  9317. let getMemory = () => 0;
  9318. let timers = {};
  9319. const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
  9320. function setTimeHelpers() {
  9321. if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
  9322. getStartTime = process.hrtime.bind(process);
  9323. getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
  9324. }
  9325. else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
  9326. getStartTime = () => [performance.now(), 0];
  9327. getElapsedTime = previous => performance.now() - previous[0];
  9328. }
  9329. if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
  9330. getMemory = () => process.memoryUsage().heapUsed;
  9331. }
  9332. }
  9333. function getPersistedLabel(label, level) {
  9334. switch (level) {
  9335. case 1:
  9336. return `# ${label}`;
  9337. case 2:
  9338. return `## ${label}`;
  9339. case 3:
  9340. return label;
  9341. default:
  9342. return `${' '.repeat(level - 4)}- ${label}`;
  9343. }
  9344. }
  9345. function timeStartImpl(label, level = 3) {
  9346. label = getPersistedLabel(label, level);
  9347. if (!timers.hasOwnProperty(label)) {
  9348. timers[label] = {
  9349. memory: 0,
  9350. startMemory: undefined,
  9351. startTime: undefined,
  9352. time: 0,
  9353. totalMemory: 0
  9354. };
  9355. }
  9356. const currentMemory = getMemory();
  9357. timers[label].startTime = getStartTime();
  9358. timers[label].startMemory = currentMemory;
  9359. }
  9360. function timeEndImpl(label, level = 3) {
  9361. label = getPersistedLabel(label, level);
  9362. if (timers.hasOwnProperty(label)) {
  9363. const currentMemory = getMemory();
  9364. timers[label].time += getElapsedTime(timers[label].startTime);
  9365. timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
  9366. timers[label].memory += currentMemory - timers[label].startMemory;
  9367. }
  9368. }
  9369. function getTimings() {
  9370. const newTimings = {};
  9371. for (const [label, { time, memory, totalMemory }] of Object.entries(timers)) {
  9372. newTimings[label] = [time, memory, totalMemory];
  9373. }
  9374. return newTimings;
  9375. }
  9376. let timeStart = NOOP, timeEnd = NOOP;
  9377. const TIMED_PLUGIN_HOOKS = {
  9378. load: true,
  9379. resolveDynamicImport: true,
  9380. resolveId: true,
  9381. transform: true
  9382. };
  9383. function getPluginWithTimers(plugin, index) {
  9384. const timedPlugin = {};
  9385. for (const hook of Object.keys(plugin)) {
  9386. if (TIMED_PLUGIN_HOOKS[hook] === true) {
  9387. let timerLabel = `plugin ${index}`;
  9388. if (plugin.name) {
  9389. timerLabel += ` (${plugin.name})`;
  9390. }
  9391. timerLabel += ` - ${hook}`;
  9392. timedPlugin[hook] = function (...args) {
  9393. timeStart(timerLabel, 4);
  9394. let result = plugin[hook].apply(this === timedPlugin ? plugin : this, args);
  9395. timeEnd(timerLabel, 4);
  9396. if (result && typeof result.then === 'function') {
  9397. timeStart(`${timerLabel} (async)`, 4);
  9398. result = result.then((hookResult) => {
  9399. timeEnd(`${timerLabel} (async)`, 4);
  9400. return hookResult;
  9401. });
  9402. }
  9403. return result;
  9404. };
  9405. }
  9406. else {
  9407. timedPlugin[hook] = plugin[hook];
  9408. }
  9409. }
  9410. return timedPlugin;
  9411. }
  9412. function initialiseTimers(inputOptions) {
  9413. if (inputOptions.perf) {
  9414. timers = {};
  9415. setTimeHelpers();
  9416. timeStart = timeStartImpl;
  9417. timeEnd = timeEndImpl;
  9418. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  9419. }
  9420. else {
  9421. timeStart = NOOP;
  9422. timeEnd = NOOP;
  9423. }
  9424. }
  9425. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  9426. baseModule.isExecuted = true;
  9427. const modules = [baseModule];
  9428. const visitedModules = new Set();
  9429. for (const module of modules) {
  9430. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  9431. if (!(dependency instanceof ExternalModule) &&
  9432. !dependency.isExecuted &&
  9433. (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  9434. !visitedModules.has(dependency.id)) {
  9435. dependency.isExecuted = true;
  9436. visitedModules.add(dependency.id);
  9437. modules.push(dependency);
  9438. }
  9439. }
  9440. }
  9441. }
  9442. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  9443. identifier: null,
  9444. localName: MISSING_EXPORT_SHIM_VARIABLE
  9445. };
  9446. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map(), skipExternalNamespaceReexports) {
  9447. const searchedModules = searchedNamesAndModules.get(name);
  9448. if (searchedModules) {
  9449. if (searchedModules.has(target)) {
  9450. return isExportAllSearch ? null : error(errCircularReexport(name, target.id));
  9451. }
  9452. searchedModules.add(target);
  9453. }
  9454. else {
  9455. searchedNamesAndModules.set(name, new Set([target]));
  9456. }
  9457. return target.getVariableForExportName(name, {
  9458. importerForSideEffects,
  9459. isExportAllSearch,
  9460. searchedNamesAndModules,
  9461. skipExternalNamespaceReexports
  9462. });
  9463. }
  9464. function getAndExtendSideEffectModules(variable, module) {
  9465. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  9466. let currentVariable = variable;
  9467. const referencedVariables = new Set([currentVariable]);
  9468. while (true) {
  9469. const importingModule = currentVariable.module;
  9470. currentVariable =
  9471. currentVariable instanceof ExportDefaultVariable
  9472. ? currentVariable.getDirectOriginalVariable()
  9473. : currentVariable instanceof SyntheticNamedExportVariable
  9474. ? currentVariable.syntheticNamespace
  9475. : null;
  9476. if (!currentVariable || referencedVariables.has(currentVariable)) {
  9477. break;
  9478. }
  9479. referencedVariables.add(currentVariable);
  9480. sideEffectModules.add(importingModule);
  9481. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  9482. if (originalSideEffects) {
  9483. for (const module of originalSideEffects) {
  9484. sideEffectModules.add(module);
  9485. }
  9486. }
  9487. }
  9488. return sideEffectModules;
  9489. }
  9490. class Module {
  9491. constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
  9492. this.graph = graph;
  9493. this.id = id;
  9494. this.options = options;
  9495. this.alternativeReexportModules = new Map();
  9496. this.ast = null;
  9497. this.chunkFileNames = new Set();
  9498. this.chunkName = null;
  9499. this.cycles = new Set();
  9500. this.dependencies = new Set();
  9501. this.dynamicDependencies = new Set();
  9502. this.dynamicImporters = [];
  9503. this.dynamicImports = [];
  9504. this.execIndex = Infinity;
  9505. this.exportAllSources = new Set();
  9506. this.exports = Object.create(null);
  9507. this.exportsAll = Object.create(null);
  9508. this.implicitlyLoadedAfter = new Set();
  9509. this.implicitlyLoadedBefore = new Set();
  9510. this.importDescriptions = Object.create(null);
  9511. this.importMetas = [];
  9512. this.importedFromNotTreeshaken = false;
  9513. this.importers = [];
  9514. this.imports = new Set();
  9515. this.includedDynamicImporters = [];
  9516. this.isExecuted = false;
  9517. this.isUserDefinedEntryPoint = false;
  9518. this.preserveSignature = this.options.preserveEntrySignatures;
  9519. this.reexportDescriptions = Object.create(null);
  9520. this.sideEffectDependenciesByVariable = new Map();
  9521. this.sources = new Set();
  9522. this.userChunkNames = new Set();
  9523. this.usesTopLevelAwait = false;
  9524. this.allExportNames = null;
  9525. this.exportAllModules = [];
  9526. this.exportNamesByVariable = null;
  9527. this.exportShimVariable = new ExportShimVariable(this);
  9528. this.namespaceReexportsByName = Object.create(null);
  9529. this.relevantDependencies = null;
  9530. this.syntheticExports = new Map();
  9531. this.syntheticNamespace = null;
  9532. this.transformDependencies = [];
  9533. this.transitiveReexports = null;
  9534. this.excludeFromSourcemap = /\0/.test(id);
  9535. this.context = options.moduleContext(id);
  9536. // eslint-disable-next-line @typescript-eslint/no-this-alias
  9537. const module = this;
  9538. this.info = {
  9539. ast: null,
  9540. code: null,
  9541. get dynamicallyImportedIds() {
  9542. const dynamicallyImportedIds = [];
  9543. for (const { id } of module.dynamicImports) {
  9544. if (id) {
  9545. dynamicallyImportedIds.push(id);
  9546. }
  9547. }
  9548. return dynamicallyImportedIds;
  9549. },
  9550. get dynamicImporters() {
  9551. return module.dynamicImporters.sort();
  9552. },
  9553. hasModuleSideEffects,
  9554. id,
  9555. get implicitlyLoadedAfterOneOf() {
  9556. return Array.from(module.implicitlyLoadedAfter, getId);
  9557. },
  9558. get implicitlyLoadedBefore() {
  9559. return Array.from(module.implicitlyLoadedBefore, getId);
  9560. },
  9561. get importedIds() {
  9562. return Array.from(module.sources, source => module.resolvedIds[source].id);
  9563. },
  9564. get importers() {
  9565. return module.importers.sort();
  9566. },
  9567. isEntry,
  9568. isExternal: false,
  9569. meta,
  9570. syntheticNamedExports
  9571. };
  9572. }
  9573. basename() {
  9574. const base = path.basename(this.id);
  9575. const ext = path.extname(this.id);
  9576. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  9577. }
  9578. bindReferences() {
  9579. this.ast.bind();
  9580. }
  9581. error(props, pos) {
  9582. this.addLocationToLogProps(props, pos);
  9583. return error(props);
  9584. }
  9585. getAllExportNames() {
  9586. if (this.allExportNames) {
  9587. return this.allExportNames;
  9588. }
  9589. const allExportNames = (this.allExportNames = new Set());
  9590. for (const name of Object.keys(this.exports)) {
  9591. allExportNames.add(name);
  9592. }
  9593. for (const name of Object.keys(this.reexportDescriptions)) {
  9594. allExportNames.add(name);
  9595. }
  9596. for (const module of this.exportAllModules) {
  9597. if (module instanceof ExternalModule) {
  9598. allExportNames.add(`*${module.id}`);
  9599. continue;
  9600. }
  9601. for (const name of module.getAllExportNames()) {
  9602. if (name !== 'default')
  9603. allExportNames.add(name);
  9604. }
  9605. }
  9606. return allExportNames;
  9607. }
  9608. getDependenciesToBeIncluded() {
  9609. if (this.relevantDependencies)
  9610. return this.relevantDependencies;
  9611. const relevantDependencies = new Set();
  9612. const necessaryDependencies = new Set();
  9613. const alwaysCheckedDependencies = new Set();
  9614. let dependencyVariables = this.imports.keys();
  9615. if (this.info.isEntry ||
  9616. this.includedDynamicImporters.length > 0 ||
  9617. this.namespace.included ||
  9618. this.implicitlyLoadedAfter.size > 0) {
  9619. dependencyVariables = new Set(dependencyVariables);
  9620. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  9621. const exportedVariable = this.getVariableForExportName(exportName);
  9622. if (exportedVariable) {
  9623. dependencyVariables.add(exportedVariable);
  9624. }
  9625. }
  9626. }
  9627. for (let variable of dependencyVariables) {
  9628. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  9629. if (sideEffectDependencies) {
  9630. for (const module of sideEffectDependencies) {
  9631. alwaysCheckedDependencies.add(module);
  9632. }
  9633. }
  9634. if (variable instanceof SyntheticNamedExportVariable) {
  9635. variable = variable.getBaseVariable();
  9636. }
  9637. else if (variable instanceof ExportDefaultVariable) {
  9638. variable = variable.getOriginalVariable();
  9639. }
  9640. necessaryDependencies.add(variable.module);
  9641. }
  9642. if (!this.options.treeshake || this.info.hasModuleSideEffects === 'no-treeshake') {
  9643. for (const dependency of this.dependencies) {
  9644. relevantDependencies.add(dependency);
  9645. }
  9646. }
  9647. else {
  9648. this.addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  9649. }
  9650. for (const dependency of necessaryDependencies) {
  9651. relevantDependencies.add(dependency);
  9652. }
  9653. return (this.relevantDependencies = relevantDependencies);
  9654. }
  9655. getExportNamesByVariable() {
  9656. if (this.exportNamesByVariable) {
  9657. return this.exportNamesByVariable;
  9658. }
  9659. const exportNamesByVariable = new Map();
  9660. for (const exportName of this.getAllExportNames()) {
  9661. if (exportName === this.info.syntheticNamedExports)
  9662. continue;
  9663. let tracedVariable = this.getVariableForExportName(exportName);
  9664. if (tracedVariable instanceof ExportDefaultVariable) {
  9665. tracedVariable = tracedVariable.getOriginalVariable();
  9666. }
  9667. if (!tracedVariable ||
  9668. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  9669. continue;
  9670. }
  9671. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  9672. if (existingExportNames) {
  9673. existingExportNames.push(exportName);
  9674. }
  9675. else {
  9676. exportNamesByVariable.set(tracedVariable, [exportName]);
  9677. }
  9678. }
  9679. return (this.exportNamesByVariable = exportNamesByVariable);
  9680. }
  9681. getExports() {
  9682. return Object.keys(this.exports);
  9683. }
  9684. getReexports() {
  9685. if (this.transitiveReexports) {
  9686. return this.transitiveReexports;
  9687. }
  9688. // to avoid infinite recursion when using circular `export * from X`
  9689. this.transitiveReexports = [];
  9690. const reexports = new Set();
  9691. for (const name in this.reexportDescriptions) {
  9692. reexports.add(name);
  9693. }
  9694. for (const module of this.exportAllModules) {
  9695. if (module instanceof ExternalModule) {
  9696. reexports.add(`*${module.id}`);
  9697. }
  9698. else {
  9699. for (const name of [...module.getReexports(), ...module.getExports()]) {
  9700. if (name !== 'default')
  9701. reexports.add(name);
  9702. }
  9703. }
  9704. }
  9705. return (this.transitiveReexports = [...reexports]);
  9706. }
  9707. getRenderedExports() {
  9708. // only direct exports are counted here, not reexports at all
  9709. const renderedExports = [];
  9710. const removedExports = [];
  9711. for (const exportName in this.exports) {
  9712. const variable = this.getVariableForExportName(exportName);
  9713. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  9714. }
  9715. return { removedExports, renderedExports };
  9716. }
  9717. getSyntheticNamespace() {
  9718. if (this.syntheticNamespace === null) {
  9719. this.syntheticNamespace = undefined;
  9720. this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  9721. ? this.info.syntheticNamedExports
  9722. : 'default');
  9723. }
  9724. if (!this.syntheticNamespace) {
  9725. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  9726. }
  9727. return this.syntheticNamespace;
  9728. }
  9729. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules, skipExternalNamespaceReexports } = EMPTY_OBJECT) {
  9730. if (name[0] === '*') {
  9731. if (name.length === 1) {
  9732. // export * from './other'
  9733. return this.namespace;
  9734. }
  9735. else {
  9736. // export * from 'external'
  9737. const module = this.graph.modulesById.get(name.slice(1));
  9738. return module.getVariableForExportName('*');
  9739. }
  9740. }
  9741. // export { foo } from './other'
  9742. const reexportDeclaration = this.reexportDescriptions[name];
  9743. if (reexportDeclaration) {
  9744. const variable = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules, false);
  9745. if (!variable) {
  9746. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  9747. }
  9748. if (importerForSideEffects) {
  9749. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9750. }
  9751. return variable;
  9752. }
  9753. const exportDeclaration = this.exports[name];
  9754. if (exportDeclaration) {
  9755. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  9756. return this.exportShimVariable;
  9757. }
  9758. const name = exportDeclaration.localName;
  9759. const variable = this.traceVariable(name, importerForSideEffects);
  9760. if (importerForSideEffects) {
  9761. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  9762. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9763. }
  9764. return variable;
  9765. }
  9766. if (name !== 'default') {
  9767. const foundNamespaceReexport = name in this.namespaceReexportsByName
  9768. ? this.namespaceReexportsByName[name]
  9769. : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, skipExternalNamespaceReexports);
  9770. if (!skipExternalNamespaceReexports) {
  9771. this.namespaceReexportsByName[name] = foundNamespaceReexport;
  9772. }
  9773. if (foundNamespaceReexport) {
  9774. return foundNamespaceReexport;
  9775. }
  9776. }
  9777. if (this.info.syntheticNamedExports) {
  9778. let syntheticExport = this.syntheticExports.get(name);
  9779. if (!syntheticExport) {
  9780. const syntheticNamespace = this.getSyntheticNamespace();
  9781. syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
  9782. this.syntheticExports.set(name, syntheticExport);
  9783. return syntheticExport;
  9784. }
  9785. return syntheticExport;
  9786. }
  9787. // we don't want to create shims when we are just
  9788. // probing export * modules for exports
  9789. if (!isExportAllSearch) {
  9790. if (this.options.shimMissingExports) {
  9791. this.shimMissingExport(name);
  9792. return this.exportShimVariable;
  9793. }
  9794. }
  9795. return null;
  9796. }
  9797. hasEffects() {
  9798. return (this.info.hasModuleSideEffects === 'no-treeshake' ||
  9799. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  9800. }
  9801. include() {
  9802. const context = createInclusionContext();
  9803. if (this.ast.shouldBeIncluded(context))
  9804. this.ast.include(context, false);
  9805. }
  9806. includeAllExports(includeNamespaceMembers) {
  9807. if (!this.isExecuted) {
  9808. markModuleAndImpureDependenciesAsExecuted(this);
  9809. this.graph.needsTreeshakingPass = true;
  9810. }
  9811. for (const exportName of this.getExports()) {
  9812. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  9813. const variable = this.getVariableForExportName(exportName);
  9814. variable.deoptimizePath(UNKNOWN_PATH);
  9815. if (!variable.included) {
  9816. this.includeVariable(variable);
  9817. }
  9818. }
  9819. }
  9820. for (const name of this.getReexports()) {
  9821. const variable = this.getVariableForExportName(name);
  9822. if (variable) {
  9823. variable.deoptimizePath(UNKNOWN_PATH);
  9824. if (!variable.included) {
  9825. this.includeVariable(variable);
  9826. }
  9827. if (variable instanceof ExternalVariable) {
  9828. variable.module.reexported = true;
  9829. }
  9830. }
  9831. }
  9832. if (includeNamespaceMembers) {
  9833. this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
  9834. }
  9835. }
  9836. includeAllInBundle() {
  9837. this.ast.include(createInclusionContext(), true);
  9838. this.includeAllExports(false);
  9839. }
  9840. isIncluded() {
  9841. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  9842. }
  9843. linkImports() {
  9844. this.addModulesToImportDescriptions(this.importDescriptions);
  9845. this.addModulesToImportDescriptions(this.reexportDescriptions);
  9846. for (const name in this.exports) {
  9847. if (name !== 'default' && name !== this.info.syntheticNamedExports) {
  9848. this.exportsAll[name] = this.id;
  9849. }
  9850. }
  9851. const externalExportAllModules = [];
  9852. for (const source of this.exportAllSources) {
  9853. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  9854. if (module instanceof ExternalModule) {
  9855. externalExportAllModules.push(module);
  9856. continue;
  9857. }
  9858. this.exportAllModules.push(module);
  9859. for (const name in module.exportsAll) {
  9860. if (name in this.exportsAll) {
  9861. this.options.onwarn(errNamespaceConflict(name, this, module));
  9862. }
  9863. else {
  9864. this.exportsAll[name] = module.exportsAll[name];
  9865. }
  9866. }
  9867. }
  9868. this.exportAllModules.push(...externalExportAllModules);
  9869. }
  9870. render(options) {
  9871. const magicString = this.magicString.clone();
  9872. this.ast.render(magicString, options);
  9873. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  9874. return magicString;
  9875. }
  9876. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  9877. this.info.code = code;
  9878. this.originalCode = originalCode;
  9879. this.originalSourcemap = originalSourcemap;
  9880. this.sourcemapChain = sourcemapChain;
  9881. if (transformFiles) {
  9882. this.transformFiles = transformFiles;
  9883. }
  9884. this.transformDependencies = transformDependencies;
  9885. this.customTransformCache = customTransformCache;
  9886. this.updateOptions(moduleOptions);
  9887. timeStart('generate ast', 3);
  9888. if (!ast) {
  9889. ast = this.tryParse();
  9890. }
  9891. timeEnd('generate ast', 3);
  9892. this.resolvedIds = resolvedIds || Object.create(null);
  9893. // By default, `id` is the file name. Custom resolvers and loaders
  9894. // can change that, but it makes sense to use it for the source file name
  9895. const fileName = this.id;
  9896. this.magicString = new MagicString$1(code, {
  9897. filename: (this.excludeFromSourcemap ? null : fileName),
  9898. indentExclusionRanges: []
  9899. });
  9900. timeStart('analyse ast', 3);
  9901. this.astContext = {
  9902. addDynamicImport: this.addDynamicImport.bind(this),
  9903. addExport: this.addExport.bind(this),
  9904. addImport: this.addImport.bind(this),
  9905. addImportMeta: this.addImportMeta.bind(this),
  9906. code,
  9907. deoptimizationTracker: this.graph.deoptimizationTracker,
  9908. error: this.error.bind(this),
  9909. fileName,
  9910. getExports: this.getExports.bind(this),
  9911. getModuleExecIndex: () => this.execIndex,
  9912. getModuleName: this.basename.bind(this),
  9913. getReexports: this.getReexports.bind(this),
  9914. importDescriptions: this.importDescriptions,
  9915. includeAllExports: () => this.includeAllExports(true),
  9916. includeDynamicImport: this.includeDynamicImport.bind(this),
  9917. includeVariableInModule: this.includeVariableInModule.bind(this),
  9918. magicString: this.magicString,
  9919. module: this,
  9920. moduleContext: this.context,
  9921. nodeConstructors,
  9922. options: this.options,
  9923. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  9924. traceExport: this.getVariableForExportName.bind(this),
  9925. traceVariable: this.traceVariable.bind(this),
  9926. usesTopLevelAwait: false,
  9927. warn: this.warn.bind(this)
  9928. };
  9929. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  9930. this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
  9931. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  9932. this.info.ast = ast;
  9933. timeEnd('analyse ast', 3);
  9934. }
  9935. toJSON() {
  9936. return {
  9937. ast: this.ast.esTreeNode,
  9938. code: this.info.code,
  9939. customTransformCache: this.customTransformCache,
  9940. dependencies: Array.from(this.dependencies, getId),
  9941. id: this.id,
  9942. meta: this.info.meta,
  9943. moduleSideEffects: this.info.hasModuleSideEffects,
  9944. originalCode: this.originalCode,
  9945. originalSourcemap: this.originalSourcemap,
  9946. resolvedIds: this.resolvedIds,
  9947. sourcemapChain: this.sourcemapChain,
  9948. syntheticNamedExports: this.info.syntheticNamedExports,
  9949. transformDependencies: this.transformDependencies,
  9950. transformFiles: this.transformFiles
  9951. };
  9952. }
  9953. traceVariable(name, importerForSideEffects) {
  9954. const localVariable = this.scope.variables.get(name);
  9955. if (localVariable) {
  9956. return localVariable;
  9957. }
  9958. if (name in this.importDescriptions) {
  9959. const importDeclaration = this.importDescriptions[name];
  9960. const otherModule = importDeclaration.module;
  9961. if (otherModule instanceof Module && importDeclaration.name === '*') {
  9962. return otherModule.namespace;
  9963. }
  9964. const declaration = otherModule.getVariableForExportName(importDeclaration.name, {
  9965. importerForSideEffects: importerForSideEffects || this
  9966. });
  9967. if (!declaration) {
  9968. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  9969. }
  9970. return declaration;
  9971. }
  9972. return null;
  9973. }
  9974. tryParse() {
  9975. try {
  9976. return this.graph.contextParse(this.info.code);
  9977. }
  9978. catch (err) {
  9979. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  9980. if (this.id.endsWith('.json')) {
  9981. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  9982. }
  9983. else if (!this.id.endsWith('.js')) {
  9984. message += ' (Note that you need plugins to import files that are not JavaScript)';
  9985. }
  9986. return this.error({
  9987. code: 'PARSE_ERROR',
  9988. message,
  9989. parserError: err
  9990. }, err.pos);
  9991. }
  9992. }
  9993. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  9994. if (moduleSideEffects != null) {
  9995. this.info.hasModuleSideEffects = moduleSideEffects;
  9996. }
  9997. if (syntheticNamedExports != null) {
  9998. this.info.syntheticNamedExports = syntheticNamedExports;
  9999. }
  10000. if (meta != null) {
  10001. this.info.meta = { ...this.info.meta, ...meta };
  10002. }
  10003. }
  10004. warn(props, pos) {
  10005. this.addLocationToLogProps(props, pos);
  10006. this.options.onwarn(props);
  10007. }
  10008. addDynamicImport(node) {
  10009. let argument = node.source;
  10010. if (argument instanceof TemplateLiteral) {
  10011. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  10012. argument = argument.quasis[0].value.cooked;
  10013. }
  10014. }
  10015. else if (argument instanceof Literal && typeof argument.value === 'string') {
  10016. argument = argument.value;
  10017. }
  10018. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  10019. }
  10020. addExport(node) {
  10021. if (node instanceof ExportDefaultDeclaration) {
  10022. // export default foo;
  10023. this.exports.default = {
  10024. identifier: node.variable.getAssignedVariableName(),
  10025. localName: 'default'
  10026. };
  10027. }
  10028. else if (node instanceof ExportAllDeclaration) {
  10029. const source = node.source.value;
  10030. this.sources.add(source);
  10031. if (node.exported) {
  10032. // export * as name from './other'
  10033. const name = node.exported.name;
  10034. this.reexportDescriptions[name] = {
  10035. localName: '*',
  10036. module: null,
  10037. source,
  10038. start: node.start
  10039. };
  10040. }
  10041. else {
  10042. // export * from './other'
  10043. this.exportAllSources.add(source);
  10044. }
  10045. }
  10046. else if (node.source instanceof Literal) {
  10047. // export { name } from './other'
  10048. const source = node.source.value;
  10049. this.sources.add(source);
  10050. for (const specifier of node.specifiers) {
  10051. const name = specifier.exported.name;
  10052. this.reexportDescriptions[name] = {
  10053. localName: specifier.local.name,
  10054. module: null,
  10055. source,
  10056. start: specifier.start
  10057. };
  10058. }
  10059. }
  10060. else if (node.declaration) {
  10061. const declaration = node.declaration;
  10062. if (declaration instanceof VariableDeclaration) {
  10063. // export var { foo, bar } = ...
  10064. // export var foo = 1, bar = 2;
  10065. for (const declarator of declaration.declarations) {
  10066. for (const localName of extractAssignedNames(declarator.id)) {
  10067. this.exports[localName] = { identifier: null, localName };
  10068. }
  10069. }
  10070. }
  10071. else {
  10072. // export function foo () {}
  10073. const localName = declaration.id.name;
  10074. this.exports[localName] = { identifier: null, localName };
  10075. }
  10076. }
  10077. else {
  10078. // export { foo, bar, baz }
  10079. for (const specifier of node.specifiers) {
  10080. const localName = specifier.local.name;
  10081. const exportedName = specifier.exported.name;
  10082. this.exports[exportedName] = { identifier: null, localName };
  10083. }
  10084. }
  10085. }
  10086. addImport(node) {
  10087. const source = node.source.value;
  10088. this.sources.add(source);
  10089. for (const specifier of node.specifiers) {
  10090. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  10091. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  10092. const name = isDefault
  10093. ? 'default'
  10094. : isNamespace
  10095. ? '*'
  10096. : specifier.imported.name;
  10097. this.importDescriptions[specifier.local.name] = {
  10098. module: null,
  10099. name,
  10100. source,
  10101. start: specifier.start
  10102. };
  10103. }
  10104. }
  10105. addImportMeta(node) {
  10106. this.importMetas.push(node);
  10107. }
  10108. addLocationToLogProps(props, pos) {
  10109. props.id = this.id;
  10110. props.pos = pos;
  10111. let code = this.info.code;
  10112. const location = locate(code, pos, { offsetLine: 1 });
  10113. if (location) {
  10114. let { column, line } = location;
  10115. try {
  10116. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  10117. code = this.originalCode;
  10118. }
  10119. catch (e) {
  10120. this.options.onwarn({
  10121. code: 'SOURCEMAP_ERROR',
  10122. id: this.id,
  10123. loc: {
  10124. column,
  10125. file: this.id,
  10126. line
  10127. },
  10128. message: `Error when using sourcemap for reporting an error: ${e.message}`,
  10129. pos
  10130. });
  10131. }
  10132. augmentCodeLocation(props, { column, line }, code, this.id);
  10133. }
  10134. }
  10135. addModulesToImportDescriptions(importDescription) {
  10136. for (const specifier of Object.values(importDescription)) {
  10137. const id = this.resolvedIds[specifier.source].id;
  10138. specifier.module = this.graph.modulesById.get(id);
  10139. }
  10140. }
  10141. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  10142. const handledDependencies = new Set();
  10143. const addSideEffectDependencies = (possibleDependencies) => {
  10144. for (const dependency of possibleDependencies) {
  10145. if (handledDependencies.has(dependency)) {
  10146. continue;
  10147. }
  10148. handledDependencies.add(dependency);
  10149. if (necessaryDependencies.has(dependency)) {
  10150. relevantDependencies.add(dependency);
  10151. continue;
  10152. }
  10153. if (!(dependency.info.hasModuleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  10154. continue;
  10155. }
  10156. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  10157. relevantDependencies.add(dependency);
  10158. continue;
  10159. }
  10160. addSideEffectDependencies(dependency.dependencies);
  10161. }
  10162. };
  10163. addSideEffectDependencies(this.dependencies);
  10164. addSideEffectDependencies(alwaysCheckedDependencies);
  10165. }
  10166. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, skipExternalNamespaceReexports = false) {
  10167. let foundSyntheticDeclaration = null;
  10168. const skipExternalNamespaceValues = [{ searchedNamesAndModules, skipExternalNamespaces: true }];
  10169. if (!skipExternalNamespaceReexports) {
  10170. const clonedSearchedNamesAndModules = new Map();
  10171. for (const [name, modules] of searchedNamesAndModules || []) {
  10172. clonedSearchedNamesAndModules.set(name, new Set(modules));
  10173. }
  10174. skipExternalNamespaceValues.push({
  10175. searchedNamesAndModules: clonedSearchedNamesAndModules,
  10176. skipExternalNamespaces: false
  10177. });
  10178. }
  10179. for (const { skipExternalNamespaces, searchedNamesAndModules } of skipExternalNamespaceValues) {
  10180. const foundDeclarations = new Set();
  10181. for (const module of this.exportAllModules) {
  10182. if (module instanceof Module || !skipExternalNamespaces) {
  10183. const declaration = getVariableForExportNameRecursive(module, name, importerForSideEffects, true, searchedNamesAndModules, skipExternalNamespaces);
  10184. if (declaration) {
  10185. if (!(declaration instanceof SyntheticNamedExportVariable)) {
  10186. foundDeclarations.add(declaration);
  10187. }
  10188. else if (!foundSyntheticDeclaration) {
  10189. foundSyntheticDeclaration = declaration;
  10190. }
  10191. }
  10192. }
  10193. }
  10194. if (foundDeclarations.size === 1) {
  10195. return [...foundDeclarations][0];
  10196. }
  10197. if (foundDeclarations.size > 1) {
  10198. if (skipExternalNamespaces) {
  10199. return null;
  10200. }
  10201. const foundDeclarationList = [...foundDeclarations];
  10202. const usedDeclaration = foundDeclarationList[0];
  10203. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  10204. return usedDeclaration;
  10205. }
  10206. }
  10207. if (foundSyntheticDeclaration) {
  10208. return foundSyntheticDeclaration;
  10209. }
  10210. return null;
  10211. }
  10212. includeAndGetAdditionalMergedNamespaces() {
  10213. const mergedNamespaces = [];
  10214. for (const module of this.exportAllModules) {
  10215. if (module instanceof ExternalModule) {
  10216. const externalVariable = module.getVariableForExportName('*');
  10217. externalVariable.include();
  10218. this.imports.add(externalVariable);
  10219. mergedNamespaces.push(externalVariable);
  10220. }
  10221. else if (module.info.syntheticNamedExports) {
  10222. const syntheticNamespace = module.getSyntheticNamespace();
  10223. syntheticNamespace.include();
  10224. this.imports.add(syntheticNamespace);
  10225. mergedNamespaces.push(syntheticNamespace);
  10226. }
  10227. }
  10228. return mergedNamespaces;
  10229. }
  10230. includeDynamicImport(node) {
  10231. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  10232. if (resolution instanceof Module) {
  10233. resolution.includedDynamicImporters.push(this);
  10234. resolution.includeAllExports(true);
  10235. }
  10236. }
  10237. includeVariable(variable) {
  10238. if (!variable.included) {
  10239. variable.include();
  10240. this.graph.needsTreeshakingPass = true;
  10241. const variableModule = variable.module;
  10242. if (variableModule && variableModule instanceof Module) {
  10243. if (!variableModule.isExecuted) {
  10244. markModuleAndImpureDependenciesAsExecuted(variableModule);
  10245. }
  10246. if (variableModule !== this) {
  10247. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  10248. for (const module of sideEffectModules) {
  10249. if (!module.isExecuted) {
  10250. markModuleAndImpureDependenciesAsExecuted(module);
  10251. }
  10252. }
  10253. }
  10254. }
  10255. }
  10256. }
  10257. includeVariableInModule(variable) {
  10258. this.includeVariable(variable);
  10259. const variableModule = variable.module;
  10260. if (variableModule && variableModule !== this) {
  10261. this.imports.add(variable);
  10262. }
  10263. }
  10264. shimMissingExport(name) {
  10265. this.options.onwarn({
  10266. code: 'SHIMMED_EXPORT',
  10267. exporter: relativeId(this.id),
  10268. exportName: name,
  10269. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  10270. });
  10271. this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
  10272. }
  10273. }
  10274. // if there is a cyclic import in the reexport chain, we should not
  10275. // import from the original module but from the cyclic module to not
  10276. // mess up execution order.
  10277. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  10278. if (variable.module instanceof Module && variable.module !== reexporter) {
  10279. const exporterCycles = variable.module.cycles;
  10280. if (exporterCycles.size > 0) {
  10281. const importerCycles = reexporter.cycles;
  10282. for (const cycleSymbol of importerCycles) {
  10283. if (exporterCycles.has(cycleSymbol)) {
  10284. importer.alternativeReexportModules.set(variable, reexporter);
  10285. break;
  10286. }
  10287. }
  10288. }
  10289. }
  10290. }
  10291. function removeJsExtension(name) {
  10292. return name.endsWith('.js') ? name.slice(0, -3) : name;
  10293. }
  10294. function getCompleteAmdId(options, chunkId) {
  10295. if (!options.autoId) {
  10296. return options.id || '';
  10297. }
  10298. else {
  10299. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  10300. }
  10301. }
  10302. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
  10303. const _ = compact ? '' : ' ';
  10304. const n = compact ? '' : '\n';
  10305. if (!namedExportsMode) {
  10306. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
  10307. }
  10308. let exportBlock = '';
  10309. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  10310. if (reexports && namedExportsMode) {
  10311. for (const specifier of reexports) {
  10312. if (specifier.reexported !== '*') {
  10313. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  10314. if (exportBlock)
  10315. exportBlock += n;
  10316. exportBlock +=
  10317. specifier.imported !== '*' && specifier.needsLiveBinding
  10318. ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  10319. `${t}enumerable:${_}true,${n}` +
  10320. `${t}get:${_}function${_}()${_}{${n}` +
  10321. `${t}${t}return ${importName};${n}${t}}${n}});`
  10322. : `exports.${specifier.reexported}${_}=${_}${importName};`;
  10323. }
  10324. }
  10325. }
  10326. }
  10327. for (const { exported, local } of exports) {
  10328. const lhs = `exports${RESERVED_NAMES[exported] ? `['${exported}']` : `.${exported}`}`;
  10329. const rhs = local;
  10330. if (lhs !== rhs) {
  10331. if (exportBlock)
  10332. exportBlock += n;
  10333. exportBlock += `${lhs}${_}=${_}${rhs};`;
  10334. }
  10335. }
  10336. for (const { name, reexports } of dependencies) {
  10337. if (reexports && namedExportsMode) {
  10338. for (const specifier of reexports) {
  10339. if (specifier.reexported === '*') {
  10340. if (exportBlock)
  10341. exportBlock += n;
  10342. if (specifier.needsLiveBinding) {
  10343. exportBlock +=
  10344. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  10345. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
  10346. `${t}${t}enumerable:${_}true,${n}` +
  10347. `${t}${t}get:${_}function${_}()${_}{${n}` +
  10348. `${t}${t}${t}return ${name}[k];${n}` +
  10349. `${t}${t}}${n}${t}});${n}});`;
  10350. }
  10351. else {
  10352. exportBlock +=
  10353. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  10354. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}exports[k]${_}=${_}${name}[k];${n}});`;
  10355. }
  10356. }
  10357. }
  10358. }
  10359. }
  10360. if (exportBlock) {
  10361. return `${n}${n}${exportBlock}`;
  10362. }
  10363. return '';
  10364. }
  10365. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
  10366. if (exports.length > 0) {
  10367. return exports[0].local;
  10368. }
  10369. else {
  10370. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  10371. if (reexports) {
  10372. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  10373. }
  10374. }
  10375. }
  10376. }
  10377. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
  10378. if (imported === 'default') {
  10379. if (!isChunk) {
  10380. const moduleInterop = String(interop(moduleId));
  10381. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  10382. ? defaultVariableName
  10383. : moduleVariableName;
  10384. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  10385. ? `${variableName}['default']`
  10386. : variableName;
  10387. }
  10388. return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
  10389. }
  10390. if (imported === '*') {
  10391. return (isChunk
  10392. ? !depNamedExportsMode
  10393. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  10394. ? namespaceVariableName
  10395. : moduleVariableName;
  10396. }
  10397. return `${moduleVariableName}.${imported}`;
  10398. }
  10399. function getEsModuleExport(_) {
  10400. return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
  10401. }
  10402. function getNamespaceToStringExport(_) {
  10403. return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
  10404. }
  10405. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
  10406. let namespaceMarkers = '';
  10407. if (hasNamedExports) {
  10408. if (addEsModule) {
  10409. namespaceMarkers += getEsModuleExport(_);
  10410. }
  10411. if (addNamespaceToStringTag) {
  10412. if (namespaceMarkers) {
  10413. namespaceMarkers += n;
  10414. }
  10415. namespaceMarkers += getNamespaceToStringExport(_);
  10416. }
  10417. }
  10418. return namespaceMarkers;
  10419. }
  10420. function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
  10421. const neededInteropHelpers = new Set();
  10422. const interopStatements = [];
  10423. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  10424. neededInteropHelpers.add(helper);
  10425. interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  10426. };
  10427. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  10428. if (isChunk) {
  10429. for (const { imported, reexported } of [
  10430. ...(imports || []),
  10431. ...(reexports || [])
  10432. ]) {
  10433. if (imported === '*' && reexported !== '*') {
  10434. if (!namedExportsMode) {
  10435. addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
  10436. }
  10437. break;
  10438. }
  10439. }
  10440. }
  10441. else {
  10442. const moduleInterop = String(interop(id));
  10443. let hasDefault = false;
  10444. let hasNamespace = false;
  10445. for (const { imported, reexported } of [
  10446. ...(imports || []),
  10447. ...(reexports || [])
  10448. ]) {
  10449. let helper;
  10450. let variableName;
  10451. if (imported === 'default') {
  10452. if (!hasDefault) {
  10453. hasDefault = true;
  10454. if (defaultVariableName !== namespaceVariableName) {
  10455. variableName = defaultVariableName;
  10456. helper = defaultInteropHelpersByInteropType[moduleInterop];
  10457. }
  10458. }
  10459. }
  10460. else if (imported === '*' && reexported !== '*') {
  10461. if (!hasNamespace) {
  10462. hasNamespace = true;
  10463. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  10464. variableName = namespaceVariableName;
  10465. }
  10466. }
  10467. if (helper) {
  10468. addInteropStatement(variableName, helper, name);
  10469. }
  10470. }
  10471. }
  10472. }
  10473. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  10474. }
  10475. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  10476. // The assumption is that this makes sense for all relative ids:
  10477. // https://requirejs.org/docs/api.html#jsfiles
  10478. function removeExtensionFromRelativeAmdId(id) {
  10479. return id[0] === '.' ? removeJsExtension(id) : id;
  10480. }
  10481. const builtins = {
  10482. assert: true,
  10483. buffer: true,
  10484. console: true,
  10485. constants: true,
  10486. domain: true,
  10487. events: true,
  10488. http: true,
  10489. https: true,
  10490. os: true,
  10491. path: true,
  10492. process: true,
  10493. punycode: true,
  10494. querystring: true,
  10495. stream: true,
  10496. string_decoder: true,
  10497. timers: true,
  10498. tty: true,
  10499. url: true,
  10500. util: true,
  10501. vm: true,
  10502. zlib: true
  10503. };
  10504. function warnOnBuiltins(warn, dependencies) {
  10505. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  10506. if (!externalBuiltins.length)
  10507. return;
  10508. warn({
  10509. code: 'MISSING_NODE_BUILTINS',
  10510. message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node`,
  10511. modules: externalBuiltins
  10512. });
  10513. }
  10514. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  10515. warnOnBuiltins(warn, dependencies);
  10516. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  10517. const args = dependencies.map(m => m.name);
  10518. const n = compact ? '' : '\n';
  10519. const s = compact ? '' : ';';
  10520. const _ = compact ? '' : ' ';
  10521. if (namedExportsMode && hasExports) {
  10522. args.unshift(`exports`);
  10523. deps.unshift(`'exports'`);
  10524. }
  10525. if (accessedGlobals.has('require')) {
  10526. args.unshift('require');
  10527. deps.unshift(`'require'`);
  10528. }
  10529. if (accessedGlobals.has('module')) {
  10530. args.unshift('module');
  10531. deps.unshift(`'module'`);
  10532. }
  10533. const completeAmdId = getCompleteAmdId(amd, id);
  10534. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  10535. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  10536. const useStrict = strict ? `${_}'use strict';` : '';
  10537. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  10538. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  10539. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  10540. if (namespaceMarkers) {
  10541. namespaceMarkers = n + n + namespaceMarkers;
  10542. }
  10543. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  10544. return magicString
  10545. .indent(t)
  10546. .prepend(`${amd.define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
  10547. .append(`${n}${n}});`);
  10548. }
  10549. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  10550. const n = compact ? '' : '\n';
  10551. const s = compact ? '' : ';';
  10552. const _ = compact ? '' : ' ';
  10553. const useStrict = strict ? `'use strict';${n}${n}` : '';
  10554. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  10555. if (namespaceMarkers) {
  10556. namespaceMarkers += n + n;
  10557. }
  10558. const importBlock = getImportBlock$1(dependencies, compact, varOrConst, n, _);
  10559. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  10560. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  10561. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
  10562. return magicString.append(`${exportBlock}${outro}`);
  10563. }
  10564. function getImportBlock$1(dependencies, compact, varOrConst, n, _) {
  10565. let importBlock = '';
  10566. let definingVariable = false;
  10567. for (const { id, name, reexports, imports } of dependencies) {
  10568. if (!reexports && !imports) {
  10569. if (importBlock) {
  10570. importBlock += !compact || definingVariable ? `;${n}` : ',';
  10571. }
  10572. definingVariable = false;
  10573. importBlock += `require('${id}')`;
  10574. }
  10575. else {
  10576. importBlock +=
  10577. compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
  10578. definingVariable = true;
  10579. importBlock += `${name}${_}=${_}require('${id}')`;
  10580. }
  10581. }
  10582. if (importBlock) {
  10583. return `${importBlock};${n}${n}`;
  10584. }
  10585. return '';
  10586. }
  10587. function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
  10588. const _ = compact ? '' : ' ';
  10589. const n = compact ? '' : '\n';
  10590. const importBlock = getImportBlock(dependencies, _);
  10591. if (importBlock.length > 0)
  10592. intro += importBlock.join(n) + n + n;
  10593. if (intro)
  10594. magicString.prepend(intro);
  10595. const exportBlock = getExportBlock(exports, _, varOrConst);
  10596. if (exportBlock.length)
  10597. magicString.append(n + n + exportBlock.join(n).trim());
  10598. if (outro)
  10599. magicString.append(outro);
  10600. return magicString.trim();
  10601. }
  10602. function getImportBlock(dependencies, _) {
  10603. const importBlock = [];
  10604. for (const { id, reexports, imports, name } of dependencies) {
  10605. if (!reexports && !imports) {
  10606. importBlock.push(`import${_}'${id}';`);
  10607. continue;
  10608. }
  10609. if (imports) {
  10610. let defaultImport = null;
  10611. let starImport = null;
  10612. const importedNames = [];
  10613. for (const specifier of imports) {
  10614. if (specifier.imported === 'default') {
  10615. defaultImport = specifier;
  10616. }
  10617. else if (specifier.imported === '*') {
  10618. starImport = specifier;
  10619. }
  10620. else {
  10621. importedNames.push(specifier);
  10622. }
  10623. }
  10624. if (starImport) {
  10625. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  10626. }
  10627. if (defaultImport && importedNames.length === 0) {
  10628. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  10629. }
  10630. else if (importedNames.length > 0) {
  10631. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  10632. .map(specifier => {
  10633. if (specifier.imported === specifier.local) {
  10634. return specifier.imported;
  10635. }
  10636. else {
  10637. return `${specifier.imported} as ${specifier.local}`;
  10638. }
  10639. })
  10640. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  10641. }
  10642. }
  10643. if (reexports) {
  10644. let starExport = null;
  10645. const namespaceReexports = [];
  10646. const namedReexports = [];
  10647. for (const specifier of reexports) {
  10648. if (specifier.reexported === '*') {
  10649. starExport = specifier;
  10650. }
  10651. else if (specifier.imported === '*') {
  10652. namespaceReexports.push(specifier);
  10653. }
  10654. else {
  10655. namedReexports.push(specifier);
  10656. }
  10657. }
  10658. if (starExport) {
  10659. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  10660. }
  10661. if (namespaceReexports.length > 0) {
  10662. if (!imports ||
  10663. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  10664. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  10665. }
  10666. for (const specifier of namespaceReexports) {
  10667. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  10668. }
  10669. }
  10670. if (namedReexports.length > 0) {
  10671. importBlock.push(`export${_}{${_}${namedReexports
  10672. .map(specifier => {
  10673. if (specifier.imported === specifier.reexported) {
  10674. return specifier.imported;
  10675. }
  10676. else {
  10677. return `${specifier.imported} as ${specifier.reexported}`;
  10678. }
  10679. })
  10680. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  10681. }
  10682. }
  10683. }
  10684. return importBlock;
  10685. }
  10686. function getExportBlock(exports, _, varOrConst) {
  10687. const exportBlock = [];
  10688. const exportDeclaration = [];
  10689. for (const specifier of exports) {
  10690. if (specifier.expression) {
  10691. exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
  10692. }
  10693. exportDeclaration.push(specifier.exported === specifier.local
  10694. ? specifier.local
  10695. : `${specifier.local} as ${specifier.exported}`);
  10696. }
  10697. if (exportDeclaration.length) {
  10698. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  10699. }
  10700. return exportBlock;
  10701. }
  10702. // Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
  10703. // if the property name isn't trivial
  10704. const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
  10705. function property(prop) {
  10706. return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
  10707. }
  10708. function keypath(keypath) {
  10709. return keypath.split('.').map(property).join('');
  10710. }
  10711. function setupNamespace(name, root, globals, compact) {
  10712. const _ = compact ? '' : ' ';
  10713. const parts = name.split('.');
  10714. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  10715. parts.pop();
  10716. let acc = root;
  10717. return (parts
  10718. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
  10719. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  10720. }
  10721. function assignToDeepVariable(deepName, root, globals, compact, assignment) {
  10722. const _ = compact ? '' : ' ';
  10723. const parts = deepName.split('.');
  10724. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  10725. const last = parts.pop();
  10726. let acc = root;
  10727. let deepAssignment = parts
  10728. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
  10729. .concat(`${acc}${property(last)}`)
  10730. .join(`,${_}`)
  10731. .concat(`${_}=${_}${assignment}`);
  10732. if (parts.length > 0) {
  10733. deepAssignment = `(${deepAssignment})`;
  10734. }
  10735. return deepAssignment;
  10736. }
  10737. function trimEmptyImports(dependencies) {
  10738. let i = dependencies.length;
  10739. while (i--) {
  10740. const { imports, reexports } = dependencies[i];
  10741. if (imports || reexports) {
  10742. return dependencies.slice(0, i + 1);
  10743. }
  10744. }
  10745. return [];
  10746. }
  10747. const thisProp = (name) => `this${keypath(name)}`;
  10748. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  10749. const _ = compact ? '' : ' ';
  10750. const s = compact ? '' : ';';
  10751. const n = compact ? '' : '\n';
  10752. const isNamespaced = name && name.indexOf('.') !== -1;
  10753. const useVariableAssignment = !extend && !isNamespaced;
  10754. if (name && useVariableAssignment && !isLegal(name)) {
  10755. return error({
  10756. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  10757. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  10758. });
  10759. }
  10760. warnOnBuiltins(warn, dependencies);
  10761. const external = trimEmptyImports(dependencies);
  10762. const deps = external.map(dep => dep.globalName || 'null');
  10763. const args = external.map(m => m.name);
  10764. if (hasExports && !name) {
  10765. warn({
  10766. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  10767. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  10768. });
  10769. }
  10770. if (namedExportsMode && hasExports) {
  10771. if (extend) {
  10772. deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
  10773. args.unshift('exports');
  10774. }
  10775. else {
  10776. deps.unshift('{}');
  10777. args.unshift('exports');
  10778. }
  10779. }
  10780. const useStrict = strict ? `${t}'use strict';${n}` : '';
  10781. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  10782. magicString.prepend(`${intro}${interopBlock}`);
  10783. let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
  10784. if (hasExports) {
  10785. if (name && !(extend && namedExportsMode)) {
  10786. wrapperIntro =
  10787. (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
  10788. `${_}=${_}${wrapperIntro}`;
  10789. }
  10790. if (isNamespaced) {
  10791. wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
  10792. }
  10793. }
  10794. let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
  10795. if (hasExports && !extend && namedExportsMode) {
  10796. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  10797. }
  10798. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  10799. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  10800. if (namespaceMarkers) {
  10801. namespaceMarkers = n + n + namespaceMarkers;
  10802. }
  10803. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  10804. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  10805. }
  10806. function getStarExcludes({ dependencies, exports }) {
  10807. const starExcludes = new Set(exports.map(expt => expt.exported));
  10808. starExcludes.add('default');
  10809. for (const { reexports } of dependencies) {
  10810. if (reexports) {
  10811. for (const reexport of reexports) {
  10812. if (reexport.imported !== '*')
  10813. starExcludes.add(reexport.reexported);
  10814. }
  10815. }
  10816. }
  10817. return starExcludes;
  10818. }
  10819. const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
  10820. ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
  10821. .map(prop => `${prop}:${_}1`)
  10822. .join(`,${_}`)}${_}};`
  10823. : '';
  10824. const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  10825. function getExportsBlock(exports, _, t, n) {
  10826. if (exports.length === 0) {
  10827. return '';
  10828. }
  10829. if (exports.length === 1) {
  10830. return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  10831. }
  10832. return (`${t}${t}${t}exports({${n}` +
  10833. exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
  10834. `${n}${t}${t}${t}});${n}${n}`);
  10835. }
  10836. const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  10837. const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  10838. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  10839. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
  10840. const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  10841. .filter(expt => expt.expression)
  10842. .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  10843. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
  10844. const n = options.compact ? '' : '\n';
  10845. const _ = options.compact ? '' : ' ';
  10846. const dependencyIds = dependencies.map(m => `'${m.id}'`);
  10847. const importBindings = [];
  10848. let starExcludes;
  10849. const setters = [];
  10850. for (const { imports, reexports } of dependencies) {
  10851. const setter = [];
  10852. if (imports) {
  10853. for (const specifier of imports) {
  10854. importBindings.push(specifier.local);
  10855. if (specifier.imported === '*') {
  10856. setter.push(`${specifier.local}${_}=${_}module;`);
  10857. }
  10858. else {
  10859. setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
  10860. }
  10861. }
  10862. }
  10863. if (reexports) {
  10864. let createdSetter = false;
  10865. // bulk-reexport form
  10866. if (reexports.length > 1 ||
  10867. (reexports.length === 1 &&
  10868. (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
  10869. // star reexports
  10870. for (const specifier of reexports) {
  10871. if (specifier.reexported !== '*')
  10872. continue;
  10873. // need own exports list for deduping in star export case
  10874. if (!starExcludes) {
  10875. starExcludes = getStarExcludes({ dependencies, exports });
  10876. }
  10877. createdSetter = true;
  10878. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  10879. setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
  10880. setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
  10881. setter.push('}');
  10882. }
  10883. // star import reexport
  10884. for (const specifier of reexports) {
  10885. if (specifier.imported !== '*' || specifier.reexported === '*')
  10886. continue;
  10887. setter.push(`exports('${specifier.reexported}',${_}module);`);
  10888. }
  10889. // reexports
  10890. for (const specifier of reexports) {
  10891. if (specifier.reexported === '*' || specifier.imported === '*')
  10892. continue;
  10893. if (!createdSetter) {
  10894. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  10895. createdSetter = true;
  10896. }
  10897. setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
  10898. }
  10899. if (createdSetter) {
  10900. setter.push('exports(_setter);');
  10901. }
  10902. }
  10903. else {
  10904. // single reexport
  10905. for (const specifier of reexports) {
  10906. setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
  10907. }
  10908. }
  10909. }
  10910. setters.push(setter.join(`${n}${t}${t}${t}`));
  10911. }
  10912. const registeredName = options.name ? `'${options.name}',${_}` : '';
  10913. const wrapperParams = accessedGlobals.has('module')
  10914. ? `exports,${_}module`
  10915. : hasExports
  10916. ? 'exports'
  10917. : '';
  10918. let wrapperStart = `System.register(${registeredName}[` +
  10919. dependencyIds.join(`,${_}`) +
  10920. `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
  10921. getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
  10922. getImportBindingsBlock(importBindings, _, t, n) +
  10923. `${n}${t}return${_}{${setters.length
  10924. ? `${n}${t}${t}setters:${_}[${setters
  10925. .map(s => s
  10926. ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
  10927. : options.systemNullSetters
  10928. ? `null`
  10929. : `function${_}()${_}{}`)
  10930. .join(`,${_}`)}],`
  10931. : ''}${n}`;
  10932. wrapperStart +=
  10933. `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
  10934. getHoistedExportsBlock(exports, _, t, n);
  10935. const wrapperEnd = `${n}${n}` +
  10936. getSyntheticExportsBlock(exports, _, t, n) +
  10937. getMissingExportsBlock(exports, _, t, n) +
  10938. `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
  10939. if (intro)
  10940. magicString.prepend(intro);
  10941. if (outro)
  10942. magicString.append(outro);
  10943. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  10944. }
  10945. function globalProp(name, globalVar) {
  10946. if (!name)
  10947. return 'null';
  10948. return `${globalVar}${keypath(name)}`;
  10949. }
  10950. function safeAccess(name, globalVar, _) {
  10951. const parts = name.split('.');
  10952. let acc = globalVar;
  10953. return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
  10954. }
  10955. function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  10956. const _ = compact ? '' : ' ';
  10957. const n = compact ? '' : '\n';
  10958. const s = compact ? '' : ';';
  10959. const factoryVar = compact ? 'f' : 'factory';
  10960. const globalVar = compact ? 'g' : 'global';
  10961. if (hasExports && !name) {
  10962. return error({
  10963. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  10964. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  10965. });
  10966. }
  10967. warnOnBuiltins(warn, dependencies);
  10968. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  10969. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  10970. const trimmedImports = trimEmptyImports(dependencies);
  10971. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
  10972. const factoryArgs = trimmedImports.map(m => m.name);
  10973. if (namedExportsMode && (hasExports || noConflict)) {
  10974. amdDeps.unshift(`'exports'`);
  10975. cjsDeps.unshift(`exports`);
  10976. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
  10977. factoryArgs.unshift('exports');
  10978. }
  10979. const completeAmdId = getCompleteAmdId(amd, id);
  10980. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  10981. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  10982. const define = amd.define;
  10983. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  10984. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  10985. let iifeExport;
  10986. if (noConflict) {
  10987. const noConflictExportsVar = compact ? 'e' : 'exports';
  10988. let factory;
  10989. if (!namedExportsMode && hasExports) {
  10990. factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
  10991. }
  10992. else {
  10993. const module = globalDeps.shift();
  10994. factory =
  10995. `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
  10996. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  10997. }
  10998. iifeExport =
  10999. `(function${_}()${_}{${n}` +
  11000. `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
  11001. `${t}${t}${factory}${n}` +
  11002. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
  11003. `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
  11004. `${t}}())`;
  11005. }
  11006. else {
  11007. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  11008. if (!namedExportsMode && hasExports) {
  11009. iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
  11010. }
  11011. }
  11012. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  11013. const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
  11014. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  11015. const iifeStart = iifeNeedsGlobal
  11016. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  11017. : '';
  11018. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  11019. const cjsIntro = iifeNeedsGlobal
  11020. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  11021. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  11022. : '';
  11023. // factory function should be wrapped by parentheses to avoid lazy parsing
  11024. const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
  11025. cjsIntro +
  11026. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  11027. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  11028. `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
  11029. const wrapperOutro = n + n + '})));';
  11030. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  11031. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  11032. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  11033. if (namespaceMarkers) {
  11034. namespaceMarkers = n + n + namespaceMarkers;
  11035. }
  11036. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  11037. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  11038. }
  11039. var finalisers = { amd, cjs, es, iife, system, umd };
  11040. class Source {
  11041. constructor(filename, content) {
  11042. this.isOriginal = true;
  11043. this.filename = filename;
  11044. this.content = content;
  11045. }
  11046. traceSegment(line, column, name) {
  11047. return { column, line, name, source: this };
  11048. }
  11049. }
  11050. class Link {
  11051. constructor(map, sources) {
  11052. this.sources = sources;
  11053. this.names = map.names;
  11054. this.mappings = map.mappings;
  11055. }
  11056. traceMappings() {
  11057. const sources = [];
  11058. const sourcesContent = [];
  11059. const names = [];
  11060. const nameIndexMap = new Map();
  11061. const mappings = [];
  11062. for (const line of this.mappings) {
  11063. const tracedLine = [];
  11064. for (const segment of line) {
  11065. if (segment.length == 1)
  11066. continue;
  11067. const source = this.sources[segment[1]];
  11068. if (!source)
  11069. continue;
  11070. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  11071. if (traced) {
  11072. // newer sources are more likely to be used, so search backwards.
  11073. let sourceIndex = sources.lastIndexOf(traced.source.filename);
  11074. if (sourceIndex === -1) {
  11075. sourceIndex = sources.length;
  11076. sources.push(traced.source.filename);
  11077. sourcesContent[sourceIndex] = traced.source.content;
  11078. }
  11079. else if (sourcesContent[sourceIndex] == null) {
  11080. sourcesContent[sourceIndex] = traced.source.content;
  11081. }
  11082. else if (traced.source.content != null &&
  11083. sourcesContent[sourceIndex] !== traced.source.content) {
  11084. return error({
  11085. message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
  11086. });
  11087. }
  11088. const tracedSegment = [
  11089. segment[0],
  11090. sourceIndex,
  11091. traced.line,
  11092. traced.column
  11093. ];
  11094. if (traced.name) {
  11095. let nameIndex = nameIndexMap.get(traced.name);
  11096. if (nameIndex === undefined) {
  11097. nameIndex = names.length;
  11098. names.push(traced.name);
  11099. nameIndexMap.set(traced.name, nameIndex);
  11100. }
  11101. tracedSegment[4] = nameIndex;
  11102. }
  11103. tracedLine.push(tracedSegment);
  11104. }
  11105. }
  11106. mappings.push(tracedLine);
  11107. }
  11108. return { mappings, names, sources, sourcesContent };
  11109. }
  11110. traceSegment(line, column, name) {
  11111. const segments = this.mappings[line];
  11112. if (!segments)
  11113. return null;
  11114. // binary search through segments for the given column
  11115. let i = 0;
  11116. let j = segments.length - 1;
  11117. while (i <= j) {
  11118. const m = (i + j) >> 1;
  11119. const segment = segments[m];
  11120. if (segment[0] === column) {
  11121. if (segment.length == 1)
  11122. return null;
  11123. const source = this.sources[segment[1]];
  11124. if (!source)
  11125. return null;
  11126. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  11127. }
  11128. if (segment[0] > column) {
  11129. j = m - 1;
  11130. }
  11131. else {
  11132. i = m + 1;
  11133. }
  11134. }
  11135. return null;
  11136. }
  11137. }
  11138. function getLinkMap(warn) {
  11139. return function linkMap(source, map) {
  11140. if (map.mappings) {
  11141. return new Link(map, [source]);
  11142. }
  11143. warn({
  11144. code: 'SOURCEMAP_BROKEN',
  11145. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  11146. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  11147. 'documentation for help',
  11148. plugin: map.plugin,
  11149. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  11150. });
  11151. return new Link({
  11152. mappings: [],
  11153. names: []
  11154. }, [source]);
  11155. };
  11156. }
  11157. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  11158. let source;
  11159. if (!originalSourcemap) {
  11160. source = new Source(id, originalCode);
  11161. }
  11162. else {
  11163. const sources = originalSourcemap.sources;
  11164. const sourcesContent = originalSourcemap.sourcesContent || [];
  11165. const directory = path.dirname(id) || '.';
  11166. const sourceRoot = originalSourcemap.sourceRoot || '.';
  11167. const baseSources = sources.map((source, i) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[i]));
  11168. source = new Link(originalSourcemap, baseSources);
  11169. }
  11170. return sourcemapChain.reduce(linkMap, source);
  11171. }
  11172. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  11173. const linkMap = getLinkMap(warn);
  11174. const moduleSources = modules
  11175. .filter(module => !module.excludeFromSourcemap)
  11176. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  11177. // DecodedSourceMap (from magic-string) uses a number[] instead of the more
  11178. // correct SourceMapSegment tuples. Cast it here to gain type safety.
  11179. let source = new Link(map, moduleSources);
  11180. source = bundleSourcemapChain.reduce(linkMap, source);
  11181. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  11182. if (file) {
  11183. const directory = path.dirname(file);
  11184. sources = sources.map((source) => path.relative(directory, source));
  11185. file = path.basename(file);
  11186. }
  11187. sourcesContent = (excludeContent ? null : sourcesContent);
  11188. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  11189. }
  11190. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  11191. if (!sourcemapChain.length) {
  11192. return originalSourcemap;
  11193. }
  11194. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  11195. const map = source.traceMappings();
  11196. return { version: 3, ...map };
  11197. }
  11198. const createHash = () => crypto.createHash('sha256');
  11199. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  11200. amd: deconflictImportsOther,
  11201. cjs: deconflictImportsOther,
  11202. es: deconflictImportsEsmOrSystem,
  11203. iife: deconflictImportsOther,
  11204. system: deconflictImportsEsmOrSystem,
  11205. umd: deconflictImportsOther
  11206. };
  11207. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  11208. const reversedModules = modules.slice().reverse();
  11209. for (const module of reversedModules) {
  11210. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  11211. }
  11212. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  11213. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  11214. for (const module of reversedModules) {
  11215. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  11216. }
  11217. }
  11218. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  11219. // This is needed for namespace reexports
  11220. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  11221. if (preserveModules || dependency instanceof ExternalModule) {
  11222. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  11223. }
  11224. }
  11225. for (const variable of imports) {
  11226. const module = variable.module;
  11227. const name = variable.name;
  11228. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  11229. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  11230. }
  11231. else if (module instanceof ExternalModule && name === 'default') {
  11232. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  11233. ? module.suggestedVariableName + '__default'
  11234. : module.suggestedVariableName, usedNames));
  11235. }
  11236. else {
  11237. variable.setRenderNames(null, getSafeName(name, usedNames));
  11238. }
  11239. }
  11240. for (const variable of syntheticExports) {
  11241. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  11242. }
  11243. }
  11244. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  11245. for (const chunkOrExternalModule of dependencies) {
  11246. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  11247. }
  11248. for (const externalModuleOrChunk of deconflictedNamespace) {
  11249. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  11250. }
  11251. for (const externalModule of deconflictedDefault) {
  11252. if (deconflictedNamespace.has(externalModule) &&
  11253. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  11254. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  11255. }
  11256. else {
  11257. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  11258. }
  11259. }
  11260. for (const variable of imports) {
  11261. const module = variable.module;
  11262. if (module instanceof ExternalModule) {
  11263. const name = variable.name;
  11264. if (name === 'default') {
  11265. const moduleInterop = String(interop(module.id));
  11266. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  11267. ? module.defaultVariableName
  11268. : module.variableName;
  11269. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  11270. variable.setRenderNames(variableName, 'default');
  11271. }
  11272. else {
  11273. variable.setRenderNames(null, variableName);
  11274. }
  11275. }
  11276. else if (name === '*') {
  11277. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  11278. ? module.namespaceVariableName
  11279. : module.variableName);
  11280. }
  11281. else {
  11282. // if the second parameter is `null`, it uses its "name" for the property name
  11283. variable.setRenderNames(module.variableName, null);
  11284. }
  11285. }
  11286. else {
  11287. const chunk = chunkByModule.get(module);
  11288. if (preserveModules && variable.isNamespace) {
  11289. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  11290. }
  11291. else if (chunk.exportMode === 'default') {
  11292. variable.setRenderNames(null, chunk.variableName);
  11293. }
  11294. else {
  11295. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  11296. }
  11297. }
  11298. }
  11299. }
  11300. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  11301. for (const module of modules) {
  11302. for (const variable of module.scope.variables.values()) {
  11303. if (variable.included &&
  11304. // this will only happen for exports in some formats
  11305. !(variable.renderBaseName ||
  11306. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  11307. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  11308. }
  11309. }
  11310. if (includedNamespaces.has(module)) {
  11311. const namespace = module.namespace;
  11312. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  11313. }
  11314. }
  11315. }
  11316. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  11317. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  11318. const backSlashRegEx = /\\/g;
  11319. function escapeId(id) {
  11320. if (!id.match(needsEscapeRegEx))
  11321. return id;
  11322. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  11323. }
  11324. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  11325. let nameIndex = 0;
  11326. for (const variable of exports) {
  11327. let exportName = variable.name[0];
  11328. if (exportsByName[exportName]) {
  11329. do {
  11330. exportName = toBase64(++nameIndex);
  11331. // skip past leading number identifiers
  11332. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  11333. nameIndex += 9 * 64 ** (exportName.length - 1);
  11334. exportName = toBase64(nameIndex);
  11335. }
  11336. } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
  11337. }
  11338. exportsByName[exportName] = variable;
  11339. exportNamesByVariable.set(variable, [exportName]);
  11340. }
  11341. }
  11342. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  11343. for (const variable of exports) {
  11344. let nameIndex = 0;
  11345. let exportName = variable.name;
  11346. while (exportsByName[exportName]) {
  11347. exportName = variable.name + '$' + ++nameIndex;
  11348. }
  11349. exportsByName[exportName] = variable;
  11350. exportNamesByVariable.set(variable, [exportName]);
  11351. }
  11352. }
  11353. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  11354. const exportKeys = chunk.getExportNames();
  11355. if (exportMode === 'default') {
  11356. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  11357. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  11358. }
  11359. }
  11360. else if (exportMode === 'none' && exportKeys.length) {
  11361. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  11362. }
  11363. if (exportMode === 'auto') {
  11364. if (exportKeys.length === 0) {
  11365. exportMode = 'none';
  11366. }
  11367. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  11368. if (format === 'cjs' && unsetOptions.has('exports')) {
  11369. warn(errPreferNamedExports(facadeModuleId));
  11370. }
  11371. exportMode = 'default';
  11372. }
  11373. else {
  11374. if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
  11375. warn(errMixedExport(facadeModuleId, name));
  11376. }
  11377. exportMode = 'named';
  11378. }
  11379. }
  11380. return exportMode;
  11381. }
  11382. function guessIndentString(code) {
  11383. const lines = code.split('\n');
  11384. const tabbed = lines.filter(line => /^\t+/.test(line));
  11385. const spaced = lines.filter(line => /^ {2,}/.test(line));
  11386. if (tabbed.length === 0 && spaced.length === 0) {
  11387. return null;
  11388. }
  11389. // More lines tabbed than spaced? Assume tabs, and
  11390. // default to tabs in the case of a tie (or nothing
  11391. // to go on)
  11392. if (tabbed.length >= spaced.length) {
  11393. return '\t';
  11394. }
  11395. // Otherwise, we need to guess the multiple
  11396. const min = spaced.reduce((previous, current) => {
  11397. const numSpaces = /^ +/.exec(current)[0].length;
  11398. return Math.min(numSpaces, previous);
  11399. }, Infinity);
  11400. return new Array(min + 1).join(' ');
  11401. }
  11402. function getIndentString(modules, options) {
  11403. if (options.indent !== true)
  11404. return options.indent;
  11405. for (let i = 0; i < modules.length; i++) {
  11406. const indent = guessIndentString(modules[i].originalCode);
  11407. if (indent !== null)
  11408. return indent;
  11409. }
  11410. return '\t';
  11411. }
  11412. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  11413. const staticDependencyBlocks = [];
  11414. const handledDependencies = new Set();
  11415. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  11416. const module = orderedModules[modulePos];
  11417. if (!handledDependencies.has(module)) {
  11418. const staticDependencies = [];
  11419. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  11420. staticDependencyBlocks.unshift(staticDependencies);
  11421. }
  11422. }
  11423. const dependencies = new Set();
  11424. for (const block of staticDependencyBlocks) {
  11425. for (const dependency of block) {
  11426. dependencies.add(dependency);
  11427. }
  11428. }
  11429. return dependencies;
  11430. }
  11431. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  11432. const dependencies = module.getDependenciesToBeIncluded();
  11433. for (const dependency of dependencies) {
  11434. if (dependency instanceof ExternalModule) {
  11435. staticDependencies.push(dependency);
  11436. continue;
  11437. }
  11438. const dependencyChunk = chunkByModule.get(dependency);
  11439. if (dependencyChunk !== chunk) {
  11440. staticDependencies.push(dependencyChunk);
  11441. continue;
  11442. }
  11443. if (!handledModules.has(dependency)) {
  11444. handledModules.add(dependency);
  11445. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  11446. }
  11447. }
  11448. }
  11449. function decodedSourcemap(map) {
  11450. if (!map)
  11451. return null;
  11452. if (typeof map === 'string') {
  11453. map = JSON.parse(map);
  11454. }
  11455. if (map.mappings === '') {
  11456. return {
  11457. mappings: [],
  11458. names: [],
  11459. sources: [],
  11460. version: 3
  11461. };
  11462. }
  11463. let mappings;
  11464. if (typeof map.mappings === 'string') {
  11465. mappings = decode(map.mappings);
  11466. }
  11467. else {
  11468. mappings = map.mappings;
  11469. }
  11470. return { ...map, mappings };
  11471. }
  11472. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  11473. const renderChunkReducer = (code, result, plugin) => {
  11474. if (result == null)
  11475. return code;
  11476. if (typeof result === 'string')
  11477. result = {
  11478. code: result,
  11479. map: undefined
  11480. };
  11481. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  11482. if (result.map !== null) {
  11483. const map = decodedSourcemap(result.map);
  11484. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  11485. }
  11486. return result.code;
  11487. };
  11488. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  11489. }
  11490. function renderNamePattern(pattern, patternName, replacements) {
  11491. if (isPathFragment(pattern))
  11492. return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
  11493. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  11494. if (!replacements.hasOwnProperty(type)) {
  11495. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  11496. }
  11497. const replacement = replacements[type]();
  11498. if (isPathFragment(replacement))
  11499. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  11500. return replacement;
  11501. });
  11502. }
  11503. function makeUnique(name, existingNames) {
  11504. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  11505. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  11506. return name;
  11507. const ext = path.extname(name);
  11508. name = name.substr(0, name.length - ext.length);
  11509. let uniqueName, uniqueIndex = 1;
  11510. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  11511. ;
  11512. return uniqueName;
  11513. }
  11514. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  11515. function getGlobalName(module, globals, hasExports, warn) {
  11516. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  11517. if (globalName) {
  11518. return globalName;
  11519. }
  11520. if (hasExports) {
  11521. warn({
  11522. code: 'MISSING_GLOBAL_NAME',
  11523. guess: module.variableName,
  11524. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  11525. source: module.id
  11526. });
  11527. return module.variableName;
  11528. }
  11529. }
  11530. class Chunk {
  11531. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  11532. this.orderedModules = orderedModules;
  11533. this.inputOptions = inputOptions;
  11534. this.outputOptions = outputOptions;
  11535. this.unsetOptions = unsetOptions;
  11536. this.pluginDriver = pluginDriver;
  11537. this.modulesById = modulesById;
  11538. this.chunkByModule = chunkByModule;
  11539. this.facadeChunkByModule = facadeChunkByModule;
  11540. this.includedNamespaces = includedNamespaces;
  11541. this.manualChunkAlias = manualChunkAlias;
  11542. this.entryModules = [];
  11543. this.exportMode = 'named';
  11544. this.facadeModule = null;
  11545. this.id = null;
  11546. this.namespaceVariableName = '';
  11547. this.variableName = '';
  11548. this.accessedGlobalsByScope = new Map();
  11549. this.dependencies = new Set();
  11550. this.dynamicDependencies = new Set();
  11551. this.dynamicEntryModules = [];
  11552. this.dynamicName = null;
  11553. this.exportNamesByVariable = new Map();
  11554. this.exports = new Set();
  11555. this.exportsByName = Object.create(null);
  11556. this.fileName = null;
  11557. this.implicitEntryModules = [];
  11558. this.implicitlyLoadedBefore = new Set();
  11559. this.imports = new Set();
  11560. this.indentString = undefined;
  11561. this.isEmpty = true;
  11562. this.name = null;
  11563. this.needsExportsShim = false;
  11564. this.renderedDependencies = null;
  11565. this.renderedExports = null;
  11566. this.renderedHash = undefined;
  11567. this.renderedModuleSources = new Map();
  11568. this.renderedModules = Object.create(null);
  11569. this.renderedSource = null;
  11570. this.sortedExportNames = null;
  11571. this.strictFacade = false;
  11572. this.usedModules = undefined;
  11573. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  11574. const chunkModules = new Set(orderedModules);
  11575. for (const module of orderedModules) {
  11576. if (module.namespace.included) {
  11577. includedNamespaces.add(module);
  11578. }
  11579. if (this.isEmpty && module.isIncluded()) {
  11580. this.isEmpty = false;
  11581. }
  11582. if (module.info.isEntry || outputOptions.preserveModules) {
  11583. this.entryModules.push(module);
  11584. }
  11585. for (const importer of module.includedDynamicImporters) {
  11586. if (!chunkModules.has(importer)) {
  11587. this.dynamicEntryModules.push(module);
  11588. // Modules with synthetic exports need an artificial namespace for dynamic imports
  11589. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  11590. includedNamespaces.add(module);
  11591. this.exports.add(module.namespace);
  11592. }
  11593. }
  11594. }
  11595. if (module.implicitlyLoadedAfter.size > 0) {
  11596. this.implicitEntryModules.push(module);
  11597. }
  11598. }
  11599. this.suggestedVariableName = makeLegal(this.generateVariableName());
  11600. }
  11601. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  11602. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  11603. chunk.assignFacadeName(facadeName, facadedModule);
  11604. if (!facadeChunkByModule.has(facadedModule)) {
  11605. facadeChunkByModule.set(facadedModule, chunk);
  11606. }
  11607. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  11608. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  11609. }
  11610. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  11611. facadedModule.info.hasModuleSideEffects &&
  11612. facadedModule.hasEffects()) {
  11613. chunk.dependencies.add(chunkByModule.get(facadedModule));
  11614. }
  11615. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  11616. chunk.facadeModule = facadedModule;
  11617. chunk.strictFacade = true;
  11618. return chunk;
  11619. }
  11620. canModuleBeFacade(module, exposedVariables) {
  11621. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  11622. for (const exposedVariable of this.exports) {
  11623. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  11624. if (moduleExportNamesByVariable.size === 0 &&
  11625. module.isUserDefinedEntryPoint &&
  11626. module.preserveSignature === 'strict' &&
  11627. this.unsetOptions.has('preserveEntrySignatures')) {
  11628. this.inputOptions.onwarn({
  11629. code: 'EMPTY_FACADE',
  11630. id: module.id,
  11631. 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.`,
  11632. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  11633. });
  11634. }
  11635. return false;
  11636. }
  11637. }
  11638. for (const exposedVariable of exposedVariables) {
  11639. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  11640. return false;
  11641. }
  11642. }
  11643. return true;
  11644. }
  11645. generateExports() {
  11646. this.sortedExportNames = null;
  11647. const remainingExports = new Set(this.exports);
  11648. if (this.facadeModule !== null &&
  11649. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  11650. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  11651. for (const [variable, exportNames] of exportNamesByVariable) {
  11652. this.exportNamesByVariable.set(variable, [...exportNames]);
  11653. for (const exportName of exportNames) {
  11654. this.exportsByName[exportName] = variable;
  11655. }
  11656. remainingExports.delete(variable);
  11657. }
  11658. }
  11659. if (this.outputOptions.minifyInternalExports) {
  11660. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  11661. }
  11662. else {
  11663. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  11664. }
  11665. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  11666. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  11667. }
  11668. generateFacades() {
  11669. var _a;
  11670. const facades = [];
  11671. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  11672. const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
  11673. for (const module of entryModules) {
  11674. if (module.preserveSignature) {
  11675. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  11676. exposedVariables.add(exportedVariable);
  11677. }
  11678. }
  11679. }
  11680. for (const module of entryModules) {
  11681. const requiredFacades = Array.from(module.userChunkNames, name => ({
  11682. name
  11683. }));
  11684. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  11685. requiredFacades.push({});
  11686. }
  11687. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  11688. if (requiredFacades.length === 0) {
  11689. requiredFacades.push({});
  11690. }
  11691. if (!this.facadeModule) {
  11692. const needsStrictFacade = module.preserveSignature === 'strict' ||
  11693. (module.preserveSignature === 'exports-only' &&
  11694. module.getExportNamesByVariable().size !== 0);
  11695. if (!needsStrictFacade ||
  11696. this.outputOptions.preserveModules ||
  11697. this.canModuleBeFacade(module, exposedVariables)) {
  11698. this.facadeModule = module;
  11699. this.facadeChunkByModule.set(module, this);
  11700. if (module.preserveSignature) {
  11701. this.strictFacade = needsStrictFacade;
  11702. }
  11703. this.assignFacadeName(requiredFacades.shift(), module);
  11704. }
  11705. }
  11706. for (const facadeName of requiredFacades) {
  11707. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  11708. }
  11709. }
  11710. for (const module of this.dynamicEntryModules) {
  11711. if (module.info.syntheticNamedExports)
  11712. continue;
  11713. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  11714. this.facadeModule = module;
  11715. this.facadeChunkByModule.set(module, this);
  11716. this.strictFacade = true;
  11717. this.dynamicName = getChunkNameFromModule(module);
  11718. }
  11719. else if (this.facadeModule === module &&
  11720. !this.strictFacade &&
  11721. this.canModuleBeFacade(module, exposedVariables)) {
  11722. this.strictFacade = true;
  11723. }
  11724. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  11725. this.includedNamespaces.add(module);
  11726. this.exports.add(module.namespace);
  11727. }
  11728. }
  11729. return facades;
  11730. }
  11731. generateId(addons, options, existingNames, includeHash) {
  11732. if (this.fileName !== null) {
  11733. return this.fileName;
  11734. }
  11735. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  11736. ? [options.entryFileNames, 'output.entryFileNames']
  11737. : [options.chunkFileNames, 'output.chunkFileNames'];
  11738. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  11739. format: () => options.format,
  11740. hash: () => includeHash
  11741. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  11742. : '[hash]',
  11743. name: () => this.getChunkName()
  11744. }), existingNames);
  11745. }
  11746. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  11747. const id = this.orderedModules[0].id;
  11748. const sanitizedId = this.outputOptions.sanitizeFileName(id);
  11749. let path$1;
  11750. if (isAbsolute(id)) {
  11751. const extension = path.extname(id);
  11752. const pattern = unsetOptions.has('entryFileNames')
  11753. ? '[name][assetExtname].js'
  11754. : options.entryFileNames;
  11755. const currentDir = path.dirname(sanitizedId);
  11756. const fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, 'output.entryFileNames', {
  11757. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  11758. ext: () => extension.substr(1),
  11759. extname: () => extension,
  11760. format: () => options.format,
  11761. name: () => this.getChunkName()
  11762. });
  11763. const currentPath = `${currentDir}/${fileName}`;
  11764. const { preserveModulesRoot } = options;
  11765. if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
  11766. path$1 = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  11767. }
  11768. else {
  11769. path$1 = relative(preserveModulesRelativeDir, currentPath);
  11770. }
  11771. }
  11772. else {
  11773. path$1 = `_virtual/${path.basename(sanitizedId)}`;
  11774. }
  11775. return makeUnique(normalize(path$1), existingNames);
  11776. }
  11777. getChunkInfo() {
  11778. const facadeModule = this.facadeModule;
  11779. const getChunkName = this.getChunkName.bind(this);
  11780. return {
  11781. exports: this.getExportNames(),
  11782. facadeModuleId: facadeModule && facadeModule.id,
  11783. isDynamicEntry: this.dynamicEntryModules.length > 0,
  11784. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  11785. isImplicitEntry: this.implicitEntryModules.length > 0,
  11786. modules: this.renderedModules,
  11787. get name() {
  11788. return getChunkName();
  11789. },
  11790. type: 'chunk'
  11791. };
  11792. }
  11793. getChunkInfoWithFileNames() {
  11794. return Object.assign(this.getChunkInfo(), {
  11795. code: undefined,
  11796. dynamicImports: Array.from(this.dynamicDependencies, getId),
  11797. fileName: this.id,
  11798. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  11799. importedBindings: this.getImportedBindingsPerDependency(),
  11800. imports: Array.from(this.dependencies, getId),
  11801. map: undefined,
  11802. referencedFiles: this.getReferencedFiles()
  11803. });
  11804. }
  11805. getChunkName() {
  11806. return (this.name || (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  11807. }
  11808. getExportNames() {
  11809. return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
  11810. }
  11811. getRenderedHash() {
  11812. if (this.renderedHash)
  11813. return this.renderedHash;
  11814. const hash = createHash();
  11815. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  11816. if (pluginHash) {
  11817. augmentation += pluginHash;
  11818. }
  11819. return augmentation;
  11820. });
  11821. hash.update(hashAugmentation);
  11822. hash.update(this.renderedSource.toString());
  11823. hash.update(this.getExportNames()
  11824. .map(exportName => {
  11825. const variable = this.exportsByName[exportName];
  11826. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  11827. })
  11828. .join(','));
  11829. return (this.renderedHash = hash.digest('hex'));
  11830. }
  11831. getVariableExportName(variable) {
  11832. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  11833. return '*';
  11834. }
  11835. return this.exportNamesByVariable.get(variable)[0];
  11836. }
  11837. link() {
  11838. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  11839. for (const module of this.orderedModules) {
  11840. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  11841. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  11842. this.setUpChunkImportsAndExportsForModule(module);
  11843. }
  11844. }
  11845. // prerender allows chunk hashes and names to be generated before finalizing
  11846. preRender(options, inputBase) {
  11847. const magicString = new Bundle$1({ separator: options.compact ? '' : '\n\n' });
  11848. this.usedModules = [];
  11849. this.indentString = getIndentString(this.orderedModules, options);
  11850. const n = options.compact ? '' : '\n';
  11851. const _ = options.compact ? '' : ' ';
  11852. const renderOptions = {
  11853. compact: options.compact,
  11854. dynamicImportFunction: options.dynamicImportFunction,
  11855. exportNamesByVariable: this.exportNamesByVariable,
  11856. format: options.format,
  11857. freeze: options.freeze,
  11858. indent: this.indentString,
  11859. namespaceToStringTag: options.namespaceToStringTag,
  11860. outputPluginDriver: this.pluginDriver,
  11861. varOrConst: options.preferConst ? 'const' : 'var'
  11862. };
  11863. // for static and dynamic entry points, inline the execution list to avoid loading latency
  11864. if (options.hoistTransitiveImports &&
  11865. !this.outputOptions.preserveModules &&
  11866. this.facadeModule !== null) {
  11867. for (const dep of this.dependencies) {
  11868. if (dep instanceof Chunk)
  11869. this.inlineChunkDependencies(dep);
  11870. }
  11871. }
  11872. this.prepareDynamicImportsAndImportMetas();
  11873. this.setIdentifierRenderResolutions(options);
  11874. let hoistedSource = '';
  11875. const renderedModules = this.renderedModules;
  11876. for (const module of this.orderedModules) {
  11877. let renderedLength = 0;
  11878. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  11879. const source = module.render(renderOptions).trim();
  11880. renderedLength = source.length();
  11881. if (renderedLength) {
  11882. if (options.compact && source.lastLine().indexOf('//') !== -1)
  11883. source.append('\n');
  11884. this.renderedModuleSources.set(module, source);
  11885. magicString.addSource(source);
  11886. this.usedModules.push(module);
  11887. }
  11888. const namespace = module.namespace;
  11889. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  11890. const rendered = namespace.renderBlock(renderOptions);
  11891. if (namespace.renderFirst())
  11892. hoistedSource += n + rendered;
  11893. else
  11894. magicString.addSource(new MagicString$1(rendered));
  11895. }
  11896. }
  11897. const { renderedExports, removedExports } = module.getRenderedExports();
  11898. const { renderedModuleSources } = this;
  11899. renderedModules[module.id] = {
  11900. get code() {
  11901. var _a, _b;
  11902. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  11903. },
  11904. originalLength: module.originalCode.length,
  11905. removedExports,
  11906. renderedExports,
  11907. renderedLength
  11908. };
  11909. }
  11910. if (hoistedSource)
  11911. magicString.prepend(hoistedSource + n + n);
  11912. if (this.needsExportsShim) {
  11913. magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  11914. }
  11915. if (options.compact) {
  11916. this.renderedSource = magicString;
  11917. }
  11918. else {
  11919. this.renderedSource = magicString.trim();
  11920. }
  11921. this.renderedHash = undefined;
  11922. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  11923. const chunkName = this.getChunkName();
  11924. this.inputOptions.onwarn({
  11925. chunkName,
  11926. code: 'EMPTY_BUNDLE',
  11927. message: `Generated an empty chunk: "${chunkName}"`
  11928. });
  11929. }
  11930. this.setExternalRenderPaths(options, inputBase);
  11931. this.renderedDependencies = this.getChunkDependencyDeclarations(options);
  11932. this.renderedExports =
  11933. this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
  11934. }
  11935. async render(options, addons, outputChunk) {
  11936. timeStart('render format', 2);
  11937. const format = options.format;
  11938. const finalise = finalisers[format];
  11939. if (options.dynamicImportFunction && format !== 'es') {
  11940. this.inputOptions.onwarn({
  11941. code: 'INVALID_OPTION',
  11942. message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
  11943. });
  11944. }
  11945. // populate ids in the rendered declarations only here
  11946. // as chunk ids known only after prerender
  11947. for (const dependency of this.dependencies) {
  11948. const renderedDependency = this.renderedDependencies.get(dependency);
  11949. if (dependency instanceof ExternalModule) {
  11950. const originalId = dependency.renderPath;
  11951. renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
  11952. }
  11953. else {
  11954. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  11955. renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
  11956. }
  11957. }
  11958. this.finaliseDynamicImports(options);
  11959. this.finaliseImportMetas(format);
  11960. const hasExports = this.renderedExports.length !== 0 ||
  11961. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  11962. let usesTopLevelAwait = false;
  11963. const accessedGlobals = new Set();
  11964. for (const module of this.orderedModules) {
  11965. if (module.usesTopLevelAwait) {
  11966. usesTopLevelAwait = true;
  11967. }
  11968. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  11969. if (accessedGlobalVariables) {
  11970. for (const name of accessedGlobalVariables) {
  11971. accessedGlobals.add(name);
  11972. }
  11973. }
  11974. }
  11975. if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
  11976. return error({
  11977. code: 'INVALID_TLA_FORMAT',
  11978. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  11979. });
  11980. }
  11981. /* istanbul ignore next */
  11982. if (!this.id) {
  11983. throw new Error('Internal Error: expecting chunk id');
  11984. }
  11985. const magicString = finalise(this.renderedSource, {
  11986. accessedGlobals,
  11987. dependencies: [...this.renderedDependencies.values()],
  11988. exports: this.renderedExports,
  11989. hasExports,
  11990. id: this.id,
  11991. indentString: this.indentString,
  11992. intro: addons.intro,
  11993. isEntryFacade: this.outputOptions.preserveModules ||
  11994. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  11995. isModuleFacade: this.facadeModule !== null,
  11996. namedExportsMode: this.exportMode !== 'default',
  11997. outro: addons.outro,
  11998. usesTopLevelAwait,
  11999. varOrConst: options.preferConst ? 'const' : 'var',
  12000. warn: this.inputOptions.onwarn
  12001. }, options);
  12002. if (addons.banner)
  12003. magicString.prepend(addons.banner);
  12004. if (addons.footer)
  12005. magicString.append(addons.footer);
  12006. const prevCode = magicString.toString();
  12007. timeEnd('render format', 2);
  12008. let map = null;
  12009. const chunkSourcemapChain = [];
  12010. let code = await renderChunk({
  12011. code: prevCode,
  12012. options,
  12013. outputPluginDriver: this.pluginDriver,
  12014. renderChunk: outputChunk,
  12015. sourcemapChain: chunkSourcemapChain
  12016. });
  12017. if (options.sourcemap) {
  12018. timeStart('sourcemap', 2);
  12019. let file;
  12020. if (options.file)
  12021. file = path.resolve(options.sourcemapFile || options.file);
  12022. else if (options.dir)
  12023. file = path.resolve(options.dir, this.id);
  12024. else
  12025. file = path.resolve(this.id);
  12026. const decodedMap = magicString.generateDecodedMap({});
  12027. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  12028. map.sources = map.sources
  12029. .map(sourcePath => {
  12030. const { sourcemapPathTransform } = options;
  12031. if (sourcemapPathTransform) {
  12032. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  12033. if (typeof newSourcePath !== 'string') {
  12034. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  12035. }
  12036. return newSourcePath;
  12037. }
  12038. return sourcePath;
  12039. })
  12040. .map(normalize);
  12041. timeEnd('sourcemap', 2);
  12042. }
  12043. if (!options.compact && code[code.length - 1] !== '\n')
  12044. code += '\n';
  12045. return { code, map };
  12046. }
  12047. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  12048. for (const module of moduleDependencies) {
  12049. if (module instanceof Module) {
  12050. const chunk = this.chunkByModule.get(module);
  12051. if (chunk && chunk !== this) {
  12052. chunkDependencies.add(chunk);
  12053. }
  12054. }
  12055. else {
  12056. chunkDependencies.add(module);
  12057. }
  12058. }
  12059. }
  12060. assignFacadeName({ fileName, name }, facadedModule) {
  12061. if (fileName) {
  12062. this.fileName = fileName;
  12063. }
  12064. else {
  12065. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  12066. }
  12067. }
  12068. checkCircularDependencyImport(variable, importingModule) {
  12069. const variableModule = variable.module;
  12070. if (variableModule instanceof Module) {
  12071. const exportChunk = this.chunkByModule.get(variableModule);
  12072. let alternativeReexportModule;
  12073. do {
  12074. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  12075. if (alternativeReexportModule) {
  12076. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  12077. if (exportingChunk && exportingChunk !== exportChunk) {
  12078. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  12079. }
  12080. importingModule = alternativeReexportModule;
  12081. }
  12082. } while (alternativeReexportModule);
  12083. }
  12084. }
  12085. computeContentHashWithDependencies(addons, options, existingNames) {
  12086. const hash = createHash();
  12087. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
  12088. hash.update(options.format);
  12089. const dependenciesForHashing = new Set([this]);
  12090. for (const current of dependenciesForHashing) {
  12091. if (current instanceof ExternalModule) {
  12092. hash.update(':' + current.renderPath);
  12093. }
  12094. else {
  12095. hash.update(current.getRenderedHash());
  12096. hash.update(current.generateId(addons, options, existingNames, false));
  12097. }
  12098. if (current instanceof ExternalModule)
  12099. continue;
  12100. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  12101. dependenciesForHashing.add(dependency);
  12102. }
  12103. }
  12104. return hash.digest('hex').substr(0, 8);
  12105. }
  12106. ensureReexportsAreAvailableForModule(module) {
  12107. const map = module.getExportNamesByVariable();
  12108. for (const exportedVariable of map.keys()) {
  12109. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  12110. const importedVariable = isSynthetic
  12111. ? exportedVariable.getBaseVariable()
  12112. : exportedVariable;
  12113. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  12114. this.checkCircularDependencyImport(importedVariable, module);
  12115. const exportingModule = importedVariable.module;
  12116. if (exportingModule instanceof Module) {
  12117. const chunk = this.chunkByModule.get(exportingModule);
  12118. if (chunk && chunk !== this) {
  12119. chunk.exports.add(importedVariable);
  12120. if (isSynthetic) {
  12121. this.imports.add(importedVariable);
  12122. }
  12123. }
  12124. }
  12125. }
  12126. }
  12127. }
  12128. finaliseDynamicImports(options) {
  12129. const stripKnownJsExtensions = options.format === 'amd';
  12130. for (const [module, code] of this.renderedModuleSources) {
  12131. for (const { node, resolution } of module.dynamicImports) {
  12132. const chunk = this.chunkByModule.get(resolution);
  12133. const facadeChunk = this.facadeChunkByModule.get(resolution);
  12134. if (!resolution || !node.included || chunk === this) {
  12135. continue;
  12136. }
  12137. const renderedResolution = resolution instanceof Module
  12138. ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
  12139. : resolution instanceof ExternalModule
  12140. ? `'${resolution.renormalizeRenderPath
  12141. ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
  12142. : resolution.renderPath}'`
  12143. : resolution;
  12144. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  12145. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  12146. chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
  12147. }
  12148. }
  12149. }
  12150. finaliseImportMetas(format) {
  12151. for (const [module, code] of this.renderedModuleSources) {
  12152. for (const importMeta of module.importMetas) {
  12153. importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
  12154. }
  12155. }
  12156. }
  12157. generateVariableName() {
  12158. if (this.manualChunkAlias) {
  12159. return this.manualChunkAlias;
  12160. }
  12161. const moduleForNaming = this.entryModules[0] ||
  12162. this.implicitEntryModules[0] ||
  12163. this.dynamicEntryModules[0] ||
  12164. this.orderedModules[this.orderedModules.length - 1];
  12165. if (moduleForNaming) {
  12166. return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
  12167. }
  12168. return 'chunk';
  12169. }
  12170. getChunkDependencyDeclarations(options) {
  12171. const importSpecifiers = this.getImportSpecifiers();
  12172. const reexportSpecifiers = this.getReexportSpecifiers();
  12173. const dependencyDeclaration = new Map();
  12174. for (const dep of this.dependencies) {
  12175. const imports = importSpecifiers.get(dep) || null;
  12176. const reexports = reexportSpecifiers.get(dep) || null;
  12177. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  12178. dependencyDeclaration.set(dep, {
  12179. defaultVariableName: dep.defaultVariableName,
  12180. globalName: (dep instanceof ExternalModule &&
  12181. (options.format === 'umd' || options.format === 'iife') &&
  12182. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  12183. id: undefined,
  12184. imports,
  12185. isChunk: dep instanceof Chunk,
  12186. name: dep.variableName,
  12187. namedExportsMode,
  12188. namespaceVariableName: dep.namespaceVariableName,
  12189. reexports
  12190. });
  12191. }
  12192. return dependencyDeclaration;
  12193. }
  12194. getChunkExportDeclarations(format) {
  12195. const exports = [];
  12196. for (const exportName of this.getExportNames()) {
  12197. if (exportName[0] === '*')
  12198. continue;
  12199. const variable = this.exportsByName[exportName];
  12200. if (!(variable instanceof SyntheticNamedExportVariable)) {
  12201. const module = variable.module;
  12202. if (module && this.chunkByModule.get(module) !== this)
  12203. continue;
  12204. }
  12205. let expression = null;
  12206. let hoisted = false;
  12207. let local = variable.getName();
  12208. if (variable instanceof LocalVariable) {
  12209. for (const declaration of variable.declarations) {
  12210. if (declaration.parent instanceof FunctionDeclaration ||
  12211. (declaration instanceof ExportDefaultDeclaration &&
  12212. declaration.declaration instanceof FunctionDeclaration)) {
  12213. hoisted = true;
  12214. break;
  12215. }
  12216. }
  12217. }
  12218. else if (variable instanceof SyntheticNamedExportVariable) {
  12219. expression = local;
  12220. if (format === 'es') {
  12221. local = variable.renderName;
  12222. }
  12223. }
  12224. exports.push({
  12225. exported: exportName,
  12226. expression,
  12227. hoisted,
  12228. local
  12229. });
  12230. }
  12231. return exports;
  12232. }
  12233. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  12234. const dependencies = new Set();
  12235. const deconflictedDefault = new Set();
  12236. const deconflictedNamespace = new Set();
  12237. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  12238. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  12239. const module = variable.module;
  12240. if (module instanceof ExternalModule) {
  12241. dependencies.add(module);
  12242. if (addNonNamespacesAndInteropHelpers) {
  12243. if (variable.name === 'default') {
  12244. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  12245. deconflictedDefault.add(module);
  12246. }
  12247. }
  12248. else if (variable.name === '*') {
  12249. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  12250. deconflictedNamespace.add(module);
  12251. }
  12252. }
  12253. }
  12254. }
  12255. else {
  12256. const chunk = this.chunkByModule.get(module);
  12257. if (chunk !== this) {
  12258. dependencies.add(chunk);
  12259. if (addNonNamespacesAndInteropHelpers &&
  12260. chunk.exportMode === 'default' &&
  12261. variable.isNamespace) {
  12262. deconflictedNamespace.add(chunk);
  12263. }
  12264. }
  12265. }
  12266. }
  12267. }
  12268. if (addDependenciesWithoutBindings) {
  12269. for (const dependency of this.dependencies) {
  12270. dependencies.add(dependency);
  12271. }
  12272. }
  12273. return { deconflictedDefault, deconflictedNamespace, dependencies };
  12274. }
  12275. getFallbackChunkName() {
  12276. if (this.manualChunkAlias) {
  12277. return this.manualChunkAlias;
  12278. }
  12279. if (this.dynamicName) {
  12280. return this.dynamicName;
  12281. }
  12282. if (this.fileName) {
  12283. return getAliasName(this.fileName);
  12284. }
  12285. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  12286. }
  12287. getImportSpecifiers() {
  12288. const { interop } = this.outputOptions;
  12289. const importsByDependency = new Map();
  12290. for (const variable of this.imports) {
  12291. const module = variable.module;
  12292. let dependency;
  12293. let imported;
  12294. if (module instanceof ExternalModule) {
  12295. dependency = module;
  12296. imported = variable.name;
  12297. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  12298. return error(errUnexpectedNamedImport(module.id, imported, false));
  12299. }
  12300. }
  12301. else {
  12302. dependency = this.chunkByModule.get(module);
  12303. imported = dependency.getVariableExportName(variable);
  12304. }
  12305. getOrCreate(importsByDependency, dependency, () => []).push({
  12306. imported,
  12307. local: variable.getName()
  12308. });
  12309. }
  12310. return importsByDependency;
  12311. }
  12312. getImportedBindingsPerDependency() {
  12313. const importSpecifiers = {};
  12314. for (const [dependency, declaration] of this.renderedDependencies) {
  12315. const specifiers = new Set();
  12316. if (declaration.imports) {
  12317. for (const { imported } of declaration.imports) {
  12318. specifiers.add(imported);
  12319. }
  12320. }
  12321. if (declaration.reexports) {
  12322. for (const { imported } of declaration.reexports) {
  12323. specifiers.add(imported);
  12324. }
  12325. }
  12326. importSpecifiers[dependency.id] = [...specifiers];
  12327. }
  12328. return importSpecifiers;
  12329. }
  12330. getReexportSpecifiers() {
  12331. const { externalLiveBindings, interop } = this.outputOptions;
  12332. const reexportSpecifiers = new Map();
  12333. for (let exportName of this.getExportNames()) {
  12334. let dependency;
  12335. let imported;
  12336. let needsLiveBinding = false;
  12337. if (exportName[0] === '*') {
  12338. const id = exportName.substr(1);
  12339. if (interop(id) === 'defaultOnly') {
  12340. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  12341. }
  12342. needsLiveBinding = externalLiveBindings;
  12343. dependency = this.modulesById.get(id);
  12344. imported = exportName = '*';
  12345. }
  12346. else {
  12347. const variable = this.exportsByName[exportName];
  12348. if (variable instanceof SyntheticNamedExportVariable)
  12349. continue;
  12350. const module = variable.module;
  12351. if (module instanceof Module) {
  12352. dependency = this.chunkByModule.get(module);
  12353. if (dependency === this)
  12354. continue;
  12355. imported = dependency.getVariableExportName(variable);
  12356. needsLiveBinding = variable.isReassigned;
  12357. }
  12358. else {
  12359. dependency = module;
  12360. imported = variable.name;
  12361. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  12362. return error(errUnexpectedNamedImport(module.id, imported, true));
  12363. }
  12364. needsLiveBinding =
  12365. externalLiveBindings &&
  12366. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  12367. }
  12368. }
  12369. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  12370. imported,
  12371. needsLiveBinding,
  12372. reexported: exportName
  12373. });
  12374. }
  12375. return reexportSpecifiers;
  12376. }
  12377. getReferencedFiles() {
  12378. const referencedFiles = [];
  12379. for (const module of this.orderedModules) {
  12380. for (const meta of module.importMetas) {
  12381. const fileName = meta.getReferencedFileName(this.pluginDriver);
  12382. if (fileName) {
  12383. referencedFiles.push(fileName);
  12384. }
  12385. }
  12386. }
  12387. return referencedFiles;
  12388. }
  12389. getRelativePath(targetPath, stripJsExtension) {
  12390. let relativePath = normalize(relative(path.dirname(this.id), targetPath));
  12391. if (stripJsExtension && relativePath.endsWith('.js')) {
  12392. relativePath = relativePath.slice(0, -3);
  12393. }
  12394. if (relativePath === '..')
  12395. return '../../' + path.basename(targetPath);
  12396. if (relativePath === '')
  12397. return '../' + path.basename(targetPath);
  12398. return relativePath.startsWith('../') ? relativePath : './' + relativePath;
  12399. }
  12400. inlineChunkDependencies(chunk) {
  12401. for (const dep of chunk.dependencies) {
  12402. if (this.dependencies.has(dep))
  12403. continue;
  12404. this.dependencies.add(dep);
  12405. if (dep instanceof Chunk) {
  12406. this.inlineChunkDependencies(dep);
  12407. }
  12408. }
  12409. }
  12410. prepareDynamicImportsAndImportMetas() {
  12411. var _a;
  12412. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  12413. for (const module of this.orderedModules) {
  12414. for (const { node, resolution } of module.dynamicImports) {
  12415. if (node.included) {
  12416. if (resolution instanceof Module) {
  12417. const chunk = this.chunkByModule.get(resolution);
  12418. if (chunk === this) {
  12419. node.setInternalResolution(resolution.namespace);
  12420. }
  12421. else {
  12422. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  12423. }
  12424. }
  12425. else {
  12426. node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  12427. }
  12428. }
  12429. }
  12430. for (const importMeta of module.importMetas) {
  12431. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  12432. }
  12433. }
  12434. }
  12435. setExternalRenderPaths(options, inputBase) {
  12436. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  12437. if (dependency instanceof ExternalModule) {
  12438. dependency.setRenderPath(options, inputBase);
  12439. }
  12440. }
  12441. }
  12442. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  12443. const syntheticExports = new Set();
  12444. for (const exportName of this.getExportNames()) {
  12445. const exportVariable = this.exportsByName[exportName];
  12446. if (exportVariable instanceof ExportShimVariable) {
  12447. this.needsExportsShim = true;
  12448. }
  12449. if (format !== 'es' &&
  12450. format !== 'system' &&
  12451. exportVariable.isReassigned &&
  12452. !exportVariable.isId) {
  12453. exportVariable.setRenderNames('exports', exportName);
  12454. }
  12455. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  12456. syntheticExports.add(exportVariable);
  12457. }
  12458. else {
  12459. exportVariable.setRenderNames(null, null);
  12460. }
  12461. }
  12462. const usedNames = new Set(['Object', 'Promise']);
  12463. if (this.needsExportsShim) {
  12464. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  12465. }
  12466. if (namespaceToStringTag) {
  12467. usedNames.add('Symbol');
  12468. }
  12469. switch (format) {
  12470. case 'system':
  12471. usedNames.add('module').add('exports');
  12472. break;
  12473. case 'es':
  12474. break;
  12475. case 'cjs':
  12476. usedNames.add('module').add('require').add('__filename').add('__dirname');
  12477. // fallthrough
  12478. default:
  12479. usedNames.add('exports');
  12480. for (const helper of HELPER_NAMES) {
  12481. usedNames.add(helper);
  12482. }
  12483. }
  12484. 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);
  12485. }
  12486. setUpChunkImportsAndExportsForModule(module) {
  12487. const moduleImports = new Set(module.imports);
  12488. // when we are not preserving modules, we need to make all namespace variables available for
  12489. // rendering the namespace object
  12490. if (!this.outputOptions.preserveModules) {
  12491. if (this.includedNamespaces.has(module)) {
  12492. const memberVariables = module.namespace.getMemberVariables();
  12493. for (const variable of Object.values(memberVariables)) {
  12494. moduleImports.add(variable);
  12495. }
  12496. }
  12497. }
  12498. for (let variable of moduleImports) {
  12499. if (variable instanceof ExportDefaultVariable) {
  12500. variable = variable.getOriginalVariable();
  12501. }
  12502. if (variable instanceof SyntheticNamedExportVariable) {
  12503. variable = variable.getBaseVariable();
  12504. }
  12505. const chunk = this.chunkByModule.get(variable.module);
  12506. if (chunk !== this) {
  12507. this.imports.add(variable);
  12508. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  12509. variable.module instanceof Module) {
  12510. chunk.exports.add(variable);
  12511. this.checkCircularDependencyImport(variable, module);
  12512. }
  12513. }
  12514. }
  12515. if (this.includedNamespaces.has(module) ||
  12516. (module.info.isEntry && module.preserveSignature !== false) ||
  12517. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  12518. this.ensureReexportsAreAvailableForModule(module);
  12519. }
  12520. for (const { node, resolution } of module.dynamicImports) {
  12521. if (node.included &&
  12522. resolution instanceof Module &&
  12523. this.chunkByModule.get(resolution) === this &&
  12524. !this.includedNamespaces.has(resolution)) {
  12525. this.includedNamespaces.add(resolution);
  12526. this.ensureReexportsAreAvailableForModule(resolution);
  12527. }
  12528. }
  12529. }
  12530. }
  12531. function getChunkNameFromModule(module) {
  12532. return module.chunkName || getAliasName(module.id);
  12533. }
  12534. var BuildPhase;
  12535. (function (BuildPhase) {
  12536. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12537. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12538. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12539. })(BuildPhase || (BuildPhase = {}));
  12540. function generateAssetFileName(name, source, outputOptions, bundle) {
  12541. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  12542. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  12543. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  12544. : outputOptions.assetFileNames, 'output.assetFileNames', {
  12545. ext: () => path.extname(emittedName).substr(1),
  12546. extname: () => path.extname(emittedName),
  12547. hash() {
  12548. const hash = createHash();
  12549. hash.update(emittedName);
  12550. hash.update(':');
  12551. hash.update(source);
  12552. return hash.digest('hex').substr(0, 8);
  12553. },
  12554. name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
  12555. }), bundle);
  12556. }
  12557. function reserveFileNameInBundle(fileName, bundle, warn) {
  12558. if (fileName in bundle) {
  12559. warn(errFileNameConflict(fileName));
  12560. }
  12561. bundle[fileName] = FILE_PLACEHOLDER;
  12562. }
  12563. const FILE_PLACEHOLDER = {
  12564. type: 'placeholder'
  12565. };
  12566. function hasValidType(emittedFile) {
  12567. return Boolean(emittedFile &&
  12568. (emittedFile.type === 'asset' ||
  12569. emittedFile.type === 'chunk'));
  12570. }
  12571. function hasValidName(emittedFile) {
  12572. const validatedName = emittedFile.fileName || emittedFile.name;
  12573. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  12574. }
  12575. function getValidSource(source, emittedFile, fileReferenceId) {
  12576. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  12577. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  12578. 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.`));
  12579. }
  12580. return source;
  12581. }
  12582. function getAssetFileName(file, referenceId) {
  12583. if (typeof file.fileName !== 'string') {
  12584. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  12585. }
  12586. return file.fileName;
  12587. }
  12588. function getChunkFileName(file, facadeChunkByModule) {
  12589. var _a;
  12590. 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));
  12591. if (!fileName)
  12592. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  12593. return fileName;
  12594. }
  12595. class FileEmitter {
  12596. constructor(graph, options, baseFileEmitter) {
  12597. this.graph = graph;
  12598. this.options = options;
  12599. this.bundle = null;
  12600. this.facadeChunkByModule = null;
  12601. this.outputOptions = null;
  12602. this.assertAssetsFinalized = () => {
  12603. for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
  12604. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  12605. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  12606. }
  12607. };
  12608. this.emitFile = (emittedFile) => {
  12609. if (!hasValidType(emittedFile)) {
  12610. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  12611. }
  12612. if (!hasValidName(emittedFile)) {
  12613. 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}".`));
  12614. }
  12615. if (emittedFile.type === 'chunk') {
  12616. return this.emitChunk(emittedFile);
  12617. }
  12618. else {
  12619. return this.emitAsset(emittedFile);
  12620. }
  12621. };
  12622. this.getFileName = (fileReferenceId) => {
  12623. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  12624. if (!emittedFile)
  12625. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  12626. if (emittedFile.type === 'chunk') {
  12627. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  12628. }
  12629. else {
  12630. return getAssetFileName(emittedFile, fileReferenceId);
  12631. }
  12632. };
  12633. this.setAssetSource = (referenceId, requestedSource) => {
  12634. const consumedFile = this.filesByReferenceId.get(referenceId);
  12635. if (!consumedFile)
  12636. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  12637. if (consumedFile.type !== 'asset') {
  12638. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  12639. }
  12640. if (consumedFile.source !== undefined) {
  12641. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  12642. }
  12643. const source = getValidSource(requestedSource, consumedFile, referenceId);
  12644. if (this.bundle) {
  12645. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  12646. }
  12647. else {
  12648. consumedFile.source = source;
  12649. }
  12650. };
  12651. this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
  12652. this.outputOptions = outputOptions;
  12653. this.bundle = outputBundle;
  12654. this.facadeChunkByModule = facadeChunkByModule;
  12655. for (const emittedFile of this.filesByReferenceId.values()) {
  12656. if (emittedFile.fileName) {
  12657. reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
  12658. }
  12659. }
  12660. for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
  12661. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  12662. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
  12663. }
  12664. }
  12665. };
  12666. this.filesByReferenceId = baseFileEmitter
  12667. ? new Map(baseFileEmitter.filesByReferenceId)
  12668. : new Map();
  12669. }
  12670. assignReferenceId(file, idBase) {
  12671. let referenceId;
  12672. do {
  12673. const hash = createHash();
  12674. if (referenceId) {
  12675. hash.update(referenceId);
  12676. }
  12677. else {
  12678. hash.update(idBase);
  12679. }
  12680. referenceId = hash.digest('hex').substr(0, 8);
  12681. } while (this.filesByReferenceId.has(referenceId));
  12682. this.filesByReferenceId.set(referenceId, file);
  12683. return referenceId;
  12684. }
  12685. emitAsset(emittedAsset) {
  12686. const source = typeof emittedAsset.source !== 'undefined'
  12687. ? getValidSource(emittedAsset.source, emittedAsset, null)
  12688. : undefined;
  12689. const consumedAsset = {
  12690. fileName: emittedAsset.fileName,
  12691. name: emittedAsset.name,
  12692. source,
  12693. type: 'asset'
  12694. };
  12695. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  12696. if (this.bundle) {
  12697. if (emittedAsset.fileName) {
  12698. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  12699. }
  12700. if (source !== undefined) {
  12701. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  12702. }
  12703. }
  12704. return referenceId;
  12705. }
  12706. emitChunk(emittedChunk) {
  12707. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  12708. return error(errInvalidRollupPhaseForChunkEmission());
  12709. }
  12710. if (typeof emittedChunk.id !== 'string') {
  12711. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  12712. }
  12713. const consumedChunk = {
  12714. fileName: emittedChunk.fileName,
  12715. module: null,
  12716. name: emittedChunk.name || emittedChunk.id,
  12717. type: 'chunk'
  12718. };
  12719. this.graph.moduleLoader
  12720. .emitChunk(emittedChunk)
  12721. .then(module => (consumedChunk.module = module))
  12722. .catch(() => {
  12723. // Avoid unhandled Promise rejection as the error will be thrown later
  12724. // once module loading has finished
  12725. });
  12726. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  12727. }
  12728. finalizeAsset(consumedFile, source, referenceId, bundle) {
  12729. const fileName = consumedFile.fileName ||
  12730. findExistingAssetFileNameWithSource(bundle, source) ||
  12731. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  12732. // We must not modify the original assets to avoid interaction between outputs
  12733. const assetWithFileName = { ...consumedFile, fileName, source };
  12734. this.filesByReferenceId.set(referenceId, assetWithFileName);
  12735. const { options } = this;
  12736. bundle[fileName] = {
  12737. fileName,
  12738. get isAsset() {
  12739. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  12740. return true;
  12741. },
  12742. name: consumedFile.name,
  12743. source,
  12744. type: 'asset'
  12745. };
  12746. }
  12747. }
  12748. function findExistingAssetFileNameWithSource(bundle, source) {
  12749. for (const [fileName, outputFile] of Object.entries(bundle)) {
  12750. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  12751. return fileName;
  12752. }
  12753. return null;
  12754. }
  12755. function areSourcesEqual(sourceA, sourceB) {
  12756. if (typeof sourceA === 'string') {
  12757. return sourceA === sourceB;
  12758. }
  12759. if (typeof sourceB === 'string') {
  12760. return false;
  12761. }
  12762. if ('equals' in sourceA) {
  12763. return sourceA.equals(sourceB);
  12764. }
  12765. if (sourceA.length !== sourceB.length) {
  12766. return false;
  12767. }
  12768. for (let index = 0; index < sourceA.length; index++) {
  12769. if (sourceA[index] !== sourceB[index]) {
  12770. return false;
  12771. }
  12772. }
  12773. return true;
  12774. }
  12775. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  12776. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  12777. async function createAddons(options, outputPluginDriver) {
  12778. try {
  12779. let [banner, footer, intro, outro] = await Promise.all([
  12780. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  12781. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  12782. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  12783. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  12784. ]);
  12785. if (intro)
  12786. intro += '\n\n';
  12787. if (outro)
  12788. outro = `\n\n${outro}`;
  12789. if (banner.length)
  12790. banner += '\n';
  12791. if (footer.length)
  12792. footer = '\n' + footer;
  12793. return { banner, footer, intro, outro };
  12794. }
  12795. catch (err) {
  12796. return error({
  12797. code: 'ADDON_ERROR',
  12798. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  12799. \tError Message: ${err.message}`
  12800. });
  12801. }
  12802. }
  12803. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  12804. const chunkDefinitions = [];
  12805. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  12806. const manualChunkModulesByAlias = Object.create(null);
  12807. for (const [entry, alias] of manualChunkAliasByEntry) {
  12808. const chunkModules = (manualChunkModulesByAlias[alias] =
  12809. manualChunkModulesByAlias[alias] || []);
  12810. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  12811. }
  12812. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  12813. chunkDefinitions.push({ alias, modules });
  12814. }
  12815. const assignedEntryPointsByModule = new Map();
  12816. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  12817. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  12818. const staticEntries = new Set(entryModules);
  12819. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  12820. const modulesToHandle = new Set([entry]);
  12821. for (const module of modulesToHandle) {
  12822. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  12823. if (dynamicDependentEntryPoints &&
  12824. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  12825. continue;
  12826. }
  12827. else {
  12828. assignedEntryPoints.add(entry);
  12829. }
  12830. for (const dependency of module.getDependenciesToBeIncluded()) {
  12831. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  12832. modulesToHandle.add(dependency);
  12833. }
  12834. }
  12835. }
  12836. }
  12837. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  12838. const entriesToCheck = new Set(entryPoints);
  12839. for (const entry of entriesToCheck) {
  12840. if (!containedIn.has(entry)) {
  12841. if (staticEntries.has(entry))
  12842. return false;
  12843. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  12844. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  12845. entriesToCheck.add(dependentEntry);
  12846. }
  12847. }
  12848. }
  12849. return true;
  12850. }
  12851. for (const entry of entryModules) {
  12852. if (!modulesInManualChunks.has(entry)) {
  12853. assignEntryToStaticDependencies(entry, null);
  12854. }
  12855. }
  12856. for (const entry of dynamicEntryModules) {
  12857. if (!modulesInManualChunks.has(entry)) {
  12858. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  12859. }
  12860. }
  12861. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  12862. return chunkDefinitions;
  12863. }
  12864. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  12865. const modulesToHandle = new Set([entry]);
  12866. for (const module of modulesToHandle) {
  12867. modulesInManualChunks.add(module);
  12868. manualChunkModules.push(module);
  12869. for (const dependency of module.dependencies) {
  12870. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  12871. modulesToHandle.add(dependency);
  12872. }
  12873. }
  12874. }
  12875. }
  12876. function analyzeModuleGraph(entryModules) {
  12877. const dynamicEntryModules = new Set();
  12878. const dependentEntryPointsByModule = new Map();
  12879. const entriesToHandle = new Set(entryModules);
  12880. for (const currentEntry of entriesToHandle) {
  12881. const modulesToHandle = new Set([currentEntry]);
  12882. for (const module of modulesToHandle) {
  12883. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  12884. for (const dependency of module.getDependenciesToBeIncluded()) {
  12885. if (!(dependency instanceof ExternalModule)) {
  12886. modulesToHandle.add(dependency);
  12887. }
  12888. }
  12889. for (const { resolution } of module.dynamicImports) {
  12890. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  12891. dynamicEntryModules.add(resolution);
  12892. entriesToHandle.add(resolution);
  12893. }
  12894. }
  12895. for (const dependency of module.implicitlyLoadedBefore) {
  12896. dynamicEntryModules.add(dependency);
  12897. entriesToHandle.add(dependency);
  12898. }
  12899. }
  12900. }
  12901. return { dependentEntryPointsByModule, dynamicEntryModules };
  12902. }
  12903. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  12904. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  12905. for (const dynamicEntry of dynamicEntryModules) {
  12906. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  12907. for (const importer of [
  12908. ...dynamicEntry.includedDynamicImporters,
  12909. ...dynamicEntry.implicitlyLoadedAfter
  12910. ]) {
  12911. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  12912. dynamicDependentEntryPoints.add(entryPoint);
  12913. }
  12914. }
  12915. }
  12916. return dynamicallyDependentEntryPointsByDynamicEntry;
  12917. }
  12918. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  12919. const chunkModules = Object.create(null);
  12920. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  12921. let chunkSignature = '';
  12922. for (const entry of allEntryPoints) {
  12923. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  12924. }
  12925. const chunk = chunkModules[chunkSignature];
  12926. if (chunk) {
  12927. chunk.push(module);
  12928. }
  12929. else {
  12930. chunkModules[chunkSignature] = [module];
  12931. }
  12932. }
  12933. return Object.values(chunkModules).map(modules => ({
  12934. alias: null,
  12935. modules
  12936. }));
  12937. }
  12938. // ported from https://github.com/substack/node-commondir
  12939. function commondir(files) {
  12940. if (files.length === 0)
  12941. return '/';
  12942. if (files.length === 1)
  12943. return path.dirname(files[0]);
  12944. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  12945. const pathSegements = file.split(/\/+|\\+/);
  12946. let i;
  12947. for (i = 0; commonSegments[i] === pathSegements[i] &&
  12948. i < Math.min(commonSegments.length, pathSegements.length); i++)
  12949. ;
  12950. return commonSegments.slice(0, i);
  12951. }, files[0].split(/\/+|\\+/));
  12952. // Windows correctly handles paths with forward-slashes
  12953. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  12954. }
  12955. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  12956. function sortByExecutionOrder(units) {
  12957. units.sort(compareExecIndex);
  12958. }
  12959. function analyseModuleExecution(entryModules) {
  12960. let nextExecIndex = 0;
  12961. const cyclePaths = [];
  12962. const analysedModules = new Set();
  12963. const dynamicImports = new Set();
  12964. const parents = new Map();
  12965. const orderedModules = [];
  12966. const analyseModule = (module) => {
  12967. if (module instanceof Module) {
  12968. for (const dependency of module.dependencies) {
  12969. if (parents.has(dependency)) {
  12970. if (!analysedModules.has(dependency)) {
  12971. cyclePaths.push(getCyclePath(dependency, module, parents));
  12972. }
  12973. continue;
  12974. }
  12975. parents.set(dependency, module);
  12976. analyseModule(dependency);
  12977. }
  12978. for (const dependency of module.implicitlyLoadedBefore) {
  12979. dynamicImports.add(dependency);
  12980. }
  12981. for (const { resolution } of module.dynamicImports) {
  12982. if (resolution instanceof Module) {
  12983. dynamicImports.add(resolution);
  12984. }
  12985. }
  12986. orderedModules.push(module);
  12987. }
  12988. module.execIndex = nextExecIndex++;
  12989. analysedModules.add(module);
  12990. };
  12991. for (const curEntry of entryModules) {
  12992. if (!parents.has(curEntry)) {
  12993. parents.set(curEntry, null);
  12994. analyseModule(curEntry);
  12995. }
  12996. }
  12997. for (const curEntry of dynamicImports) {
  12998. if (!parents.has(curEntry)) {
  12999. parents.set(curEntry, null);
  13000. analyseModule(curEntry);
  13001. }
  13002. }
  13003. return { cyclePaths, orderedModules };
  13004. }
  13005. function getCyclePath(module, parent, parents) {
  13006. const cycleSymbol = Symbol(module.id);
  13007. const path = [relativeId(module.id)];
  13008. let nextModule = parent;
  13009. module.cycles.add(cycleSymbol);
  13010. while (nextModule !== module) {
  13011. nextModule.cycles.add(cycleSymbol);
  13012. path.push(relativeId(nextModule.id));
  13013. nextModule = parents.get(nextModule);
  13014. }
  13015. path.push(path[0]);
  13016. path.reverse();
  13017. return path;
  13018. }
  13019. class Bundle {
  13020. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  13021. this.outputOptions = outputOptions;
  13022. this.unsetOptions = unsetOptions;
  13023. this.inputOptions = inputOptions;
  13024. this.pluginDriver = pluginDriver;
  13025. this.graph = graph;
  13026. this.facadeChunkByModule = new Map();
  13027. this.includedNamespaces = new Set();
  13028. }
  13029. async generate(isWrite) {
  13030. timeStart('GENERATE', 1);
  13031. const outputBundle = Object.create(null);
  13032. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  13033. try {
  13034. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  13035. timeStart('generate chunks', 2);
  13036. const chunks = await this.generateChunks();
  13037. if (chunks.length > 1) {
  13038. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  13039. }
  13040. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  13041. timeEnd('generate chunks', 2);
  13042. timeStart('render modules', 2);
  13043. // We need to create addons before prerender because at the moment, there
  13044. // can be no async code between prerender and render due to internal state
  13045. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  13046. this.prerenderChunks(chunks, inputBase);
  13047. timeEnd('render modules', 2);
  13048. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
  13049. }
  13050. catch (error) {
  13051. await this.pluginDriver.hookParallel('renderError', [error]);
  13052. throw error;
  13053. }
  13054. await this.pluginDriver.hookSeq('generateBundle', [
  13055. this.outputOptions,
  13056. outputBundle,
  13057. isWrite
  13058. ]);
  13059. this.finaliseAssets(outputBundle);
  13060. timeEnd('GENERATE', 1);
  13061. return outputBundle;
  13062. }
  13063. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
  13064. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  13065. for (const chunk of chunks) {
  13066. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  13067. }
  13068. await Promise.all(chunks.map(async (chunk) => {
  13069. const outputChunk = outputBundle[chunk.id];
  13070. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
  13071. }));
  13072. }
  13073. async addManualChunks(manualChunks) {
  13074. const manualChunkAliasByEntry = new Map();
  13075. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  13076. alias,
  13077. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  13078. })));
  13079. for (const { alias, entries } of chunkEntries) {
  13080. for (const entry of entries) {
  13081. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  13082. }
  13083. }
  13084. return manualChunkAliasByEntry;
  13085. }
  13086. assignChunkIds(chunks, inputBase, addons, bundle) {
  13087. const entryChunks = [];
  13088. const otherChunks = [];
  13089. for (const chunk of chunks) {
  13090. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  13091. ? entryChunks
  13092. : otherChunks).push(chunk);
  13093. }
  13094. // make sure entry chunk names take precedence with regard to deconflicting
  13095. const chunksForNaming = entryChunks.concat(otherChunks);
  13096. for (const chunk of chunksForNaming) {
  13097. if (this.outputOptions.file) {
  13098. chunk.id = path.basename(this.outputOptions.file);
  13099. }
  13100. else if (this.outputOptions.preserveModules) {
  13101. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  13102. }
  13103. else {
  13104. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  13105. }
  13106. bundle[chunk.id] = FILE_PLACEHOLDER;
  13107. }
  13108. }
  13109. assignManualChunks(getManualChunk) {
  13110. const manualChunkAliasByEntry = new Map();
  13111. const manualChunksApi = {
  13112. getModuleIds: () => this.graph.modulesById.keys(),
  13113. getModuleInfo: this.graph.getModuleInfo
  13114. };
  13115. for (const module of this.graph.modulesById.values()) {
  13116. if (module instanceof Module) {
  13117. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  13118. if (typeof manualChunkAlias === 'string') {
  13119. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  13120. }
  13121. }
  13122. }
  13123. return manualChunkAliasByEntry;
  13124. }
  13125. finaliseAssets(outputBundle) {
  13126. for (const file of Object.values(outputBundle)) {
  13127. if (!file.type) {
  13128. 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);
  13129. file.type = 'asset';
  13130. }
  13131. if (this.outputOptions.validate && typeof file.code == 'string') {
  13132. try {
  13133. this.graph.contextParse(file.code, {
  13134. allowHashBang: true,
  13135. ecmaVersion: 'latest'
  13136. });
  13137. }
  13138. catch (exception) {
  13139. this.inputOptions.onwarn(errChunkInvalid(file, exception));
  13140. }
  13141. }
  13142. }
  13143. this.pluginDriver.finaliseAssets();
  13144. }
  13145. async generateChunks() {
  13146. const { manualChunks } = this.outputOptions;
  13147. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  13148. ? await this.addManualChunks(manualChunks)
  13149. : this.assignManualChunks(manualChunks);
  13150. const chunks = [];
  13151. const chunkByModule = new Map();
  13152. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  13153. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  13154. : this.outputOptions.preserveModules
  13155. ? getIncludedModules(this.graph.modulesById).map(module => ({
  13156. alias: null,
  13157. modules: [module]
  13158. }))
  13159. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  13160. sortByExecutionOrder(modules);
  13161. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  13162. chunks.push(chunk);
  13163. for (const module of modules) {
  13164. chunkByModule.set(module, chunk);
  13165. }
  13166. }
  13167. for (const chunk of chunks) {
  13168. chunk.link();
  13169. }
  13170. const facades = [];
  13171. for (const chunk of chunks) {
  13172. facades.push(...chunk.generateFacades());
  13173. }
  13174. return [...chunks, ...facades];
  13175. }
  13176. prerenderChunks(chunks, inputBase) {
  13177. for (const chunk of chunks) {
  13178. chunk.generateExports();
  13179. }
  13180. for (const chunk of chunks) {
  13181. chunk.preRender(this.outputOptions, inputBase);
  13182. }
  13183. }
  13184. }
  13185. function getAbsoluteEntryModulePaths(chunks) {
  13186. const absoluteEntryModulePaths = [];
  13187. for (const chunk of chunks) {
  13188. for (const entryModule of chunk.entryModules) {
  13189. if (isAbsolute(entryModule.id)) {
  13190. absoluteEntryModulePaths.push(entryModule.id);
  13191. }
  13192. }
  13193. }
  13194. return absoluteEntryModulePaths;
  13195. }
  13196. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  13197. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  13198. return error({
  13199. code: 'INVALID_OPTION',
  13200. message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
  13201. });
  13202. if (typeof outputOptions.file === 'string')
  13203. return error({
  13204. code: 'INVALID_OPTION',
  13205. message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
  13206. 'To inline dynamic imports, set the "inlineDynamicImports" option.'
  13207. });
  13208. if (outputOptions.sourcemapFile)
  13209. return error({
  13210. code: 'INVALID_OPTION',
  13211. message: '"output.sourcemapFile" is only supported for single-file builds.'
  13212. });
  13213. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  13214. onWarn({
  13215. code: 'INVALID_OPTION',
  13216. message: '"output.amd.id" is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath".'
  13217. });
  13218. }
  13219. function getIncludedModules(modulesById) {
  13220. return [...modulesById.values()].filter(module => module instanceof Module &&
  13221. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  13222. }
  13223. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  13224. const existingAlias = manualChunkAliasByEntry.get(module);
  13225. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  13226. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  13227. }
  13228. manualChunkAliasByEntry.set(module, alias);
  13229. }
  13230. // Reserved word lists for various dialects of the language
  13231. var reservedWords = {
  13232. 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",
  13233. 5: "class enum extends super const export import",
  13234. 6: "enum",
  13235. strict: "implements interface let package private protected public static yield",
  13236. strictBind: "eval arguments"
  13237. };
  13238. // And the keywords
  13239. 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";
  13240. var keywords = {
  13241. 5: ecma5AndLessKeywords,
  13242. "5module": ecma5AndLessKeywords + " export import",
  13243. 6: ecma5AndLessKeywords + " const class extends export import super"
  13244. };
  13245. var keywordRelationalOperator = /^in(stanceof)?$/;
  13246. // ## Character categories
  13247. // Big ugly regular expressions that match characters in the
  13248. // whitespace, identifier, and identifier-start categories. These
  13249. // are only applied when a character is found to actually have a
  13250. // code point above 128.
  13251. // Generated by `bin/generate-identifier-regex.js`.
  13252. 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\u08a0-\u08b4\u08b6-\u08c7\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\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\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-\u170c\u170e-\u1711\u1720-\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-\u1b4b\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-\u2c2e\u2c30-\u2c5e\u2c60-\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-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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";
  13253. 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\u08d3-\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\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-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\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-\u1df9\u1dfb-\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";
  13254. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  13255. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  13256. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  13257. // These are a run-length and offset encoded representation of the
  13258. // >0xffff code points that are a valid part of identifiers. The
  13259. // offset starts at 0x10000, and each pair of numbers represents an
  13260. // offset to the next range, and then a size of the range. They were
  13261. // generated by bin/generate-identifier-regex.js
  13262. // eslint-disable-next-line comma-spacing
  13263. 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,157,310,10,21,11,7,153,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,107,20,28,22,13,52,76,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,230,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,35,56,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,2749,1070,4050,582,8634,568,8,30,114,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,8952,286,50,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,2357,44,11,6,17,0,370,43,1301,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,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
  13264. // eslint-disable-next-line comma-spacing
  13265. 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,176,2,54,14,32,9,16,3,46,10,54,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,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,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,419,13,1495,6,110,6,6,9,4759,9,787719,239];
  13266. // This has a complexity linear to the value of the code. The
  13267. // assumption is that looking up astral identifier characters is
  13268. // rare.
  13269. function isInAstralSet(code, set) {
  13270. var pos = 0x10000;
  13271. for (var i = 0; i < set.length; i += 2) {
  13272. pos += set[i];
  13273. if (pos > code) { return false }
  13274. pos += set[i + 1];
  13275. if (pos >= code) { return true }
  13276. }
  13277. }
  13278. // Test whether a given character code starts an identifier.
  13279. function isIdentifierStart(code, astral) {
  13280. if (code < 65) { return code === 36 }
  13281. if (code < 91) { return true }
  13282. if (code < 97) { return code === 95 }
  13283. if (code < 123) { return true }
  13284. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  13285. if (astral === false) { return false }
  13286. return isInAstralSet(code, astralIdentifierStartCodes)
  13287. }
  13288. // Test whether a given character is part of an identifier.
  13289. function isIdentifierChar(code, astral) {
  13290. if (code < 48) { return code === 36 }
  13291. if (code < 58) { return true }
  13292. if (code < 65) { return false }
  13293. if (code < 91) { return true }
  13294. if (code < 97) { return code === 95 }
  13295. if (code < 123) { return true }
  13296. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  13297. if (astral === false) { return false }
  13298. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  13299. }
  13300. // ## Token types
  13301. // The assignment of fine-grained, information-carrying type objects
  13302. // allows the tokenizer to store the information it has about a
  13303. // token in a way that is very cheap for the parser to look up.
  13304. // All token type variables start with an underscore, to make them
  13305. // easy to recognize.
  13306. // The `beforeExpr` property is used to disambiguate between regular
  13307. // expressions and divisions. It is set on all token types that can
  13308. // be followed by an expression (thus, a slash after them would be a
  13309. // regular expression).
  13310. //
  13311. // The `startsExpr` property is used to check if the token ends a
  13312. // `yield` expression. It is set on all token types that either can
  13313. // directly start an expression (like a quotation mark) or can
  13314. // continue an expression (like the body of a string).
  13315. //
  13316. // `isLoop` marks a keyword as starting a loop, which is important
  13317. // to know when parsing a label, in order to allow or disallow
  13318. // continue jumps to that label.
  13319. var TokenType = function TokenType(label, conf) {
  13320. if ( conf === void 0 ) conf = {};
  13321. this.label = label;
  13322. this.keyword = conf.keyword;
  13323. this.beforeExpr = !!conf.beforeExpr;
  13324. this.startsExpr = !!conf.startsExpr;
  13325. this.isLoop = !!conf.isLoop;
  13326. this.isAssign = !!conf.isAssign;
  13327. this.prefix = !!conf.prefix;
  13328. this.postfix = !!conf.postfix;
  13329. this.binop = conf.binop || null;
  13330. this.updateContext = null;
  13331. };
  13332. function binop(name, prec) {
  13333. return new TokenType(name, {beforeExpr: true, binop: prec})
  13334. }
  13335. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  13336. // Map keyword names to token types.
  13337. var keywords$1 = {};
  13338. // Succinct definitions of keyword token types
  13339. function kw(name, options) {
  13340. if ( options === void 0 ) options = {};
  13341. options.keyword = name;
  13342. return keywords$1[name] = new TokenType(name, options)
  13343. }
  13344. var types = {
  13345. num: new TokenType("num", startsExpr),
  13346. regexp: new TokenType("regexp", startsExpr),
  13347. string: new TokenType("string", startsExpr),
  13348. name: new TokenType("name", startsExpr),
  13349. privateId: new TokenType("privateId", startsExpr),
  13350. eof: new TokenType("eof"),
  13351. // Punctuation token types.
  13352. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  13353. bracketR: new TokenType("]"),
  13354. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  13355. braceR: new TokenType("}"),
  13356. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  13357. parenR: new TokenType(")"),
  13358. comma: new TokenType(",", beforeExpr),
  13359. semi: new TokenType(";", beforeExpr),
  13360. colon: new TokenType(":", beforeExpr),
  13361. dot: new TokenType("."),
  13362. question: new TokenType("?", beforeExpr),
  13363. questionDot: new TokenType("?."),
  13364. arrow: new TokenType("=>", beforeExpr),
  13365. template: new TokenType("template"),
  13366. invalidTemplate: new TokenType("invalidTemplate"),
  13367. ellipsis: new TokenType("...", beforeExpr),
  13368. backQuote: new TokenType("`", startsExpr),
  13369. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  13370. // Operators. These carry several kinds of properties to help the
  13371. // parser use them properly (the presence of these properties is
  13372. // what categorizes them as operators).
  13373. //
  13374. // `binop`, when present, specifies that this operator is a binary
  13375. // operator, and will refer to its precedence.
  13376. //
  13377. // `prefix` and `postfix` mark the operator as a prefix or postfix
  13378. // unary operator.
  13379. //
  13380. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  13381. // binary operators with a very low precedence, that should result
  13382. // in AssignmentExpression nodes.
  13383. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  13384. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  13385. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  13386. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  13387. logicalOR: binop("||", 1),
  13388. logicalAND: binop("&&", 2),
  13389. bitwiseOR: binop("|", 3),
  13390. bitwiseXOR: binop("^", 4),
  13391. bitwiseAND: binop("&", 5),
  13392. equality: binop("==/!=/===/!==", 6),
  13393. relational: binop("</>/<=/>=", 7),
  13394. bitShift: binop("<</>>/>>>", 8),
  13395. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  13396. modulo: binop("%", 10),
  13397. star: binop("*", 10),
  13398. slash: binop("/", 10),
  13399. starstar: new TokenType("**", {beforeExpr: true}),
  13400. coalesce: binop("??", 1),
  13401. // Keyword token types.
  13402. _break: kw("break"),
  13403. _case: kw("case", beforeExpr),
  13404. _catch: kw("catch"),
  13405. _continue: kw("continue"),
  13406. _debugger: kw("debugger"),
  13407. _default: kw("default", beforeExpr),
  13408. _do: kw("do", {isLoop: true, beforeExpr: true}),
  13409. _else: kw("else", beforeExpr),
  13410. _finally: kw("finally"),
  13411. _for: kw("for", {isLoop: true}),
  13412. _function: kw("function", startsExpr),
  13413. _if: kw("if"),
  13414. _return: kw("return", beforeExpr),
  13415. _switch: kw("switch"),
  13416. _throw: kw("throw", beforeExpr),
  13417. _try: kw("try"),
  13418. _var: kw("var"),
  13419. _const: kw("const"),
  13420. _while: kw("while", {isLoop: true}),
  13421. _with: kw("with"),
  13422. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  13423. _this: kw("this", startsExpr),
  13424. _super: kw("super", startsExpr),
  13425. _class: kw("class", startsExpr),
  13426. _extends: kw("extends", beforeExpr),
  13427. _export: kw("export"),
  13428. _import: kw("import", startsExpr),
  13429. _null: kw("null", startsExpr),
  13430. _true: kw("true", startsExpr),
  13431. _false: kw("false", startsExpr),
  13432. _in: kw("in", {beforeExpr: true, binop: 7}),
  13433. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  13434. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  13435. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  13436. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  13437. };
  13438. // Matches a whole line break (where CRLF is considered a single
  13439. // line break). Used to count lines.
  13440. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  13441. var lineBreakG = new RegExp(lineBreak.source, "g");
  13442. function isNewLine(code, ecma2019String) {
  13443. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  13444. }
  13445. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  13446. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  13447. var ref = Object.prototype;
  13448. var hasOwnProperty = ref.hasOwnProperty;
  13449. var toString = ref.toString;
  13450. // Checks if an object has a property.
  13451. function has(obj, propName) {
  13452. return hasOwnProperty.call(obj, propName)
  13453. }
  13454. var isArray = Array.isArray || (function (obj) { return (
  13455. toString.call(obj) === "[object Array]"
  13456. ); });
  13457. function wordsRegexp(words) {
  13458. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  13459. }
  13460. // These are used when `options.locations` is on, for the
  13461. // `startLoc` and `endLoc` properties.
  13462. var Position = function Position(line, col) {
  13463. this.line = line;
  13464. this.column = col;
  13465. };
  13466. Position.prototype.offset = function offset (n) {
  13467. return new Position(this.line, this.column + n)
  13468. };
  13469. var SourceLocation = function SourceLocation(p, start, end) {
  13470. this.start = start;
  13471. this.end = end;
  13472. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  13473. };
  13474. // The `getLineInfo` function is mostly useful when the
  13475. // `locations` option is off (for performance reasons) and you
  13476. // want to find the line/column position for a given character
  13477. // offset. `input` should be the code string that the offset refers
  13478. // into.
  13479. function getLineInfo(input, offset) {
  13480. for (var line = 1, cur = 0;;) {
  13481. lineBreakG.lastIndex = cur;
  13482. var match = lineBreakG.exec(input);
  13483. if (match && match.index < offset) {
  13484. ++line;
  13485. cur = match.index + match[0].length;
  13486. } else {
  13487. return new Position(line, offset - cur)
  13488. }
  13489. }
  13490. }
  13491. // A second argument must be given to configure the parser process.
  13492. // These options are recognized (only `ecmaVersion` is required):
  13493. var defaultOptions = {
  13494. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  13495. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  13496. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  13497. // latest version the library supports). This influences support
  13498. // for strict mode, the set of reserved words, and support for
  13499. // new syntax features.
  13500. ecmaVersion: null,
  13501. // `sourceType` indicates the mode the code should be parsed in.
  13502. // Can be either `"script"` or `"module"`. This influences global
  13503. // strict mode and parsing of `import` and `export` declarations.
  13504. sourceType: "script",
  13505. // `onInsertedSemicolon` can be a callback that will be called
  13506. // when a semicolon is automatically inserted. It will be passed
  13507. // the position of the comma as an offset, and if `locations` is
  13508. // enabled, it is given the location as a `{line, column}` object
  13509. // as second argument.
  13510. onInsertedSemicolon: null,
  13511. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  13512. // trailing commas.
  13513. onTrailingComma: null,
  13514. // By default, reserved words are only enforced if ecmaVersion >= 5.
  13515. // Set `allowReserved` to a boolean value to explicitly turn this on
  13516. // an off. When this option has the value "never", reserved words
  13517. // and keywords can also not be used as property names.
  13518. allowReserved: null,
  13519. // When enabled, a return at the top level is not considered an
  13520. // error.
  13521. allowReturnOutsideFunction: false,
  13522. // When enabled, import/export statements are not constrained to
  13523. // appearing at the top of the program, and an import.meta expression
  13524. // in a script isn't considered an error.
  13525. allowImportExportEverywhere: false,
  13526. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  13527. // When enabled, await identifiers are allowed to appear at the top-level scope,
  13528. // but they are still not allowed in non-async functions.
  13529. allowAwaitOutsideFunction: null,
  13530. // When enabled, super identifiers are not constrained to
  13531. // appearing in methods and do not raise an error when they appear elsewhere.
  13532. allowSuperOutsideMethod: null,
  13533. // When enabled, hashbang directive in the beginning of file
  13534. // is allowed and treated as a line comment.
  13535. allowHashBang: false,
  13536. // When `locations` is on, `loc` properties holding objects with
  13537. // `start` and `end` properties in `{line, column}` form (with
  13538. // line being 1-based and column 0-based) will be attached to the
  13539. // nodes.
  13540. locations: false,
  13541. // A function can be passed as `onToken` option, which will
  13542. // cause Acorn to call that function with object in the same
  13543. // format as tokens returned from `tokenizer().getToken()`. Note
  13544. // that you are not allowed to call the parser from the
  13545. // callback—that will corrupt its internal state.
  13546. onToken: null,
  13547. // A function can be passed as `onComment` option, which will
  13548. // cause Acorn to call that function with `(block, text, start,
  13549. // end)` parameters whenever a comment is skipped. `block` is a
  13550. // boolean indicating whether this is a block (`/* */`) comment,
  13551. // `text` is the content of the comment, and `start` and `end` are
  13552. // character offsets that denote the start and end of the comment.
  13553. // When the `locations` option is on, two more parameters are
  13554. // passed, the full `{line, column}` locations of the start and
  13555. // end of the comments. Note that you are not allowed to call the
  13556. // parser from the callback—that will corrupt its internal state.
  13557. onComment: null,
  13558. // Nodes have their start and end characters offsets recorded in
  13559. // `start` and `end` properties (directly on the node, rather than
  13560. // the `loc` object, which holds line/column data. To also add a
  13561. // [semi-standardized][range] `range` property holding a `[start,
  13562. // end]` array with the same numbers, set the `ranges` option to
  13563. // `true`.
  13564. //
  13565. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  13566. ranges: false,
  13567. // It is possible to parse multiple files into a single AST by
  13568. // passing the tree produced by parsing the first file as
  13569. // `program` option in subsequent parses. This will add the
  13570. // toplevel forms of the parsed file to the `Program` (top) node
  13571. // of an existing parse tree.
  13572. program: null,
  13573. // When `locations` is on, you can pass this to record the source
  13574. // file in every node's `loc` object.
  13575. sourceFile: null,
  13576. // This value, if given, is stored in every node, whether
  13577. // `locations` is on or off.
  13578. directSourceFile: null,
  13579. // When enabled, parenthesized expressions are represented by
  13580. // (non-standard) ParenthesizedExpression nodes
  13581. preserveParens: false
  13582. };
  13583. // Interpret and default an options object
  13584. var warnedAboutEcmaVersion = false;
  13585. function getOptions(opts) {
  13586. var options = {};
  13587. for (var opt in defaultOptions)
  13588. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  13589. if (options.ecmaVersion === "latest") {
  13590. options.ecmaVersion = 1e8;
  13591. } else if (options.ecmaVersion == null) {
  13592. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  13593. warnedAboutEcmaVersion = true;
  13594. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  13595. }
  13596. options.ecmaVersion = 11;
  13597. } else if (options.ecmaVersion >= 2015) {
  13598. options.ecmaVersion -= 2009;
  13599. }
  13600. if (options.allowReserved == null)
  13601. { options.allowReserved = options.ecmaVersion < 5; }
  13602. if (options.allowAwaitOutsideFunction == null)
  13603. { options.allowAwaitOutsideFunction = options.ecmaVersion >= 13; }
  13604. if (isArray(options.onToken)) {
  13605. var tokens = options.onToken;
  13606. options.onToken = function (token) { return tokens.push(token); };
  13607. }
  13608. if (isArray(options.onComment))
  13609. { options.onComment = pushComment(options, options.onComment); }
  13610. return options
  13611. }
  13612. function pushComment(options, array) {
  13613. return function(block, text, start, end, startLoc, endLoc) {
  13614. var comment = {
  13615. type: block ? "Block" : "Line",
  13616. value: text,
  13617. start: start,
  13618. end: end
  13619. };
  13620. if (options.locations)
  13621. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  13622. if (options.ranges)
  13623. { comment.range = [start, end]; }
  13624. array.push(comment);
  13625. }
  13626. }
  13627. // Each scope gets a bitset that may contain these flags
  13628. var
  13629. SCOPE_TOP = 1,
  13630. SCOPE_FUNCTION = 2,
  13631. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  13632. SCOPE_ASYNC = 4,
  13633. SCOPE_GENERATOR = 8,
  13634. SCOPE_ARROW = 16,
  13635. SCOPE_SIMPLE_CATCH = 32,
  13636. SCOPE_SUPER = 64,
  13637. SCOPE_DIRECT_SUPER = 128;
  13638. function functionFlags(async, generator) {
  13639. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  13640. }
  13641. // Used in checkLVal* and declareName to determine the type of a binding
  13642. var
  13643. BIND_NONE = 0, // Not a binding
  13644. BIND_VAR = 1, // Var-style binding
  13645. BIND_LEXICAL = 2, // Let- or const-style binding
  13646. BIND_FUNCTION = 3, // Function declaration
  13647. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  13648. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  13649. var Parser = function Parser(options, input, startPos) {
  13650. this.options = options = getOptions(options);
  13651. this.sourceFile = options.sourceFile;
  13652. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  13653. var reserved = "";
  13654. if (options.allowReserved !== true) {
  13655. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  13656. if (options.sourceType === "module") { reserved += " await"; }
  13657. }
  13658. this.reservedWords = wordsRegexp(reserved);
  13659. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  13660. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  13661. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  13662. this.input = String(input);
  13663. // Used to signal to callers of `readWord1` whether the word
  13664. // contained any escape sequences. This is needed because words with
  13665. // escape sequences must not be interpreted as keywords.
  13666. this.containsEsc = false;
  13667. // Set up token state
  13668. // The current position of the tokenizer in the input.
  13669. if (startPos) {
  13670. this.pos = startPos;
  13671. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  13672. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  13673. } else {
  13674. this.pos = this.lineStart = 0;
  13675. this.curLine = 1;
  13676. }
  13677. // Properties of the current token:
  13678. // Its type
  13679. this.type = types.eof;
  13680. // For tokens that include more information than their type, the value
  13681. this.value = null;
  13682. // Its start and end offset
  13683. this.start = this.end = this.pos;
  13684. // And, if locations are used, the {line, column} object
  13685. // corresponding to those offsets
  13686. this.startLoc = this.endLoc = this.curPosition();
  13687. // Position information for the previous token
  13688. this.lastTokEndLoc = this.lastTokStartLoc = null;
  13689. this.lastTokStart = this.lastTokEnd = this.pos;
  13690. // The context stack is used to superficially track syntactic
  13691. // context to predict whether a regular expression is allowed in a
  13692. // given position.
  13693. this.context = this.initialContext();
  13694. this.exprAllowed = true;
  13695. // Figure out if it's a module code.
  13696. this.inModule = options.sourceType === "module";
  13697. this.strict = this.inModule || this.strictDirective(this.pos);
  13698. // Used to signify the start of a potential arrow function
  13699. this.potentialArrowAt = -1;
  13700. this.potentialArrowInForAwait = false;
  13701. // Positions to delayed-check that yield/await does not exist in default parameters.
  13702. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  13703. // Labels in scope.
  13704. this.labels = [];
  13705. // Thus-far undefined exports.
  13706. this.undefinedExports = Object.create(null);
  13707. // If enabled, skip leading hashbang line.
  13708. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  13709. { this.skipLineComment(2); }
  13710. // Scope tracking for duplicate variable names (see scope.js)
  13711. this.scopeStack = [];
  13712. this.enterScope(SCOPE_TOP);
  13713. // For RegExp validation
  13714. this.regexpState = null;
  13715. // The stack of private names.
  13716. // Each element has two properties: 'declared' and 'used'.
  13717. // When it exited from the outermost class definition, all used private names must be declared.
  13718. this.privateNameStack = [];
  13719. };
  13720. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  13721. Parser.prototype.parse = function parse () {
  13722. var node = this.options.program || this.startNode();
  13723. this.nextToken();
  13724. return this.parseTopLevel(node)
  13725. };
  13726. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  13727. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  13728. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  13729. prototypeAccessors.allowSuper.get = function () {
  13730. var ref = this.currentThisScope();
  13731. var flags = ref.flags;
  13732. var inClassFieldInit = ref.inClassFieldInit;
  13733. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  13734. };
  13735. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  13736. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  13737. prototypeAccessors.inNonArrowFunction.get = function () {
  13738. var ref = this.currentThisScope();
  13739. var flags = ref.flags;
  13740. var inClassFieldInit = ref.inClassFieldInit;
  13741. return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
  13742. };
  13743. Parser.extend = function extend () {
  13744. var plugins = [], len = arguments.length;
  13745. while ( len-- ) plugins[ len ] = arguments[ len ];
  13746. var cls = this;
  13747. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  13748. return cls
  13749. };
  13750. Parser.parse = function parse (input, options) {
  13751. return new this(options, input).parse()
  13752. };
  13753. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  13754. var parser = new this(options, input, pos);
  13755. parser.nextToken();
  13756. return parser.parseExpression()
  13757. };
  13758. Parser.tokenizer = function tokenizer (input, options) {
  13759. return new this(options, input)
  13760. };
  13761. Object.defineProperties( Parser.prototype, prototypeAccessors );
  13762. var pp = Parser.prototype;
  13763. // ## Parser utilities
  13764. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  13765. pp.strictDirective = function(start) {
  13766. for (;;) {
  13767. // Try to find string literal.
  13768. skipWhiteSpace.lastIndex = start;
  13769. start += skipWhiteSpace.exec(this.input)[0].length;
  13770. var match = literal.exec(this.input.slice(start));
  13771. if (!match) { return false }
  13772. if ((match[1] || match[2]) === "use strict") {
  13773. skipWhiteSpace.lastIndex = start + match[0].length;
  13774. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  13775. var next = this.input.charAt(end);
  13776. return next === ";" || next === "}" ||
  13777. (lineBreak.test(spaceAfter[0]) &&
  13778. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  13779. }
  13780. start += match[0].length;
  13781. // Skip semicolon, if any.
  13782. skipWhiteSpace.lastIndex = start;
  13783. start += skipWhiteSpace.exec(this.input)[0].length;
  13784. if (this.input[start] === ";")
  13785. { start++; }
  13786. }
  13787. };
  13788. // Predicate that tests whether the next token is of the given
  13789. // type, and if yes, consumes it as a side effect.
  13790. pp.eat = function(type) {
  13791. if (this.type === type) {
  13792. this.next();
  13793. return true
  13794. } else {
  13795. return false
  13796. }
  13797. };
  13798. // Tests whether parsed token is a contextual keyword.
  13799. pp.isContextual = function(name) {
  13800. return this.type === types.name && this.value === name && !this.containsEsc
  13801. };
  13802. // Consumes contextual keyword if possible.
  13803. pp.eatContextual = function(name) {
  13804. if (!this.isContextual(name)) { return false }
  13805. this.next();
  13806. return true
  13807. };
  13808. // Asserts that following token is given contextual keyword.
  13809. pp.expectContextual = function(name) {
  13810. if (!this.eatContextual(name)) { this.unexpected(); }
  13811. };
  13812. // Test whether a semicolon can be inserted at the current position.
  13813. pp.canInsertSemicolon = function() {
  13814. return this.type === types.eof ||
  13815. this.type === types.braceR ||
  13816. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  13817. };
  13818. pp.insertSemicolon = function() {
  13819. if (this.canInsertSemicolon()) {
  13820. if (this.options.onInsertedSemicolon)
  13821. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  13822. return true
  13823. }
  13824. };
  13825. // Consume a semicolon, or, failing that, see if we are allowed to
  13826. // pretend that there is a semicolon at this position.
  13827. pp.semicolon = function() {
  13828. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  13829. };
  13830. pp.afterTrailingComma = function(tokType, notNext) {
  13831. if (this.type === tokType) {
  13832. if (this.options.onTrailingComma)
  13833. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  13834. if (!notNext)
  13835. { this.next(); }
  13836. return true
  13837. }
  13838. };
  13839. // Expect a token of a given type. If found, consume it, otherwise,
  13840. // raise an unexpected token error.
  13841. pp.expect = function(type) {
  13842. this.eat(type) || this.unexpected();
  13843. };
  13844. // Raise an unexpected token error.
  13845. pp.unexpected = function(pos) {
  13846. this.raise(pos != null ? pos : this.start, "Unexpected token");
  13847. };
  13848. function DestructuringErrors() {
  13849. this.shorthandAssign =
  13850. this.trailingComma =
  13851. this.parenthesizedAssign =
  13852. this.parenthesizedBind =
  13853. this.doubleProto =
  13854. -1;
  13855. }
  13856. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  13857. if (!refDestructuringErrors) { return }
  13858. if (refDestructuringErrors.trailingComma > -1)
  13859. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  13860. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  13861. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  13862. };
  13863. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  13864. if (!refDestructuringErrors) { return false }
  13865. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  13866. var doubleProto = refDestructuringErrors.doubleProto;
  13867. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  13868. if (shorthandAssign >= 0)
  13869. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  13870. if (doubleProto >= 0)
  13871. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  13872. };
  13873. pp.checkYieldAwaitInDefaultParams = function() {
  13874. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  13875. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  13876. if (this.awaitPos)
  13877. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  13878. };
  13879. pp.isSimpleAssignTarget = function(expr) {
  13880. if (expr.type === "ParenthesizedExpression")
  13881. { return this.isSimpleAssignTarget(expr.expression) }
  13882. return expr.type === "Identifier" || expr.type === "MemberExpression"
  13883. };
  13884. var pp$1 = Parser.prototype;
  13885. // ### Statement parsing
  13886. // Parse a program. Initializes the parser, reads any number of
  13887. // statements, and wraps them in a Program node. Optionally takes a
  13888. // `program` argument. If present, the statements will be appended
  13889. // to its body instead of creating a new node.
  13890. pp$1.parseTopLevel = function(node) {
  13891. var exports = Object.create(null);
  13892. if (!node.body) { node.body = []; }
  13893. while (this.type !== types.eof) {
  13894. var stmt = this.parseStatement(null, true, exports);
  13895. node.body.push(stmt);
  13896. }
  13897. if (this.inModule)
  13898. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  13899. {
  13900. var name = list[i];
  13901. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  13902. } }
  13903. this.adaptDirectivePrologue(node.body);
  13904. this.next();
  13905. node.sourceType = this.options.sourceType;
  13906. return this.finishNode(node, "Program")
  13907. };
  13908. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  13909. pp$1.isLet = function(context) {
  13910. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  13911. skipWhiteSpace.lastIndex = this.pos;
  13912. var skip = skipWhiteSpace.exec(this.input);
  13913. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13914. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  13915. // Statement) is allowed here. If context is not empty then only a Statement
  13916. // is allowed. However, `let [` is an explicit negative lookahead for
  13917. // ExpressionStatement, so special-case it first.
  13918. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  13919. if (context) { return false }
  13920. if (nextCh === 123) { return true } // '{'
  13921. if (isIdentifierStart(nextCh, true)) {
  13922. var pos = next + 1;
  13923. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  13924. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  13925. var ident = this.input.slice(next, pos);
  13926. if (!keywordRelationalOperator.test(ident)) { return true }
  13927. }
  13928. return false
  13929. };
  13930. // check 'async [no LineTerminator here] function'
  13931. // - 'async /*foo*/ function' is OK.
  13932. // - 'async /*\n*/ function' is invalid.
  13933. pp$1.isAsyncFunction = function() {
  13934. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  13935. { return false }
  13936. skipWhiteSpace.lastIndex = this.pos;
  13937. var skip = skipWhiteSpace.exec(this.input);
  13938. var next = this.pos + skip[0].length, after;
  13939. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  13940. this.input.slice(next, next + 8) === "function" &&
  13941. (next + 8 === this.input.length ||
  13942. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  13943. };
  13944. // Parse a single statement.
  13945. //
  13946. // If expecting a statement and finding a slash operator, parse a
  13947. // regular expression literal. This is to handle cases like
  13948. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  13949. // does not help.
  13950. pp$1.parseStatement = function(context, topLevel, exports) {
  13951. var starttype = this.type, node = this.startNode(), kind;
  13952. if (this.isLet(context)) {
  13953. starttype = types._var;
  13954. kind = "let";
  13955. }
  13956. // Most types of statements are recognized by the keyword they
  13957. // start with. Many are trivial to parse, some require a bit of
  13958. // complexity.
  13959. switch (starttype) {
  13960. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  13961. case types._debugger: return this.parseDebuggerStatement(node)
  13962. case types._do: return this.parseDoStatement(node)
  13963. case types._for: return this.parseForStatement(node)
  13964. case types._function:
  13965. // Function as sole body of either an if statement or a labeled statement
  13966. // works, but not when it is part of a labeled statement that is the sole
  13967. // body of an if statement.
  13968. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  13969. return this.parseFunctionStatement(node, false, !context)
  13970. case types._class:
  13971. if (context) { this.unexpected(); }
  13972. return this.parseClass(node, true)
  13973. case types._if: return this.parseIfStatement(node)
  13974. case types._return: return this.parseReturnStatement(node)
  13975. case types._switch: return this.parseSwitchStatement(node)
  13976. case types._throw: return this.parseThrowStatement(node)
  13977. case types._try: return this.parseTryStatement(node)
  13978. case types._const: case types._var:
  13979. kind = kind || this.value;
  13980. if (context && kind !== "var") { this.unexpected(); }
  13981. return this.parseVarStatement(node, kind)
  13982. case types._while: return this.parseWhileStatement(node)
  13983. case types._with: return this.parseWithStatement(node)
  13984. case types.braceL: return this.parseBlock(true, node)
  13985. case types.semi: return this.parseEmptyStatement(node)
  13986. case types._export:
  13987. case types._import:
  13988. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  13989. skipWhiteSpace.lastIndex = this.pos;
  13990. var skip = skipWhiteSpace.exec(this.input);
  13991. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13992. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  13993. { return this.parseExpressionStatement(node, this.parseExpression()) }
  13994. }
  13995. if (!this.options.allowImportExportEverywhere) {
  13996. if (!topLevel)
  13997. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  13998. if (!this.inModule)
  13999. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  14000. }
  14001. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  14002. // If the statement does not start with a statement keyword or a
  14003. // brace, it's an ExpressionStatement or LabeledStatement. We
  14004. // simply start parsing an expression, and afterwards, if the
  14005. // next token is a colon and the expression was a simple
  14006. // Identifier node, we switch to interpreting it as a label.
  14007. default:
  14008. if (this.isAsyncFunction()) {
  14009. if (context) { this.unexpected(); }
  14010. this.next();
  14011. return this.parseFunctionStatement(node, true, !context)
  14012. }
  14013. var maybeName = this.value, expr = this.parseExpression();
  14014. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  14015. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  14016. else { return this.parseExpressionStatement(node, expr) }
  14017. }
  14018. };
  14019. pp$1.parseBreakContinueStatement = function(node, keyword) {
  14020. var isBreak = keyword === "break";
  14021. this.next();
  14022. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  14023. else if (this.type !== types.name) { this.unexpected(); }
  14024. else {
  14025. node.label = this.parseIdent();
  14026. this.semicolon();
  14027. }
  14028. // Verify that there is an actual destination to break or
  14029. // continue to.
  14030. var i = 0;
  14031. for (; i < this.labels.length; ++i) {
  14032. var lab = this.labels[i];
  14033. if (node.label == null || lab.name === node.label.name) {
  14034. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  14035. if (node.label && isBreak) { break }
  14036. }
  14037. }
  14038. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  14039. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  14040. };
  14041. pp$1.parseDebuggerStatement = function(node) {
  14042. this.next();
  14043. this.semicolon();
  14044. return this.finishNode(node, "DebuggerStatement")
  14045. };
  14046. pp$1.parseDoStatement = function(node) {
  14047. this.next();
  14048. this.labels.push(loopLabel);
  14049. node.body = this.parseStatement("do");
  14050. this.labels.pop();
  14051. this.expect(types._while);
  14052. node.test = this.parseParenExpression();
  14053. if (this.options.ecmaVersion >= 6)
  14054. { this.eat(types.semi); }
  14055. else
  14056. { this.semicolon(); }
  14057. return this.finishNode(node, "DoWhileStatement")
  14058. };
  14059. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  14060. // loop is non-trivial. Basically, we have to parse the init `var`
  14061. // statement or expression, disallowing the `in` operator (see
  14062. // the second parameter to `parseExpression`), and then check
  14063. // whether the next token is `in` or `of`. When there is no init
  14064. // part (semicolon immediately after the opening parenthesis), it
  14065. // is a regular `for` loop.
  14066. pp$1.parseForStatement = function(node) {
  14067. this.next();
  14068. var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
  14069. this.labels.push(loopLabel);
  14070. this.enterScope(0);
  14071. this.expect(types.parenL);
  14072. if (this.type === types.semi) {
  14073. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14074. return this.parseFor(node, null)
  14075. }
  14076. var isLet = this.isLet();
  14077. if (this.type === types._var || this.type === types._const || isLet) {
  14078. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  14079. this.next();
  14080. this.parseVar(init$1, true, kind);
  14081. this.finishNode(init$1, "VariableDeclaration");
  14082. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  14083. if (this.options.ecmaVersion >= 9) {
  14084. if (this.type === types._in) {
  14085. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14086. } else { node.await = awaitAt > -1; }
  14087. }
  14088. return this.parseForIn(node, init$1)
  14089. }
  14090. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14091. return this.parseFor(node, init$1)
  14092. }
  14093. var refDestructuringErrors = new DestructuringErrors;
  14094. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  14095. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  14096. if (this.options.ecmaVersion >= 9) {
  14097. if (this.type === types._in) {
  14098. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14099. } else { node.await = awaitAt > -1; }
  14100. }
  14101. this.toAssignable(init, false, refDestructuringErrors);
  14102. this.checkLValPattern(init);
  14103. return this.parseForIn(node, init)
  14104. } else {
  14105. this.checkExpressionErrors(refDestructuringErrors, true);
  14106. }
  14107. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14108. return this.parseFor(node, init)
  14109. };
  14110. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  14111. this.next();
  14112. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  14113. };
  14114. pp$1.parseIfStatement = function(node) {
  14115. this.next();
  14116. node.test = this.parseParenExpression();
  14117. // allow function declarations in branches, but only in non-strict mode
  14118. node.consequent = this.parseStatement("if");
  14119. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  14120. return this.finishNode(node, "IfStatement")
  14121. };
  14122. pp$1.parseReturnStatement = function(node) {
  14123. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  14124. { this.raise(this.start, "'return' outside of function"); }
  14125. this.next();
  14126. // In `return` (and `break`/`continue`), the keywords with
  14127. // optional arguments, we eagerly look for a semicolon or the
  14128. // possibility to insert one.
  14129. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  14130. else { node.argument = this.parseExpression(); this.semicolon(); }
  14131. return this.finishNode(node, "ReturnStatement")
  14132. };
  14133. pp$1.parseSwitchStatement = function(node) {
  14134. this.next();
  14135. node.discriminant = this.parseParenExpression();
  14136. node.cases = [];
  14137. this.expect(types.braceL);
  14138. this.labels.push(switchLabel);
  14139. this.enterScope(0);
  14140. // Statements under must be grouped (by label) in SwitchCase
  14141. // nodes. `cur` is used to keep the node that we are currently
  14142. // adding statements to.
  14143. var cur;
  14144. for (var sawDefault = false; this.type !== types.braceR;) {
  14145. if (this.type === types._case || this.type === types._default) {
  14146. var isCase = this.type === types._case;
  14147. if (cur) { this.finishNode(cur, "SwitchCase"); }
  14148. node.cases.push(cur = this.startNode());
  14149. cur.consequent = [];
  14150. this.next();
  14151. if (isCase) {
  14152. cur.test = this.parseExpression();
  14153. } else {
  14154. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  14155. sawDefault = true;
  14156. cur.test = null;
  14157. }
  14158. this.expect(types.colon);
  14159. } else {
  14160. if (!cur) { this.unexpected(); }
  14161. cur.consequent.push(this.parseStatement(null));
  14162. }
  14163. }
  14164. this.exitScope();
  14165. if (cur) { this.finishNode(cur, "SwitchCase"); }
  14166. this.next(); // Closing brace
  14167. this.labels.pop();
  14168. return this.finishNode(node, "SwitchStatement")
  14169. };
  14170. pp$1.parseThrowStatement = function(node) {
  14171. this.next();
  14172. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  14173. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  14174. node.argument = this.parseExpression();
  14175. this.semicolon();
  14176. return this.finishNode(node, "ThrowStatement")
  14177. };
  14178. // Reused empty array added for node fields that are always empty.
  14179. var empty = [];
  14180. pp$1.parseTryStatement = function(node) {
  14181. this.next();
  14182. node.block = this.parseBlock();
  14183. node.handler = null;
  14184. if (this.type === types._catch) {
  14185. var clause = this.startNode();
  14186. this.next();
  14187. if (this.eat(types.parenL)) {
  14188. clause.param = this.parseBindingAtom();
  14189. var simple = clause.param.type === "Identifier";
  14190. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  14191. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  14192. this.expect(types.parenR);
  14193. } else {
  14194. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  14195. clause.param = null;
  14196. this.enterScope(0);
  14197. }
  14198. clause.body = this.parseBlock(false);
  14199. this.exitScope();
  14200. node.handler = this.finishNode(clause, "CatchClause");
  14201. }
  14202. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  14203. if (!node.handler && !node.finalizer)
  14204. { this.raise(node.start, "Missing catch or finally clause"); }
  14205. return this.finishNode(node, "TryStatement")
  14206. };
  14207. pp$1.parseVarStatement = function(node, kind) {
  14208. this.next();
  14209. this.parseVar(node, false, kind);
  14210. this.semicolon();
  14211. return this.finishNode(node, "VariableDeclaration")
  14212. };
  14213. pp$1.parseWhileStatement = function(node) {
  14214. this.next();
  14215. node.test = this.parseParenExpression();
  14216. this.labels.push(loopLabel);
  14217. node.body = this.parseStatement("while");
  14218. this.labels.pop();
  14219. return this.finishNode(node, "WhileStatement")
  14220. };
  14221. pp$1.parseWithStatement = function(node) {
  14222. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  14223. this.next();
  14224. node.object = this.parseParenExpression();
  14225. node.body = this.parseStatement("with");
  14226. return this.finishNode(node, "WithStatement")
  14227. };
  14228. pp$1.parseEmptyStatement = function(node) {
  14229. this.next();
  14230. return this.finishNode(node, "EmptyStatement")
  14231. };
  14232. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  14233. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  14234. {
  14235. var label = list[i$1];
  14236. if (label.name === maybeName)
  14237. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  14238. } }
  14239. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  14240. for (var i = this.labels.length - 1; i >= 0; i--) {
  14241. var label$1 = this.labels[i];
  14242. if (label$1.statementStart === node.start) {
  14243. // Update information about previous labels on this node
  14244. label$1.statementStart = this.start;
  14245. label$1.kind = kind;
  14246. } else { break }
  14247. }
  14248. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  14249. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  14250. this.labels.pop();
  14251. node.label = expr;
  14252. return this.finishNode(node, "LabeledStatement")
  14253. };
  14254. pp$1.parseExpressionStatement = function(node, expr) {
  14255. node.expression = expr;
  14256. this.semicolon();
  14257. return this.finishNode(node, "ExpressionStatement")
  14258. };
  14259. // Parse a semicolon-enclosed block of statements, handling `"use
  14260. // strict"` declarations when `allowStrict` is true (used for
  14261. // function bodies).
  14262. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  14263. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  14264. if ( node === void 0 ) node = this.startNode();
  14265. node.body = [];
  14266. this.expect(types.braceL);
  14267. if (createNewLexicalScope) { this.enterScope(0); }
  14268. while (this.type !== types.braceR) {
  14269. var stmt = this.parseStatement(null);
  14270. node.body.push(stmt);
  14271. }
  14272. if (exitStrict) { this.strict = false; }
  14273. this.next();
  14274. if (createNewLexicalScope) { this.exitScope(); }
  14275. return this.finishNode(node, "BlockStatement")
  14276. };
  14277. // Parse a regular `for` loop. The disambiguation code in
  14278. // `parseStatement` will already have parsed the init statement or
  14279. // expression.
  14280. pp$1.parseFor = function(node, init) {
  14281. node.init = init;
  14282. this.expect(types.semi);
  14283. node.test = this.type === types.semi ? null : this.parseExpression();
  14284. this.expect(types.semi);
  14285. node.update = this.type === types.parenR ? null : this.parseExpression();
  14286. this.expect(types.parenR);
  14287. node.body = this.parseStatement("for");
  14288. this.exitScope();
  14289. this.labels.pop();
  14290. return this.finishNode(node, "ForStatement")
  14291. };
  14292. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  14293. // same from parser's perspective.
  14294. pp$1.parseForIn = function(node, init) {
  14295. var isForIn = this.type === types._in;
  14296. this.next();
  14297. if (
  14298. init.type === "VariableDeclaration" &&
  14299. init.declarations[0].init != null &&
  14300. (
  14301. !isForIn ||
  14302. this.options.ecmaVersion < 8 ||
  14303. this.strict ||
  14304. init.kind !== "var" ||
  14305. init.declarations[0].id.type !== "Identifier"
  14306. )
  14307. ) {
  14308. this.raise(
  14309. init.start,
  14310. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  14311. );
  14312. }
  14313. node.left = init;
  14314. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  14315. this.expect(types.parenR);
  14316. node.body = this.parseStatement("for");
  14317. this.exitScope();
  14318. this.labels.pop();
  14319. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  14320. };
  14321. // Parse a list of variable declarations.
  14322. pp$1.parseVar = function(node, isFor, kind) {
  14323. node.declarations = [];
  14324. node.kind = kind;
  14325. for (;;) {
  14326. var decl = this.startNode();
  14327. this.parseVarId(decl, kind);
  14328. if (this.eat(types.eq)) {
  14329. decl.init = this.parseMaybeAssign(isFor);
  14330. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  14331. this.unexpected();
  14332. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  14333. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  14334. } else {
  14335. decl.init = null;
  14336. }
  14337. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  14338. if (!this.eat(types.comma)) { break }
  14339. }
  14340. return node
  14341. };
  14342. pp$1.parseVarId = function(decl, kind) {
  14343. decl.id = this.parseBindingAtom();
  14344. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  14345. };
  14346. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  14347. // Parse a function declaration or literal (depending on the
  14348. // `statement & FUNC_STATEMENT`).
  14349. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  14350. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  14351. this.initFunction(node);
  14352. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  14353. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  14354. { this.unexpected(); }
  14355. node.generator = this.eat(types.star);
  14356. }
  14357. if (this.options.ecmaVersion >= 8)
  14358. { node.async = !!isAsync; }
  14359. if (statement & FUNC_STATEMENT) {
  14360. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  14361. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  14362. // If it is a regular function declaration in sloppy mode, then it is
  14363. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  14364. // mode depends on properties of the current scope (see
  14365. // treatFunctionsAsVar).
  14366. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  14367. }
  14368. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14369. this.yieldPos = 0;
  14370. this.awaitPos = 0;
  14371. this.awaitIdentPos = 0;
  14372. this.enterScope(functionFlags(node.async, node.generator));
  14373. if (!(statement & FUNC_STATEMENT))
  14374. { node.id = this.type === types.name ? this.parseIdent() : null; }
  14375. this.parseFunctionParams(node);
  14376. this.parseFunctionBody(node, allowExpressionBody, false);
  14377. this.yieldPos = oldYieldPos;
  14378. this.awaitPos = oldAwaitPos;
  14379. this.awaitIdentPos = oldAwaitIdentPos;
  14380. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  14381. };
  14382. pp$1.parseFunctionParams = function(node) {
  14383. this.expect(types.parenL);
  14384. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  14385. this.checkYieldAwaitInDefaultParams();
  14386. };
  14387. // Parse a class declaration or literal (depending on the
  14388. // `isStatement` parameter).
  14389. pp$1.parseClass = function(node, isStatement) {
  14390. this.next();
  14391. // ecma-262 14.6 Class Definitions
  14392. // A class definition is always strict mode code.
  14393. var oldStrict = this.strict;
  14394. this.strict = true;
  14395. this.parseClassId(node, isStatement);
  14396. this.parseClassSuper(node);
  14397. var privateNameMap = this.enterClassBody();
  14398. var classBody = this.startNode();
  14399. var hadConstructor = false;
  14400. classBody.body = [];
  14401. this.expect(types.braceL);
  14402. while (this.type !== types.braceR) {
  14403. var element = this.parseClassElement(node.superClass !== null);
  14404. if (element) {
  14405. classBody.body.push(element);
  14406. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  14407. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  14408. hadConstructor = true;
  14409. } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  14410. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  14411. }
  14412. }
  14413. }
  14414. this.strict = oldStrict;
  14415. this.next();
  14416. node.body = this.finishNode(classBody, "ClassBody");
  14417. this.exitClassBody();
  14418. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  14419. };
  14420. pp$1.parseClassElement = function(constructorAllowsSuper) {
  14421. if (this.eat(types.semi)) { return null }
  14422. var ecmaVersion = this.options.ecmaVersion;
  14423. var node = this.startNode();
  14424. var keyName = "";
  14425. var isGenerator = false;
  14426. var isAsync = false;
  14427. var kind = "method";
  14428. // Parse modifiers
  14429. node.static = false;
  14430. if (this.eatContextual("static")) {
  14431. if (this.isClassElementNameStart() || this.type === types.star) {
  14432. node.static = true;
  14433. } else {
  14434. keyName = "static";
  14435. }
  14436. }
  14437. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  14438. if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
  14439. isAsync = true;
  14440. } else {
  14441. keyName = "async";
  14442. }
  14443. }
  14444. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
  14445. isGenerator = true;
  14446. }
  14447. if (!keyName && !isAsync && !isGenerator) {
  14448. var lastValue = this.value;
  14449. if (this.eatContextual("get") || this.eatContextual("set")) {
  14450. if (this.isClassElementNameStart()) {
  14451. kind = lastValue;
  14452. } else {
  14453. keyName = lastValue;
  14454. }
  14455. }
  14456. }
  14457. // Parse element name
  14458. if (keyName) {
  14459. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  14460. // The last token is any of those. Make it the element name.
  14461. node.computed = false;
  14462. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  14463. node.key.name = keyName;
  14464. this.finishNode(node.key, "Identifier");
  14465. } else {
  14466. this.parseClassElementName(node);
  14467. }
  14468. // Parse element value
  14469. if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
  14470. var isConstructor = !node.static && checkKeyName(node, "constructor");
  14471. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  14472. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  14473. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  14474. node.kind = isConstructor ? "constructor" : kind;
  14475. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  14476. } else {
  14477. this.parseClassField(node);
  14478. }
  14479. return node
  14480. };
  14481. pp$1.isClassElementNameStart = function() {
  14482. return (
  14483. this.type === types.name ||
  14484. this.type === types.privateId ||
  14485. this.type === types.num ||
  14486. this.type === types.string ||
  14487. this.type === types.bracketL ||
  14488. this.type.keyword
  14489. )
  14490. };
  14491. pp$1.parseClassElementName = function(element) {
  14492. if (this.type === types.privateId) {
  14493. if (this.value === "constructor") {
  14494. this.raise(this.start, "Classes can't have an element named '#constructor'");
  14495. }
  14496. element.computed = false;
  14497. element.key = this.parsePrivateIdent();
  14498. } else {
  14499. this.parsePropertyName(element);
  14500. }
  14501. };
  14502. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  14503. // Check key and flags
  14504. var key = method.key;
  14505. if (method.kind === "constructor") {
  14506. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  14507. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  14508. } else if (method.static && checkKeyName(method, "prototype")) {
  14509. this.raise(key.start, "Classes may not have a static property named prototype");
  14510. }
  14511. // Parse value
  14512. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  14513. // Check value
  14514. if (method.kind === "get" && value.params.length !== 0)
  14515. { this.raiseRecoverable(value.start, "getter should have no params"); }
  14516. if (method.kind === "set" && value.params.length !== 1)
  14517. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  14518. if (method.kind === "set" && value.params[0].type === "RestElement")
  14519. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  14520. return this.finishNode(method, "MethodDefinition")
  14521. };
  14522. pp$1.parseClassField = function(field) {
  14523. if (checkKeyName(field, "constructor")) {
  14524. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  14525. } else if (field.static && checkKeyName(field, "prototype")) {
  14526. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  14527. }
  14528. if (this.eat(types.eq)) {
  14529. // To raise SyntaxError if 'arguments' exists in the initializer.
  14530. var scope = this.currentThisScope();
  14531. var inClassFieldInit = scope.inClassFieldInit;
  14532. scope.inClassFieldInit = true;
  14533. field.value = this.parseMaybeAssign();
  14534. scope.inClassFieldInit = inClassFieldInit;
  14535. } else {
  14536. field.value = null;
  14537. }
  14538. this.semicolon();
  14539. return this.finishNode(field, "PropertyDefinition")
  14540. };
  14541. pp$1.parseClassId = function(node, isStatement) {
  14542. if (this.type === types.name) {
  14543. node.id = this.parseIdent();
  14544. if (isStatement)
  14545. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  14546. } else {
  14547. if (isStatement === true)
  14548. { this.unexpected(); }
  14549. node.id = null;
  14550. }
  14551. };
  14552. pp$1.parseClassSuper = function(node) {
  14553. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  14554. };
  14555. pp$1.enterClassBody = function() {
  14556. var element = {declared: Object.create(null), used: []};
  14557. this.privateNameStack.push(element);
  14558. return element.declared
  14559. };
  14560. pp$1.exitClassBody = function() {
  14561. var ref = this.privateNameStack.pop();
  14562. var declared = ref.declared;
  14563. var used = ref.used;
  14564. var len = this.privateNameStack.length;
  14565. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  14566. for (var i = 0; i < used.length; ++i) {
  14567. var id = used[i];
  14568. if (!has(declared, id.name)) {
  14569. if (parent) {
  14570. parent.used.push(id);
  14571. } else {
  14572. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  14573. }
  14574. }
  14575. }
  14576. };
  14577. function isPrivateNameConflicted(privateNameMap, element) {
  14578. var name = element.key.name;
  14579. var curr = privateNameMap[name];
  14580. var next = "true";
  14581. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  14582. next = (element.static ? "s" : "i") + element.kind;
  14583. }
  14584. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  14585. if (
  14586. curr === "iget" && next === "iset" ||
  14587. curr === "iset" && next === "iget" ||
  14588. curr === "sget" && next === "sset" ||
  14589. curr === "sset" && next === "sget"
  14590. ) {
  14591. privateNameMap[name] = "true";
  14592. return false
  14593. } else if (!curr) {
  14594. privateNameMap[name] = next;
  14595. return false
  14596. } else {
  14597. return true
  14598. }
  14599. }
  14600. function checkKeyName(node, name) {
  14601. var computed = node.computed;
  14602. var key = node.key;
  14603. return !computed && (
  14604. key.type === "Identifier" && key.name === name ||
  14605. key.type === "Literal" && key.value === name
  14606. )
  14607. }
  14608. // Parses module export declaration.
  14609. pp$1.parseExport = function(node, exports) {
  14610. this.next();
  14611. // export * from '...'
  14612. if (this.eat(types.star)) {
  14613. if (this.options.ecmaVersion >= 11) {
  14614. if (this.eatContextual("as")) {
  14615. node.exported = this.parseIdent(true);
  14616. this.checkExport(exports, node.exported.name, this.lastTokStart);
  14617. } else {
  14618. node.exported = null;
  14619. }
  14620. }
  14621. this.expectContextual("from");
  14622. if (this.type !== types.string) { this.unexpected(); }
  14623. node.source = this.parseExprAtom();
  14624. this.semicolon();
  14625. return this.finishNode(node, "ExportAllDeclaration")
  14626. }
  14627. if (this.eat(types._default)) { // export default ...
  14628. this.checkExport(exports, "default", this.lastTokStart);
  14629. var isAsync;
  14630. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  14631. var fNode = this.startNode();
  14632. this.next();
  14633. if (isAsync) { this.next(); }
  14634. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  14635. } else if (this.type === types._class) {
  14636. var cNode = this.startNode();
  14637. node.declaration = this.parseClass(cNode, "nullableID");
  14638. } else {
  14639. node.declaration = this.parseMaybeAssign();
  14640. this.semicolon();
  14641. }
  14642. return this.finishNode(node, "ExportDefaultDeclaration")
  14643. }
  14644. // export var|const|let|function|class ...
  14645. if (this.shouldParseExportStatement()) {
  14646. node.declaration = this.parseStatement(null);
  14647. if (node.declaration.type === "VariableDeclaration")
  14648. { this.checkVariableExport(exports, node.declaration.declarations); }
  14649. else
  14650. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  14651. node.specifiers = [];
  14652. node.source = null;
  14653. } else { // export { x, y as z } [from '...']
  14654. node.declaration = null;
  14655. node.specifiers = this.parseExportSpecifiers(exports);
  14656. if (this.eatContextual("from")) {
  14657. if (this.type !== types.string) { this.unexpected(); }
  14658. node.source = this.parseExprAtom();
  14659. } else {
  14660. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  14661. // check for keywords used as local names
  14662. var spec = list[i];
  14663. this.checkUnreserved(spec.local);
  14664. // check if export is defined
  14665. this.checkLocalExport(spec.local);
  14666. }
  14667. node.source = null;
  14668. }
  14669. this.semicolon();
  14670. }
  14671. return this.finishNode(node, "ExportNamedDeclaration")
  14672. };
  14673. pp$1.checkExport = function(exports, name, pos) {
  14674. if (!exports) { return }
  14675. if (has(exports, name))
  14676. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  14677. exports[name] = true;
  14678. };
  14679. pp$1.checkPatternExport = function(exports, pat) {
  14680. var type = pat.type;
  14681. if (type === "Identifier")
  14682. { this.checkExport(exports, pat.name, pat.start); }
  14683. else if (type === "ObjectPattern")
  14684. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  14685. {
  14686. var prop = list[i];
  14687. this.checkPatternExport(exports, prop);
  14688. } }
  14689. else if (type === "ArrayPattern")
  14690. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  14691. var elt = list$1[i$1];
  14692. if (elt) { this.checkPatternExport(exports, elt); }
  14693. } }
  14694. else if (type === "Property")
  14695. { this.checkPatternExport(exports, pat.value); }
  14696. else if (type === "AssignmentPattern")
  14697. { this.checkPatternExport(exports, pat.left); }
  14698. else if (type === "RestElement")
  14699. { this.checkPatternExport(exports, pat.argument); }
  14700. else if (type === "ParenthesizedExpression")
  14701. { this.checkPatternExport(exports, pat.expression); }
  14702. };
  14703. pp$1.checkVariableExport = function(exports, decls) {
  14704. if (!exports) { return }
  14705. for (var i = 0, list = decls; i < list.length; i += 1)
  14706. {
  14707. var decl = list[i];
  14708. this.checkPatternExport(exports, decl.id);
  14709. }
  14710. };
  14711. pp$1.shouldParseExportStatement = function() {
  14712. return this.type.keyword === "var" ||
  14713. this.type.keyword === "const" ||
  14714. this.type.keyword === "class" ||
  14715. this.type.keyword === "function" ||
  14716. this.isLet() ||
  14717. this.isAsyncFunction()
  14718. };
  14719. // Parses a comma-separated list of module exports.
  14720. pp$1.parseExportSpecifiers = function(exports) {
  14721. var nodes = [], first = true;
  14722. // export { x, y as z } [from '...']
  14723. this.expect(types.braceL);
  14724. while (!this.eat(types.braceR)) {
  14725. if (!first) {
  14726. this.expect(types.comma);
  14727. if (this.afterTrailingComma(types.braceR)) { break }
  14728. } else { first = false; }
  14729. var node = this.startNode();
  14730. node.local = this.parseIdent(true);
  14731. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  14732. this.checkExport(exports, node.exported.name, node.exported.start);
  14733. nodes.push(this.finishNode(node, "ExportSpecifier"));
  14734. }
  14735. return nodes
  14736. };
  14737. // Parses import declaration.
  14738. pp$1.parseImport = function(node) {
  14739. this.next();
  14740. // import '...'
  14741. if (this.type === types.string) {
  14742. node.specifiers = empty;
  14743. node.source = this.parseExprAtom();
  14744. } else {
  14745. node.specifiers = this.parseImportSpecifiers();
  14746. this.expectContextual("from");
  14747. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  14748. }
  14749. this.semicolon();
  14750. return this.finishNode(node, "ImportDeclaration")
  14751. };
  14752. // Parses a comma-separated list of module imports.
  14753. pp$1.parseImportSpecifiers = function() {
  14754. var nodes = [], first = true;
  14755. if (this.type === types.name) {
  14756. // import defaultObj, { x, y as z } from '...'
  14757. var node = this.startNode();
  14758. node.local = this.parseIdent();
  14759. this.checkLValSimple(node.local, BIND_LEXICAL);
  14760. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  14761. if (!this.eat(types.comma)) { return nodes }
  14762. }
  14763. if (this.type === types.star) {
  14764. var node$1 = this.startNode();
  14765. this.next();
  14766. this.expectContextual("as");
  14767. node$1.local = this.parseIdent();
  14768. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  14769. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  14770. return nodes
  14771. }
  14772. this.expect(types.braceL);
  14773. while (!this.eat(types.braceR)) {
  14774. if (!first) {
  14775. this.expect(types.comma);
  14776. if (this.afterTrailingComma(types.braceR)) { break }
  14777. } else { first = false; }
  14778. var node$2 = this.startNode();
  14779. node$2.imported = this.parseIdent(true);
  14780. if (this.eatContextual("as")) {
  14781. node$2.local = this.parseIdent();
  14782. } else {
  14783. this.checkUnreserved(node$2.imported);
  14784. node$2.local = node$2.imported;
  14785. }
  14786. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  14787. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  14788. }
  14789. return nodes
  14790. };
  14791. // Set `ExpressionStatement#directive` property for directive prologues.
  14792. pp$1.adaptDirectivePrologue = function(statements) {
  14793. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  14794. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  14795. }
  14796. };
  14797. pp$1.isDirectiveCandidate = function(statement) {
  14798. return (
  14799. statement.type === "ExpressionStatement" &&
  14800. statement.expression.type === "Literal" &&
  14801. typeof statement.expression.value === "string" &&
  14802. // Reject parenthesized strings.
  14803. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  14804. )
  14805. };
  14806. var pp$2 = Parser.prototype;
  14807. // Convert existing expression atom to assignable pattern
  14808. // if possible.
  14809. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  14810. if (this.options.ecmaVersion >= 6 && node) {
  14811. switch (node.type) {
  14812. case "Identifier":
  14813. if (this.inAsync && node.name === "await")
  14814. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  14815. break
  14816. case "ObjectPattern":
  14817. case "ArrayPattern":
  14818. case "AssignmentPattern":
  14819. case "RestElement":
  14820. break
  14821. case "ObjectExpression":
  14822. node.type = "ObjectPattern";
  14823. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  14824. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  14825. var prop = list[i];
  14826. this.toAssignable(prop, isBinding);
  14827. // Early error:
  14828. // AssignmentRestProperty[Yield, Await] :
  14829. // `...` DestructuringAssignmentTarget[Yield, Await]
  14830. //
  14831. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  14832. if (
  14833. prop.type === "RestElement" &&
  14834. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  14835. ) {
  14836. this.raise(prop.argument.start, "Unexpected token");
  14837. }
  14838. }
  14839. break
  14840. case "Property":
  14841. // AssignmentProperty has type === "Property"
  14842. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  14843. this.toAssignable(node.value, isBinding);
  14844. break
  14845. case "ArrayExpression":
  14846. node.type = "ArrayPattern";
  14847. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  14848. this.toAssignableList(node.elements, isBinding);
  14849. break
  14850. case "SpreadElement":
  14851. node.type = "RestElement";
  14852. this.toAssignable(node.argument, isBinding);
  14853. if (node.argument.type === "AssignmentPattern")
  14854. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  14855. break
  14856. case "AssignmentExpression":
  14857. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  14858. node.type = "AssignmentPattern";
  14859. delete node.operator;
  14860. this.toAssignable(node.left, isBinding);
  14861. break
  14862. case "ParenthesizedExpression":
  14863. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  14864. break
  14865. case "ChainExpression":
  14866. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  14867. break
  14868. case "MemberExpression":
  14869. if (!isBinding) { break }
  14870. default:
  14871. this.raise(node.start, "Assigning to rvalue");
  14872. }
  14873. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  14874. return node
  14875. };
  14876. // Convert list of expression atoms to binding list.
  14877. pp$2.toAssignableList = function(exprList, isBinding) {
  14878. var end = exprList.length;
  14879. for (var i = 0; i < end; i++) {
  14880. var elt = exprList[i];
  14881. if (elt) { this.toAssignable(elt, isBinding); }
  14882. }
  14883. if (end) {
  14884. var last = exprList[end - 1];
  14885. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  14886. { this.unexpected(last.argument.start); }
  14887. }
  14888. return exprList
  14889. };
  14890. // Parses spread element.
  14891. pp$2.parseSpread = function(refDestructuringErrors) {
  14892. var node = this.startNode();
  14893. this.next();
  14894. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  14895. return this.finishNode(node, "SpreadElement")
  14896. };
  14897. pp$2.parseRestBinding = function() {
  14898. var node = this.startNode();
  14899. this.next();
  14900. // RestElement inside of a function parameter must be an identifier
  14901. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  14902. { this.unexpected(); }
  14903. node.argument = this.parseBindingAtom();
  14904. return this.finishNode(node, "RestElement")
  14905. };
  14906. // Parses lvalue (assignable) atom.
  14907. pp$2.parseBindingAtom = function() {
  14908. if (this.options.ecmaVersion >= 6) {
  14909. switch (this.type) {
  14910. case types.bracketL:
  14911. var node = this.startNode();
  14912. this.next();
  14913. node.elements = this.parseBindingList(types.bracketR, true, true);
  14914. return this.finishNode(node, "ArrayPattern")
  14915. case types.braceL:
  14916. return this.parseObj(true)
  14917. }
  14918. }
  14919. return this.parseIdent()
  14920. };
  14921. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  14922. var elts = [], first = true;
  14923. while (!this.eat(close)) {
  14924. if (first) { first = false; }
  14925. else { this.expect(types.comma); }
  14926. if (allowEmpty && this.type === types.comma) {
  14927. elts.push(null);
  14928. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  14929. break
  14930. } else if (this.type === types.ellipsis) {
  14931. var rest = this.parseRestBinding();
  14932. this.parseBindingListItem(rest);
  14933. elts.push(rest);
  14934. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  14935. this.expect(close);
  14936. break
  14937. } else {
  14938. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  14939. this.parseBindingListItem(elem);
  14940. elts.push(elem);
  14941. }
  14942. }
  14943. return elts
  14944. };
  14945. pp$2.parseBindingListItem = function(param) {
  14946. return param
  14947. };
  14948. // Parses assignment pattern around given atom if possible.
  14949. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  14950. left = left || this.parseBindingAtom();
  14951. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  14952. var node = this.startNodeAt(startPos, startLoc);
  14953. node.left = left;
  14954. node.right = this.parseMaybeAssign();
  14955. return this.finishNode(node, "AssignmentPattern")
  14956. };
  14957. // The following three functions all verify that a node is an lvalue —
  14958. // something that can be bound, or assigned to. In order to do so, they perform
  14959. // a variety of checks:
  14960. //
  14961. // - Check that none of the bound/assigned-to identifiers are reserved words.
  14962. // - Record name declarations for bindings in the appropriate scope.
  14963. // - Check duplicate argument names, if checkClashes is set.
  14964. //
  14965. // If a complex binding pattern is encountered (e.g., object and array
  14966. // destructuring), the entire pattern is recursively checked.
  14967. //
  14968. // There are three versions of checkLVal*() appropriate for different
  14969. // circumstances:
  14970. //
  14971. // - checkLValSimple() shall be used if the syntactic construct supports
  14972. // nothing other than identifiers and member expressions. Parenthesized
  14973. // expressions are also correctly handled. This is generally appropriate for
  14974. // constructs for which the spec says
  14975. //
  14976. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  14977. // > simple.
  14978. //
  14979. // It is also appropriate for checking if an identifier is valid and not
  14980. // defined elsewhere, like import declarations or function/class identifiers.
  14981. //
  14982. // Examples where this is used include:
  14983. // a += …;
  14984. // import a from '…';
  14985. // where a is the node to be checked.
  14986. //
  14987. // - checkLValPattern() shall be used if the syntactic construct supports
  14988. // anything checkLValSimple() supports, as well as object and array
  14989. // destructuring patterns. This is generally appropriate for constructs for
  14990. // which the spec says
  14991. //
  14992. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  14993. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  14994. // > simple.
  14995. //
  14996. // Examples where this is used include:
  14997. // (a = …);
  14998. // const a = …;
  14999. // try { … } catch (a) { … }
  15000. // where a is the node to be checked.
  15001. //
  15002. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  15003. // anything checkLValPattern() supports, as well as default assignment
  15004. // patterns, rest elements, and other constructs that may appear within an
  15005. // object or array destructuring pattern.
  15006. //
  15007. // As a special case, function parameters also use checkLValInnerPattern(),
  15008. // as they also support defaults and rest constructs.
  15009. //
  15010. // These functions deliberately support both assignment and binding constructs,
  15011. // as the logic for both is exceedingly similar. If the node is the target of
  15012. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  15013. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  15014. // BIND_LEXICAL.
  15015. //
  15016. // If the function is called with a non-BIND_NONE bindingType, then
  15017. // additionally a checkClashes object may be specified to allow checking for
  15018. // duplicate argument names. checkClashes is ignored if the provided construct
  15019. // is an assignment (i.e., bindingType is BIND_NONE).
  15020. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  15021. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  15022. var isBind = bindingType !== BIND_NONE;
  15023. switch (expr.type) {
  15024. case "Identifier":
  15025. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  15026. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  15027. if (isBind) {
  15028. if (bindingType === BIND_LEXICAL && expr.name === "let")
  15029. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  15030. if (checkClashes) {
  15031. if (has(checkClashes, expr.name))
  15032. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  15033. checkClashes[expr.name] = true;
  15034. }
  15035. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  15036. }
  15037. break
  15038. case "ChainExpression":
  15039. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  15040. break
  15041. case "MemberExpression":
  15042. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  15043. break
  15044. case "ParenthesizedExpression":
  15045. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  15046. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  15047. default:
  15048. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  15049. }
  15050. };
  15051. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  15052. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  15053. switch (expr.type) {
  15054. case "ObjectPattern":
  15055. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  15056. var prop = list[i];
  15057. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  15058. }
  15059. break
  15060. case "ArrayPattern":
  15061. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  15062. var elem = list$1[i$1];
  15063. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  15064. }
  15065. break
  15066. default:
  15067. this.checkLValSimple(expr, bindingType, checkClashes);
  15068. }
  15069. };
  15070. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  15071. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  15072. switch (expr.type) {
  15073. case "Property":
  15074. // AssignmentProperty has type === "Property"
  15075. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  15076. break
  15077. case "AssignmentPattern":
  15078. this.checkLValPattern(expr.left, bindingType, checkClashes);
  15079. break
  15080. case "RestElement":
  15081. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  15082. break
  15083. default:
  15084. this.checkLValPattern(expr, bindingType, checkClashes);
  15085. }
  15086. };
  15087. // A recursive descent parser operates by defining functions for all
  15088. var pp$3 = Parser.prototype;
  15089. // Check if property name clashes with already added.
  15090. // Object/class getters and setters are not allowed to clash —
  15091. // either with each other or with an init property — and in
  15092. // strict mode, init properties are also not allowed to be repeated.
  15093. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  15094. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  15095. { return }
  15096. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  15097. { return }
  15098. var key = prop.key;
  15099. var name;
  15100. switch (key.type) {
  15101. case "Identifier": name = key.name; break
  15102. case "Literal": name = String(key.value); break
  15103. default: return
  15104. }
  15105. var kind = prop.kind;
  15106. if (this.options.ecmaVersion >= 6) {
  15107. if (name === "__proto__" && kind === "init") {
  15108. if (propHash.proto) {
  15109. if (refDestructuringErrors) {
  15110. if (refDestructuringErrors.doubleProto < 0)
  15111. { refDestructuringErrors.doubleProto = key.start; }
  15112. // Backwards-compat kludge. Can be removed in version 6.0
  15113. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  15114. }
  15115. propHash.proto = true;
  15116. }
  15117. return
  15118. }
  15119. name = "$" + name;
  15120. var other = propHash[name];
  15121. if (other) {
  15122. var redefinition;
  15123. if (kind === "init") {
  15124. redefinition = this.strict && other.init || other.get || other.set;
  15125. } else {
  15126. redefinition = other.init || other[kind];
  15127. }
  15128. if (redefinition)
  15129. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  15130. } else {
  15131. other = propHash[name] = {
  15132. init: false,
  15133. get: false,
  15134. set: false
  15135. };
  15136. }
  15137. other[kind] = true;
  15138. };
  15139. // ### Expression parsing
  15140. // These nest, from the most general expression type at the top to
  15141. // 'atomic', nondivisible expression types at the bottom. Most of
  15142. // the functions will simply let the function(s) below them parse,
  15143. // and, *if* the syntactic construct they handle is present, wrap
  15144. // the AST node that the inner parser gave them in another node.
  15145. // Parse a full expression. The optional arguments are used to
  15146. // forbid the `in` operator (in for loops initalization expressions)
  15147. // and provide reference for storing '=' operator inside shorthand
  15148. // property assignment in contexts where both object expression
  15149. // and object pattern might appear (so it's possible to raise
  15150. // delayed syntax error at correct position).
  15151. pp$3.parseExpression = function(forInit, refDestructuringErrors) {
  15152. var startPos = this.start, startLoc = this.startLoc;
  15153. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  15154. if (this.type === types.comma) {
  15155. var node = this.startNodeAt(startPos, startLoc);
  15156. node.expressions = [expr];
  15157. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  15158. return this.finishNode(node, "SequenceExpression")
  15159. }
  15160. return expr
  15161. };
  15162. // Parse an assignment expression. This includes applications of
  15163. // operators like `+=`.
  15164. pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  15165. if (this.isContextual("yield")) {
  15166. if (this.inGenerator) { return this.parseYield(forInit) }
  15167. // The tokenizer will assume an expression is allowed after
  15168. // `yield`, but this isn't that kind of yield
  15169. else { this.exprAllowed = false; }
  15170. }
  15171. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  15172. if (refDestructuringErrors) {
  15173. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  15174. oldTrailingComma = refDestructuringErrors.trailingComma;
  15175. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  15176. } else {
  15177. refDestructuringErrors = new DestructuringErrors;
  15178. ownDestructuringErrors = true;
  15179. }
  15180. var startPos = this.start, startLoc = this.startLoc;
  15181. if (this.type === types.parenL || this.type === types.name) {
  15182. this.potentialArrowAt = this.start;
  15183. this.potentialArrowInForAwait = forInit === "await";
  15184. }
  15185. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  15186. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  15187. if (this.type.isAssign) {
  15188. var node = this.startNodeAt(startPos, startLoc);
  15189. node.operator = this.value;
  15190. if (this.type === types.eq)
  15191. { left = this.toAssignable(left, false, refDestructuringErrors); }
  15192. if (!ownDestructuringErrors) {
  15193. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  15194. }
  15195. if (refDestructuringErrors.shorthandAssign >= left.start)
  15196. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  15197. if (this.type === types.eq)
  15198. { this.checkLValPattern(left); }
  15199. else
  15200. { this.checkLValSimple(left); }
  15201. node.left = left;
  15202. this.next();
  15203. node.right = this.parseMaybeAssign(forInit);
  15204. return this.finishNode(node, "AssignmentExpression")
  15205. } else {
  15206. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  15207. }
  15208. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  15209. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  15210. return left
  15211. };
  15212. // Parse a ternary conditional (`?:`) operator.
  15213. pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  15214. var startPos = this.start, startLoc = this.startLoc;
  15215. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  15216. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  15217. if (this.eat(types.question)) {
  15218. var node = this.startNodeAt(startPos, startLoc);
  15219. node.test = expr;
  15220. node.consequent = this.parseMaybeAssign();
  15221. this.expect(types.colon);
  15222. node.alternate = this.parseMaybeAssign(forInit);
  15223. return this.finishNode(node, "ConditionalExpression")
  15224. }
  15225. return expr
  15226. };
  15227. // Start the precedence parser.
  15228. pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
  15229. var startPos = this.start, startLoc = this.startLoc;
  15230. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  15231. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  15232. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  15233. };
  15234. // Parse binary operators with the operator precedence parsing
  15235. // algorithm. `left` is the left-hand side of the operator.
  15236. // `minPrec` provides context that allows the function to stop and
  15237. // defer further parser to one of its callers when it encounters an
  15238. // operator that has a lower precedence than the set it is parsing.
  15239. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  15240. var prec = this.type.binop;
  15241. if (prec != null && (!forInit || this.type !== types._in)) {
  15242. if (prec > minPrec) {
  15243. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  15244. var coalesce = this.type === types.coalesce;
  15245. if (coalesce) {
  15246. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  15247. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  15248. prec = types.logicalAND.binop;
  15249. }
  15250. var op = this.value;
  15251. this.next();
  15252. var startPos = this.start, startLoc = this.startLoc;
  15253. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
  15254. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  15255. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  15256. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  15257. }
  15258. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  15259. }
  15260. }
  15261. return left
  15262. };
  15263. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  15264. var node = this.startNodeAt(startPos, startLoc);
  15265. node.left = left;
  15266. node.operator = op;
  15267. node.right = right;
  15268. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  15269. };
  15270. // Parse unary operators, both prefix and postfix.
  15271. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
  15272. var startPos = this.start, startLoc = this.startLoc, expr;
  15273. if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
  15274. expr = this.parseAwait();
  15275. sawUnary = true;
  15276. } else if (this.type.prefix) {
  15277. var node = this.startNode(), update = this.type === types.incDec;
  15278. node.operator = this.value;
  15279. node.prefix = true;
  15280. this.next();
  15281. node.argument = this.parseMaybeUnary(null, true, update);
  15282. this.checkExpressionErrors(refDestructuringErrors, true);
  15283. if (update) { this.checkLValSimple(node.argument); }
  15284. else if (this.strict && node.operator === "delete" &&
  15285. node.argument.type === "Identifier")
  15286. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  15287. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  15288. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  15289. else { sawUnary = true; }
  15290. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  15291. } else {
  15292. expr = this.parseExprSubscripts(refDestructuringErrors);
  15293. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  15294. while (this.type.postfix && !this.canInsertSemicolon()) {
  15295. var node$1 = this.startNodeAt(startPos, startLoc);
  15296. node$1.operator = this.value;
  15297. node$1.prefix = false;
  15298. node$1.argument = expr;
  15299. this.checkLValSimple(expr);
  15300. this.next();
  15301. expr = this.finishNode(node$1, "UpdateExpression");
  15302. }
  15303. }
  15304. if (!incDec && this.eat(types.starstar)) {
  15305. if (sawUnary)
  15306. { this.unexpected(this.lastTokStart); }
  15307. else
  15308. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  15309. } else {
  15310. return expr
  15311. }
  15312. };
  15313. function isPrivateFieldAccess(node) {
  15314. return (
  15315. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  15316. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  15317. )
  15318. }
  15319. // Parse call, dot, and `[]`-subscript expressions.
  15320. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  15321. var startPos = this.start, startLoc = this.startLoc;
  15322. var expr = this.parseExprAtom(refDestructuringErrors);
  15323. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  15324. { return expr }
  15325. var result = this.parseSubscripts(expr, startPos, startLoc);
  15326. if (refDestructuringErrors && result.type === "MemberExpression") {
  15327. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  15328. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  15329. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  15330. }
  15331. return result
  15332. };
  15333. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  15334. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  15335. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  15336. this.potentialArrowAt === base.start;
  15337. var optionalChained = false;
  15338. while (true) {
  15339. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  15340. if (element.optional) { optionalChained = true; }
  15341. if (element === base || element.type === "ArrowFunctionExpression") {
  15342. if (optionalChained) {
  15343. var chainNode = this.startNodeAt(startPos, startLoc);
  15344. chainNode.expression = element;
  15345. element = this.finishNode(chainNode, "ChainExpression");
  15346. }
  15347. return element
  15348. }
  15349. base = element;
  15350. }
  15351. };
  15352. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  15353. var optionalSupported = this.options.ecmaVersion >= 11;
  15354. var optional = optionalSupported && this.eat(types.questionDot);
  15355. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  15356. var computed = this.eat(types.bracketL);
  15357. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  15358. var node = this.startNodeAt(startPos, startLoc);
  15359. node.object = base;
  15360. if (computed) {
  15361. node.property = this.parseExpression();
  15362. this.expect(types.bracketR);
  15363. } else if (this.type === types.privateId && base.type !== "Super") {
  15364. node.property = this.parsePrivateIdent();
  15365. } else {
  15366. node.property = this.parseIdent(this.options.allowReserved !== "never");
  15367. }
  15368. node.computed = !!computed;
  15369. if (optionalSupported) {
  15370. node.optional = optional;
  15371. }
  15372. base = this.finishNode(node, "MemberExpression");
  15373. } else if (!noCalls && this.eat(types.parenL)) {
  15374. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15375. this.yieldPos = 0;
  15376. this.awaitPos = 0;
  15377. this.awaitIdentPos = 0;
  15378. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  15379. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  15380. this.checkPatternErrors(refDestructuringErrors, false);
  15381. this.checkYieldAwaitInDefaultParams();
  15382. if (this.awaitIdentPos > 0)
  15383. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  15384. this.yieldPos = oldYieldPos;
  15385. this.awaitPos = oldAwaitPos;
  15386. this.awaitIdentPos = oldAwaitIdentPos;
  15387. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  15388. }
  15389. this.checkExpressionErrors(refDestructuringErrors, true);
  15390. this.yieldPos = oldYieldPos || this.yieldPos;
  15391. this.awaitPos = oldAwaitPos || this.awaitPos;
  15392. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  15393. var node$1 = this.startNodeAt(startPos, startLoc);
  15394. node$1.callee = base;
  15395. node$1.arguments = exprList;
  15396. if (optionalSupported) {
  15397. node$1.optional = optional;
  15398. }
  15399. base = this.finishNode(node$1, "CallExpression");
  15400. } else if (this.type === types.backQuote) {
  15401. if (optional || optionalChained) {
  15402. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  15403. }
  15404. var node$2 = this.startNodeAt(startPos, startLoc);
  15405. node$2.tag = base;
  15406. node$2.quasi = this.parseTemplate({isTagged: true});
  15407. base = this.finishNode(node$2, "TaggedTemplateExpression");
  15408. }
  15409. return base
  15410. };
  15411. // Parse an atomic expression — either a single token that is an
  15412. // expression, an expression started by a keyword like `function` or
  15413. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  15414. // or `{}`.
  15415. pp$3.parseExprAtom = function(refDestructuringErrors) {
  15416. // If a division operator appears in an expression position, the
  15417. // tokenizer got confused, and we force it to read a regexp instead.
  15418. if (this.type === types.slash) { this.readRegexp(); }
  15419. var node, canBeArrow = this.potentialArrowAt === this.start;
  15420. switch (this.type) {
  15421. case types._super:
  15422. if (!this.allowSuper)
  15423. { this.raise(this.start, "'super' keyword outside a method"); }
  15424. node = this.startNode();
  15425. this.next();
  15426. if (this.type === types.parenL && !this.allowDirectSuper)
  15427. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  15428. // The `super` keyword can appear at below:
  15429. // SuperProperty:
  15430. // super [ Expression ]
  15431. // super . IdentifierName
  15432. // SuperCall:
  15433. // super ( Arguments )
  15434. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  15435. { this.unexpected(); }
  15436. return this.finishNode(node, "Super")
  15437. case types._this:
  15438. node = this.startNode();
  15439. this.next();
  15440. return this.finishNode(node, "ThisExpression")
  15441. case types.name:
  15442. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  15443. var id = this.parseIdent(false);
  15444. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  15445. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  15446. if (canBeArrow && !this.canInsertSemicolon()) {
  15447. if (this.eat(types.arrow))
  15448. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  15449. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
  15450. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  15451. id = this.parseIdent(false);
  15452. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  15453. { this.unexpected(); }
  15454. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  15455. }
  15456. }
  15457. return id
  15458. case types.regexp:
  15459. var value = this.value;
  15460. node = this.parseLiteral(value.value);
  15461. node.regex = {pattern: value.pattern, flags: value.flags};
  15462. return node
  15463. case types.num: case types.string:
  15464. return this.parseLiteral(this.value)
  15465. case types._null: case types._true: case types._false:
  15466. node = this.startNode();
  15467. node.value = this.type === types._null ? null : this.type === types._true;
  15468. node.raw = this.type.keyword;
  15469. this.next();
  15470. return this.finishNode(node, "Literal")
  15471. case types.parenL:
  15472. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  15473. if (refDestructuringErrors) {
  15474. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  15475. { refDestructuringErrors.parenthesizedAssign = start; }
  15476. if (refDestructuringErrors.parenthesizedBind < 0)
  15477. { refDestructuringErrors.parenthesizedBind = start; }
  15478. }
  15479. return expr
  15480. case types.bracketL:
  15481. node = this.startNode();
  15482. this.next();
  15483. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  15484. return this.finishNode(node, "ArrayExpression")
  15485. case types.braceL:
  15486. return this.parseObj(false, refDestructuringErrors)
  15487. case types._function:
  15488. node = this.startNode();
  15489. this.next();
  15490. return this.parseFunction(node, 0)
  15491. case types._class:
  15492. return this.parseClass(this.startNode(), false)
  15493. case types._new:
  15494. return this.parseNew()
  15495. case types.backQuote:
  15496. return this.parseTemplate()
  15497. case types._import:
  15498. if (this.options.ecmaVersion >= 11) {
  15499. return this.parseExprImport()
  15500. } else {
  15501. return this.unexpected()
  15502. }
  15503. default:
  15504. this.unexpected();
  15505. }
  15506. };
  15507. pp$3.parseExprImport = function() {
  15508. var node = this.startNode();
  15509. // Consume `import` as an identifier for `import.meta`.
  15510. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  15511. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  15512. var meta = this.parseIdent(true);
  15513. switch (this.type) {
  15514. case types.parenL:
  15515. return this.parseDynamicImport(node)
  15516. case types.dot:
  15517. node.meta = meta;
  15518. return this.parseImportMeta(node)
  15519. default:
  15520. this.unexpected();
  15521. }
  15522. };
  15523. pp$3.parseDynamicImport = function(node) {
  15524. this.next(); // skip `(`
  15525. // Parse node.source.
  15526. node.source = this.parseMaybeAssign();
  15527. // Verify ending.
  15528. if (!this.eat(types.parenR)) {
  15529. var errorPos = this.start;
  15530. if (this.eat(types.comma) && this.eat(types.parenR)) {
  15531. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  15532. } else {
  15533. this.unexpected(errorPos);
  15534. }
  15535. }
  15536. return this.finishNode(node, "ImportExpression")
  15537. };
  15538. pp$3.parseImportMeta = function(node) {
  15539. this.next(); // skip `.`
  15540. var containsEsc = this.containsEsc;
  15541. node.property = this.parseIdent(true);
  15542. if (node.property.name !== "meta")
  15543. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  15544. if (containsEsc)
  15545. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  15546. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  15547. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  15548. return this.finishNode(node, "MetaProperty")
  15549. };
  15550. pp$3.parseLiteral = function(value) {
  15551. var node = this.startNode();
  15552. node.value = value;
  15553. node.raw = this.input.slice(this.start, this.end);
  15554. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  15555. this.next();
  15556. return this.finishNode(node, "Literal")
  15557. };
  15558. pp$3.parseParenExpression = function() {
  15559. this.expect(types.parenL);
  15560. var val = this.parseExpression();
  15561. this.expect(types.parenR);
  15562. return val
  15563. };
  15564. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  15565. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  15566. if (this.options.ecmaVersion >= 6) {
  15567. this.next();
  15568. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  15569. var exprList = [], first = true, lastIsComma = false;
  15570. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  15571. this.yieldPos = 0;
  15572. this.awaitPos = 0;
  15573. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  15574. while (this.type !== types.parenR) {
  15575. first ? first = false : this.expect(types.comma);
  15576. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  15577. lastIsComma = true;
  15578. break
  15579. } else if (this.type === types.ellipsis) {
  15580. spreadStart = this.start;
  15581. exprList.push(this.parseParenItem(this.parseRestBinding()));
  15582. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  15583. break
  15584. } else {
  15585. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  15586. }
  15587. }
  15588. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  15589. this.expect(types.parenR);
  15590. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  15591. this.checkPatternErrors(refDestructuringErrors, false);
  15592. this.checkYieldAwaitInDefaultParams();
  15593. this.yieldPos = oldYieldPos;
  15594. this.awaitPos = oldAwaitPos;
  15595. return this.parseParenArrowList(startPos, startLoc, exprList)
  15596. }
  15597. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  15598. if (spreadStart) { this.unexpected(spreadStart); }
  15599. this.checkExpressionErrors(refDestructuringErrors, true);
  15600. this.yieldPos = oldYieldPos || this.yieldPos;
  15601. this.awaitPos = oldAwaitPos || this.awaitPos;
  15602. if (exprList.length > 1) {
  15603. val = this.startNodeAt(innerStartPos, innerStartLoc);
  15604. val.expressions = exprList;
  15605. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  15606. } else {
  15607. val = exprList[0];
  15608. }
  15609. } else {
  15610. val = this.parseParenExpression();
  15611. }
  15612. if (this.options.preserveParens) {
  15613. var par = this.startNodeAt(startPos, startLoc);
  15614. par.expression = val;
  15615. return this.finishNode(par, "ParenthesizedExpression")
  15616. } else {
  15617. return val
  15618. }
  15619. };
  15620. pp$3.parseParenItem = function(item) {
  15621. return item
  15622. };
  15623. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  15624. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  15625. };
  15626. // New's precedence is slightly tricky. It must allow its argument to
  15627. // be a `[]` or dot subscript expression, but not a call — at least,
  15628. // not without wrapping it in parentheses. Thus, it uses the noCalls
  15629. // argument to parseSubscripts to prevent it from consuming the
  15630. // argument list.
  15631. var empty$1 = [];
  15632. pp$3.parseNew = function() {
  15633. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  15634. var node = this.startNode();
  15635. var meta = this.parseIdent(true);
  15636. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  15637. node.meta = meta;
  15638. var containsEsc = this.containsEsc;
  15639. node.property = this.parseIdent(true);
  15640. if (node.property.name !== "target")
  15641. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  15642. if (containsEsc)
  15643. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  15644. if (!this.inNonArrowFunction)
  15645. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  15646. return this.finishNode(node, "MetaProperty")
  15647. }
  15648. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  15649. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  15650. if (isImport && node.callee.type === "ImportExpression") {
  15651. this.raise(startPos, "Cannot use new with import()");
  15652. }
  15653. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  15654. else { node.arguments = empty$1; }
  15655. return this.finishNode(node, "NewExpression")
  15656. };
  15657. // Parse template expression.
  15658. pp$3.parseTemplateElement = function(ref) {
  15659. var isTagged = ref.isTagged;
  15660. var elem = this.startNode();
  15661. if (this.type === types.invalidTemplate) {
  15662. if (!isTagged) {
  15663. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  15664. }
  15665. elem.value = {
  15666. raw: this.value,
  15667. cooked: null
  15668. };
  15669. } else {
  15670. elem.value = {
  15671. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  15672. cooked: this.value
  15673. };
  15674. }
  15675. this.next();
  15676. elem.tail = this.type === types.backQuote;
  15677. return this.finishNode(elem, "TemplateElement")
  15678. };
  15679. pp$3.parseTemplate = function(ref) {
  15680. if ( ref === void 0 ) ref = {};
  15681. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  15682. var node = this.startNode();
  15683. this.next();
  15684. node.expressions = [];
  15685. var curElt = this.parseTemplateElement({isTagged: isTagged});
  15686. node.quasis = [curElt];
  15687. while (!curElt.tail) {
  15688. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  15689. this.expect(types.dollarBraceL);
  15690. node.expressions.push(this.parseExpression());
  15691. this.expect(types.braceR);
  15692. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  15693. }
  15694. this.next();
  15695. return this.finishNode(node, "TemplateLiteral")
  15696. };
  15697. pp$3.isAsyncProp = function(prop) {
  15698. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  15699. (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
  15700. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15701. };
  15702. // Parse an object literal or binding pattern.
  15703. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  15704. var node = this.startNode(), first = true, propHash = {};
  15705. node.properties = [];
  15706. this.next();
  15707. while (!this.eat(types.braceR)) {
  15708. if (!first) {
  15709. this.expect(types.comma);
  15710. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  15711. } else { first = false; }
  15712. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  15713. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  15714. node.properties.push(prop);
  15715. }
  15716. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  15717. };
  15718. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  15719. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  15720. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  15721. if (isPattern) {
  15722. prop.argument = this.parseIdent(false);
  15723. if (this.type === types.comma) {
  15724. this.raise(this.start, "Comma is not permitted after the rest element");
  15725. }
  15726. return this.finishNode(prop, "RestElement")
  15727. }
  15728. // To disallow parenthesized identifier via `this.toAssignable()`.
  15729. if (this.type === types.parenL && refDestructuringErrors) {
  15730. if (refDestructuringErrors.parenthesizedAssign < 0) {
  15731. refDestructuringErrors.parenthesizedAssign = this.start;
  15732. }
  15733. if (refDestructuringErrors.parenthesizedBind < 0) {
  15734. refDestructuringErrors.parenthesizedBind = this.start;
  15735. }
  15736. }
  15737. // Parse argument.
  15738. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  15739. // To disallow trailing comma via `this.toAssignable()`.
  15740. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  15741. refDestructuringErrors.trailingComma = this.start;
  15742. }
  15743. // Finish
  15744. return this.finishNode(prop, "SpreadElement")
  15745. }
  15746. if (this.options.ecmaVersion >= 6) {
  15747. prop.method = false;
  15748. prop.shorthand = false;
  15749. if (isPattern || refDestructuringErrors) {
  15750. startPos = this.start;
  15751. startLoc = this.startLoc;
  15752. }
  15753. if (!isPattern)
  15754. { isGenerator = this.eat(types.star); }
  15755. }
  15756. var containsEsc = this.containsEsc;
  15757. this.parsePropertyName(prop);
  15758. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  15759. isAsync = true;
  15760. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  15761. this.parsePropertyName(prop, refDestructuringErrors);
  15762. } else {
  15763. isAsync = false;
  15764. }
  15765. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  15766. return this.finishNode(prop, "Property")
  15767. };
  15768. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  15769. if ((isGenerator || isAsync) && this.type === types.colon)
  15770. { this.unexpected(); }
  15771. if (this.eat(types.colon)) {
  15772. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  15773. prop.kind = "init";
  15774. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  15775. if (isPattern) { this.unexpected(); }
  15776. prop.kind = "init";
  15777. prop.method = true;
  15778. prop.value = this.parseMethod(isGenerator, isAsync);
  15779. } else if (!isPattern && !containsEsc &&
  15780. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  15781. (prop.key.name === "get" || prop.key.name === "set") &&
  15782. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  15783. if (isGenerator || isAsync) { this.unexpected(); }
  15784. prop.kind = prop.key.name;
  15785. this.parsePropertyName(prop);
  15786. prop.value = this.parseMethod(false);
  15787. var paramCount = prop.kind === "get" ? 0 : 1;
  15788. if (prop.value.params.length !== paramCount) {
  15789. var start = prop.value.start;
  15790. if (prop.kind === "get")
  15791. { this.raiseRecoverable(start, "getter should have no params"); }
  15792. else
  15793. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  15794. } else {
  15795. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  15796. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  15797. }
  15798. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  15799. if (isGenerator || isAsync) { this.unexpected(); }
  15800. this.checkUnreserved(prop.key);
  15801. if (prop.key.name === "await" && !this.awaitIdentPos)
  15802. { this.awaitIdentPos = startPos; }
  15803. prop.kind = "init";
  15804. if (isPattern) {
  15805. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  15806. } else if (this.type === types.eq && refDestructuringErrors) {
  15807. if (refDestructuringErrors.shorthandAssign < 0)
  15808. { refDestructuringErrors.shorthandAssign = this.start; }
  15809. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  15810. } else {
  15811. prop.value = this.copyNode(prop.key);
  15812. }
  15813. prop.shorthand = true;
  15814. } else { this.unexpected(); }
  15815. };
  15816. pp$3.parsePropertyName = function(prop) {
  15817. if (this.options.ecmaVersion >= 6) {
  15818. if (this.eat(types.bracketL)) {
  15819. prop.computed = true;
  15820. prop.key = this.parseMaybeAssign();
  15821. this.expect(types.bracketR);
  15822. return prop.key
  15823. } else {
  15824. prop.computed = false;
  15825. }
  15826. }
  15827. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  15828. };
  15829. // Initialize empty function node.
  15830. pp$3.initFunction = function(node) {
  15831. node.id = null;
  15832. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  15833. if (this.options.ecmaVersion >= 8) { node.async = false; }
  15834. };
  15835. // Parse object or class method.
  15836. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  15837. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15838. this.initFunction(node);
  15839. if (this.options.ecmaVersion >= 6)
  15840. { node.generator = isGenerator; }
  15841. if (this.options.ecmaVersion >= 8)
  15842. { node.async = !!isAsync; }
  15843. this.yieldPos = 0;
  15844. this.awaitPos = 0;
  15845. this.awaitIdentPos = 0;
  15846. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  15847. this.expect(types.parenL);
  15848. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  15849. this.checkYieldAwaitInDefaultParams();
  15850. this.parseFunctionBody(node, false, true);
  15851. this.yieldPos = oldYieldPos;
  15852. this.awaitPos = oldAwaitPos;
  15853. this.awaitIdentPos = oldAwaitIdentPos;
  15854. return this.finishNode(node, "FunctionExpression")
  15855. };
  15856. // Parse arrow function expression with given parameters.
  15857. pp$3.parseArrowExpression = function(node, params, isAsync) {
  15858. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15859. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  15860. this.initFunction(node);
  15861. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  15862. this.yieldPos = 0;
  15863. this.awaitPos = 0;
  15864. this.awaitIdentPos = 0;
  15865. node.params = this.toAssignableList(params, true);
  15866. this.parseFunctionBody(node, true, false);
  15867. this.yieldPos = oldYieldPos;
  15868. this.awaitPos = oldAwaitPos;
  15869. this.awaitIdentPos = oldAwaitIdentPos;
  15870. return this.finishNode(node, "ArrowFunctionExpression")
  15871. };
  15872. // Parse function body and check parameters.
  15873. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  15874. var isExpression = isArrowFunction && this.type !== types.braceL;
  15875. var oldStrict = this.strict, useStrict = false;
  15876. if (isExpression) {
  15877. node.body = this.parseMaybeAssign();
  15878. node.expression = true;
  15879. this.checkParams(node, false);
  15880. } else {
  15881. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  15882. if (!oldStrict || nonSimple) {
  15883. useStrict = this.strictDirective(this.end);
  15884. // If this is a strict mode function, verify that argument names
  15885. // are not repeated, and it does not try to bind the words `eval`
  15886. // or `arguments`.
  15887. if (useStrict && nonSimple)
  15888. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  15889. }
  15890. // Start a new scope with regard to labels and the `inFunction`
  15891. // flag (restore them to their old value afterwards).
  15892. var oldLabels = this.labels;
  15893. this.labels = [];
  15894. if (useStrict) { this.strict = true; }
  15895. // Add the params to varDeclaredNames to ensure that an error is thrown
  15896. // if a let/const declaration in the function clashes with one of the params.
  15897. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  15898. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  15899. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  15900. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  15901. node.expression = false;
  15902. this.adaptDirectivePrologue(node.body.body);
  15903. this.labels = oldLabels;
  15904. }
  15905. this.exitScope();
  15906. };
  15907. pp$3.isSimpleParamList = function(params) {
  15908. for (var i = 0, list = params; i < list.length; i += 1)
  15909. {
  15910. var param = list[i];
  15911. if (param.type !== "Identifier") { return false
  15912. } }
  15913. return true
  15914. };
  15915. // Checks function params for various disallowed patterns such as using "eval"
  15916. // or "arguments" and duplicate parameters.
  15917. pp$3.checkParams = function(node, allowDuplicates) {
  15918. var nameHash = Object.create(null);
  15919. for (var i = 0, list = node.params; i < list.length; i += 1)
  15920. {
  15921. var param = list[i];
  15922. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  15923. }
  15924. };
  15925. // Parses a comma-separated list of expressions, and returns them as
  15926. // an array. `close` is the token type that ends the list, and
  15927. // `allowEmpty` can be turned on to allow subsequent commas with
  15928. // nothing in between them to be parsed as `null` (which is needed
  15929. // for array literals).
  15930. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  15931. var elts = [], first = true;
  15932. while (!this.eat(close)) {
  15933. if (!first) {
  15934. this.expect(types.comma);
  15935. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  15936. } else { first = false; }
  15937. var elt = (void 0);
  15938. if (allowEmpty && this.type === types.comma)
  15939. { elt = null; }
  15940. else if (this.type === types.ellipsis) {
  15941. elt = this.parseSpread(refDestructuringErrors);
  15942. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  15943. { refDestructuringErrors.trailingComma = this.start; }
  15944. } else {
  15945. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  15946. }
  15947. elts.push(elt);
  15948. }
  15949. return elts
  15950. };
  15951. pp$3.checkUnreserved = function(ref) {
  15952. var start = ref.start;
  15953. var end = ref.end;
  15954. var name = ref.name;
  15955. if (this.inGenerator && name === "yield")
  15956. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  15957. if (this.inAsync && name === "await")
  15958. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  15959. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  15960. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  15961. if (this.keywords.test(name))
  15962. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  15963. if (this.options.ecmaVersion < 6 &&
  15964. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  15965. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  15966. if (re.test(name)) {
  15967. if (!this.inAsync && name === "await")
  15968. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  15969. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  15970. }
  15971. };
  15972. // Parse the next token as an identifier. If `liberal` is true (used
  15973. // when parsing properties), it will also convert keywords into
  15974. // identifiers.
  15975. pp$3.parseIdent = function(liberal, isBinding) {
  15976. var node = this.startNode();
  15977. if (this.type === types.name) {
  15978. node.name = this.value;
  15979. } else if (this.type.keyword) {
  15980. node.name = this.type.keyword;
  15981. // To fix https://github.com/acornjs/acorn/issues/575
  15982. // `class` and `function` keywords push new context into this.context.
  15983. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  15984. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  15985. if ((node.name === "class" || node.name === "function") &&
  15986. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  15987. this.context.pop();
  15988. }
  15989. } else {
  15990. this.unexpected();
  15991. }
  15992. this.next(!!liberal);
  15993. this.finishNode(node, "Identifier");
  15994. if (!liberal) {
  15995. this.checkUnreserved(node);
  15996. if (node.name === "await" && !this.awaitIdentPos)
  15997. { this.awaitIdentPos = node.start; }
  15998. }
  15999. return node
  16000. };
  16001. pp$3.parsePrivateIdent = function() {
  16002. var node = this.startNode();
  16003. if (this.type === types.privateId) {
  16004. node.name = this.value;
  16005. } else {
  16006. this.unexpected();
  16007. }
  16008. this.next();
  16009. this.finishNode(node, "PrivateIdentifier");
  16010. // For validating existence
  16011. if (this.privateNameStack.length === 0) {
  16012. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  16013. } else {
  16014. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  16015. }
  16016. return node
  16017. };
  16018. // Parses yield expression inside generator.
  16019. pp$3.parseYield = function(forInit) {
  16020. if (!this.yieldPos) { this.yieldPos = this.start; }
  16021. var node = this.startNode();
  16022. this.next();
  16023. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  16024. node.delegate = false;
  16025. node.argument = null;
  16026. } else {
  16027. node.delegate = this.eat(types.star);
  16028. node.argument = this.parseMaybeAssign(forInit);
  16029. }
  16030. return this.finishNode(node, "YieldExpression")
  16031. };
  16032. pp$3.parseAwait = function() {
  16033. if (!this.awaitPos) { this.awaitPos = this.start; }
  16034. var node = this.startNode();
  16035. this.next();
  16036. node.argument = this.parseMaybeUnary(null, true);
  16037. return this.finishNode(node, "AwaitExpression")
  16038. };
  16039. var pp$4 = Parser.prototype;
  16040. // This function is used to raise exceptions on parse errors. It
  16041. // takes an offset integer (into the current `input`) to indicate
  16042. // the location of the error, attaches the position to the end
  16043. // of the error message, and then raises a `SyntaxError` with that
  16044. // message.
  16045. pp$4.raise = function(pos, message) {
  16046. var loc = getLineInfo(this.input, pos);
  16047. message += " (" + loc.line + ":" + loc.column + ")";
  16048. var err = new SyntaxError(message);
  16049. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  16050. throw err
  16051. };
  16052. pp$4.raiseRecoverable = pp$4.raise;
  16053. pp$4.curPosition = function() {
  16054. if (this.options.locations) {
  16055. return new Position(this.curLine, this.pos - this.lineStart)
  16056. }
  16057. };
  16058. var pp$5 = Parser.prototype;
  16059. var Scope = function Scope(flags) {
  16060. this.flags = flags;
  16061. // A list of var-declared names in the current lexical scope
  16062. this.var = [];
  16063. // A list of lexically-declared names in the current lexical scope
  16064. this.lexical = [];
  16065. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  16066. this.functions = [];
  16067. // A switch to disallow the identifier reference 'arguments'
  16068. this.inClassFieldInit = false;
  16069. };
  16070. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  16071. pp$5.enterScope = function(flags) {
  16072. this.scopeStack.push(new Scope(flags));
  16073. };
  16074. pp$5.exitScope = function() {
  16075. this.scopeStack.pop();
  16076. };
  16077. // The spec says:
  16078. // > At the top level of a function, or script, function declarations are
  16079. // > treated like var declarations rather than like lexical declarations.
  16080. pp$5.treatFunctionsAsVarInScope = function(scope) {
  16081. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  16082. };
  16083. pp$5.declareName = function(name, bindingType, pos) {
  16084. var redeclared = false;
  16085. if (bindingType === BIND_LEXICAL) {
  16086. var scope = this.currentScope();
  16087. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  16088. scope.lexical.push(name);
  16089. if (this.inModule && (scope.flags & SCOPE_TOP))
  16090. { delete this.undefinedExports[name]; }
  16091. } else if (bindingType === BIND_SIMPLE_CATCH) {
  16092. var scope$1 = this.currentScope();
  16093. scope$1.lexical.push(name);
  16094. } else if (bindingType === BIND_FUNCTION) {
  16095. var scope$2 = this.currentScope();
  16096. if (this.treatFunctionsAsVar)
  16097. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  16098. else
  16099. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  16100. scope$2.functions.push(name);
  16101. } else {
  16102. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  16103. var scope$3 = this.scopeStack[i];
  16104. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  16105. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  16106. redeclared = true;
  16107. break
  16108. }
  16109. scope$3.var.push(name);
  16110. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  16111. { delete this.undefinedExports[name]; }
  16112. if (scope$3.flags & SCOPE_VAR) { break }
  16113. }
  16114. }
  16115. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  16116. };
  16117. pp$5.checkLocalExport = function(id) {
  16118. // scope.functions must be empty as Module code is always strict.
  16119. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  16120. this.scopeStack[0].var.indexOf(id.name) === -1) {
  16121. this.undefinedExports[id.name] = id;
  16122. }
  16123. };
  16124. pp$5.currentScope = function() {
  16125. return this.scopeStack[this.scopeStack.length - 1]
  16126. };
  16127. pp$5.currentVarScope = function() {
  16128. for (var i = this.scopeStack.length - 1;; i--) {
  16129. var scope = this.scopeStack[i];
  16130. if (scope.flags & SCOPE_VAR) { return scope }
  16131. }
  16132. };
  16133. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  16134. pp$5.currentThisScope = function() {
  16135. for (var i = this.scopeStack.length - 1;; i--) {
  16136. var scope = this.scopeStack[i];
  16137. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  16138. }
  16139. };
  16140. var Node = function Node(parser, pos, loc) {
  16141. this.type = "";
  16142. this.start = pos;
  16143. this.end = 0;
  16144. if (parser.options.locations)
  16145. { this.loc = new SourceLocation(parser, loc); }
  16146. if (parser.options.directSourceFile)
  16147. { this.sourceFile = parser.options.directSourceFile; }
  16148. if (parser.options.ranges)
  16149. { this.range = [pos, 0]; }
  16150. };
  16151. // Start an AST node, attaching a start offset.
  16152. var pp$6 = Parser.prototype;
  16153. pp$6.startNode = function() {
  16154. return new Node(this, this.start, this.startLoc)
  16155. };
  16156. pp$6.startNodeAt = function(pos, loc) {
  16157. return new Node(this, pos, loc)
  16158. };
  16159. // Finish an AST node, adding `type` and `end` properties.
  16160. function finishNodeAt(node, type, pos, loc) {
  16161. node.type = type;
  16162. node.end = pos;
  16163. if (this.options.locations)
  16164. { node.loc.end = loc; }
  16165. if (this.options.ranges)
  16166. { node.range[1] = pos; }
  16167. return node
  16168. }
  16169. pp$6.finishNode = function(node, type) {
  16170. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  16171. };
  16172. // Finish node at given position
  16173. pp$6.finishNodeAt = function(node, type, pos, loc) {
  16174. return finishNodeAt.call(this, node, type, pos, loc)
  16175. };
  16176. pp$6.copyNode = function(node) {
  16177. var newNode = new Node(this, node.start, this.startLoc);
  16178. for (var prop in node) { newNode[prop] = node[prop]; }
  16179. return newNode
  16180. };
  16181. // The algorithm used to determine whether a regexp can appear at a
  16182. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  16183. this.token = token;
  16184. this.isExpr = !!isExpr;
  16185. this.preserveSpace = !!preserveSpace;
  16186. this.override = override;
  16187. this.generator = !!generator;
  16188. };
  16189. var types$1 = {
  16190. b_stat: new TokContext("{", false),
  16191. b_expr: new TokContext("{", true),
  16192. b_tmpl: new TokContext("${", false),
  16193. p_stat: new TokContext("(", false),
  16194. p_expr: new TokContext("(", true),
  16195. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  16196. f_stat: new TokContext("function", false),
  16197. f_expr: new TokContext("function", true),
  16198. f_expr_gen: new TokContext("function", true, false, null, true),
  16199. f_gen: new TokContext("function", false, false, null, true)
  16200. };
  16201. var pp$7 = Parser.prototype;
  16202. pp$7.initialContext = function() {
  16203. return [types$1.b_stat]
  16204. };
  16205. pp$7.braceIsBlock = function(prevType) {
  16206. var parent = this.curContext();
  16207. if (parent === types$1.f_expr || parent === types$1.f_stat)
  16208. { return true }
  16209. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  16210. { return !parent.isExpr }
  16211. // The check for `tt.name && exprAllowed` detects whether we are
  16212. // after a `yield` or `of` construct. See the `updateContext` for
  16213. // `tt.name`.
  16214. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  16215. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  16216. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  16217. { return true }
  16218. if (prevType === types.braceL)
  16219. { return parent === types$1.b_stat }
  16220. if (prevType === types._var || prevType === types._const || prevType === types.name)
  16221. { return false }
  16222. return !this.exprAllowed
  16223. };
  16224. pp$7.inGeneratorContext = function() {
  16225. for (var i = this.context.length - 1; i >= 1; i--) {
  16226. var context = this.context[i];
  16227. if (context.token === "function")
  16228. { return context.generator }
  16229. }
  16230. return false
  16231. };
  16232. pp$7.updateContext = function(prevType) {
  16233. var update, type = this.type;
  16234. if (type.keyword && prevType === types.dot)
  16235. { this.exprAllowed = false; }
  16236. else if (update = type.updateContext)
  16237. { update.call(this, prevType); }
  16238. else
  16239. { this.exprAllowed = type.beforeExpr; }
  16240. };
  16241. // Token-specific context update code
  16242. types.parenR.updateContext = types.braceR.updateContext = function() {
  16243. if (this.context.length === 1) {
  16244. this.exprAllowed = true;
  16245. return
  16246. }
  16247. var out = this.context.pop();
  16248. if (out === types$1.b_stat && this.curContext().token === "function") {
  16249. out = this.context.pop();
  16250. }
  16251. this.exprAllowed = !out.isExpr;
  16252. };
  16253. types.braceL.updateContext = function(prevType) {
  16254. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  16255. this.exprAllowed = true;
  16256. };
  16257. types.dollarBraceL.updateContext = function() {
  16258. this.context.push(types$1.b_tmpl);
  16259. this.exprAllowed = true;
  16260. };
  16261. types.parenL.updateContext = function(prevType) {
  16262. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  16263. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  16264. this.exprAllowed = true;
  16265. };
  16266. types.incDec.updateContext = function() {
  16267. // tokExprAllowed stays unchanged
  16268. };
  16269. types._function.updateContext = types._class.updateContext = function(prevType) {
  16270. if (prevType.beforeExpr && prevType !== types._else &&
  16271. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  16272. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  16273. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  16274. { this.context.push(types$1.f_expr); }
  16275. else
  16276. { this.context.push(types$1.f_stat); }
  16277. this.exprAllowed = false;
  16278. };
  16279. types.backQuote.updateContext = function() {
  16280. if (this.curContext() === types$1.q_tmpl)
  16281. { this.context.pop(); }
  16282. else
  16283. { this.context.push(types$1.q_tmpl); }
  16284. this.exprAllowed = false;
  16285. };
  16286. types.star.updateContext = function(prevType) {
  16287. if (prevType === types._function) {
  16288. var index = this.context.length - 1;
  16289. if (this.context[index] === types$1.f_expr)
  16290. { this.context[index] = types$1.f_expr_gen; }
  16291. else
  16292. { this.context[index] = types$1.f_gen; }
  16293. }
  16294. this.exprAllowed = true;
  16295. };
  16296. types.name.updateContext = function(prevType) {
  16297. var allowed = false;
  16298. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  16299. if (this.value === "of" && !this.exprAllowed ||
  16300. this.value === "yield" && this.inGeneratorContext())
  16301. { allowed = true; }
  16302. }
  16303. this.exprAllowed = allowed;
  16304. };
  16305. // This file contains Unicode properties extracted from the ECMAScript
  16306. // specification. The lists are extracted like so:
  16307. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  16308. // #table-binary-unicode-properties
  16309. 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";
  16310. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  16311. var ecma11BinaryProperties = ecma10BinaryProperties;
  16312. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  16313. var unicodeBinaryProperties = {
  16314. 9: ecma9BinaryProperties,
  16315. 10: ecma10BinaryProperties,
  16316. 11: ecma11BinaryProperties,
  16317. 12: ecma12BinaryProperties
  16318. };
  16319. // #table-unicode-general-category-values
  16320. 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";
  16321. // #table-unicode-script-values
  16322. var ecma9ScriptValues = "Adlam Adlm Ahom 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 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";
  16323. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  16324. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  16325. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  16326. var unicodeScriptValues = {
  16327. 9: ecma9ScriptValues,
  16328. 10: ecma10ScriptValues,
  16329. 11: ecma11ScriptValues,
  16330. 12: ecma12ScriptValues
  16331. };
  16332. var data = {};
  16333. function buildUnicodeData(ecmaVersion) {
  16334. var d = data[ecmaVersion] = {
  16335. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  16336. nonBinary: {
  16337. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  16338. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  16339. }
  16340. };
  16341. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  16342. d.nonBinary.gc = d.nonBinary.General_Category;
  16343. d.nonBinary.sc = d.nonBinary.Script;
  16344. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  16345. }
  16346. buildUnicodeData(9);
  16347. buildUnicodeData(10);
  16348. buildUnicodeData(11);
  16349. buildUnicodeData(12);
  16350. var pp$8 = Parser.prototype;
  16351. var RegExpValidationState = function RegExpValidationState(parser) {
  16352. this.parser = parser;
  16353. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  16354. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  16355. this.source = "";
  16356. this.flags = "";
  16357. this.start = 0;
  16358. this.switchU = false;
  16359. this.switchN = false;
  16360. this.pos = 0;
  16361. this.lastIntValue = 0;
  16362. this.lastStringValue = "";
  16363. this.lastAssertionIsQuantifiable = false;
  16364. this.numCapturingParens = 0;
  16365. this.maxBackReference = 0;
  16366. this.groupNames = [];
  16367. this.backReferenceNames = [];
  16368. };
  16369. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  16370. var unicode = flags.indexOf("u") !== -1;
  16371. this.start = start | 0;
  16372. this.source = pattern + "";
  16373. this.flags = flags;
  16374. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  16375. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  16376. };
  16377. RegExpValidationState.prototype.raise = function raise (message) {
  16378. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  16379. };
  16380. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  16381. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  16382. RegExpValidationState.prototype.at = function at (i, forceU) {
  16383. if ( forceU === void 0 ) forceU = false;
  16384. var s = this.source;
  16385. var l = s.length;
  16386. if (i >= l) {
  16387. return -1
  16388. }
  16389. var c = s.charCodeAt(i);
  16390. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  16391. return c
  16392. }
  16393. var next = s.charCodeAt(i + 1);
  16394. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  16395. };
  16396. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  16397. if ( forceU === void 0 ) forceU = false;
  16398. var s = this.source;
  16399. var l = s.length;
  16400. if (i >= l) {
  16401. return l
  16402. }
  16403. var c = s.charCodeAt(i), next;
  16404. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  16405. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  16406. return i + 1
  16407. }
  16408. return i + 2
  16409. };
  16410. RegExpValidationState.prototype.current = function current (forceU) {
  16411. if ( forceU === void 0 ) forceU = false;
  16412. return this.at(this.pos, forceU)
  16413. };
  16414. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  16415. if ( forceU === void 0 ) forceU = false;
  16416. return this.at(this.nextIndex(this.pos, forceU), forceU)
  16417. };
  16418. RegExpValidationState.prototype.advance = function advance (forceU) {
  16419. if ( forceU === void 0 ) forceU = false;
  16420. this.pos = this.nextIndex(this.pos, forceU);
  16421. };
  16422. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  16423. if ( forceU === void 0 ) forceU = false;
  16424. if (this.current(forceU) === ch) {
  16425. this.advance(forceU);
  16426. return true
  16427. }
  16428. return false
  16429. };
  16430. function codePointToString(ch) {
  16431. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  16432. ch -= 0x10000;
  16433. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  16434. }
  16435. /**
  16436. * Validate the flags part of a given RegExpLiteral.
  16437. *
  16438. * @param {RegExpValidationState} state The state to validate RegExp.
  16439. * @returns {void}
  16440. */
  16441. pp$8.validateRegExpFlags = function(state) {
  16442. var validFlags = state.validFlags;
  16443. var flags = state.flags;
  16444. for (var i = 0; i < flags.length; i++) {
  16445. var flag = flags.charAt(i);
  16446. if (validFlags.indexOf(flag) === -1) {
  16447. this.raise(state.start, "Invalid regular expression flag");
  16448. }
  16449. if (flags.indexOf(flag, i + 1) > -1) {
  16450. this.raise(state.start, "Duplicate regular expression flag");
  16451. }
  16452. }
  16453. };
  16454. /**
  16455. * Validate the pattern part of a given RegExpLiteral.
  16456. *
  16457. * @param {RegExpValidationState} state The state to validate RegExp.
  16458. * @returns {void}
  16459. */
  16460. pp$8.validateRegExpPattern = function(state) {
  16461. this.regexp_pattern(state);
  16462. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  16463. // parsing contains a |GroupName|, reparse with the goal symbol
  16464. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  16465. // exception if _P_ did not conform to the grammar, if any elements of _P_
  16466. // were not matched by the parse, or if any Early Error conditions exist.
  16467. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  16468. state.switchN = true;
  16469. this.regexp_pattern(state);
  16470. }
  16471. };
  16472. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  16473. pp$8.regexp_pattern = function(state) {
  16474. state.pos = 0;
  16475. state.lastIntValue = 0;
  16476. state.lastStringValue = "";
  16477. state.lastAssertionIsQuantifiable = false;
  16478. state.numCapturingParens = 0;
  16479. state.maxBackReference = 0;
  16480. state.groupNames.length = 0;
  16481. state.backReferenceNames.length = 0;
  16482. this.regexp_disjunction(state);
  16483. if (state.pos !== state.source.length) {
  16484. // Make the same messages as V8.
  16485. if (state.eat(0x29 /* ) */)) {
  16486. state.raise("Unmatched ')'");
  16487. }
  16488. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  16489. state.raise("Lone quantifier brackets");
  16490. }
  16491. }
  16492. if (state.maxBackReference > state.numCapturingParens) {
  16493. state.raise("Invalid escape");
  16494. }
  16495. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  16496. var name = list[i];
  16497. if (state.groupNames.indexOf(name) === -1) {
  16498. state.raise("Invalid named capture referenced");
  16499. }
  16500. }
  16501. };
  16502. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  16503. pp$8.regexp_disjunction = function(state) {
  16504. this.regexp_alternative(state);
  16505. while (state.eat(0x7C /* | */)) {
  16506. this.regexp_alternative(state);
  16507. }
  16508. // Make the same message as V8.
  16509. if (this.regexp_eatQuantifier(state, true)) {
  16510. state.raise("Nothing to repeat");
  16511. }
  16512. if (state.eat(0x7B /* { */)) {
  16513. state.raise("Lone quantifier brackets");
  16514. }
  16515. };
  16516. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  16517. pp$8.regexp_alternative = function(state) {
  16518. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  16519. { }
  16520. };
  16521. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  16522. pp$8.regexp_eatTerm = function(state) {
  16523. if (this.regexp_eatAssertion(state)) {
  16524. // Handle `QuantifiableAssertion Quantifier` alternative.
  16525. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  16526. // is a QuantifiableAssertion.
  16527. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  16528. // Make the same message as V8.
  16529. if (state.switchU) {
  16530. state.raise("Invalid quantifier");
  16531. }
  16532. }
  16533. return true
  16534. }
  16535. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  16536. this.regexp_eatQuantifier(state);
  16537. return true
  16538. }
  16539. return false
  16540. };
  16541. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  16542. pp$8.regexp_eatAssertion = function(state) {
  16543. var start = state.pos;
  16544. state.lastAssertionIsQuantifiable = false;
  16545. // ^, $
  16546. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  16547. return true
  16548. }
  16549. // \b \B
  16550. if (state.eat(0x5C /* \ */)) {
  16551. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  16552. return true
  16553. }
  16554. state.pos = start;
  16555. }
  16556. // Lookahead / Lookbehind
  16557. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  16558. var lookbehind = false;
  16559. if (this.options.ecmaVersion >= 9) {
  16560. lookbehind = state.eat(0x3C /* < */);
  16561. }
  16562. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  16563. this.regexp_disjunction(state);
  16564. if (!state.eat(0x29 /* ) */)) {
  16565. state.raise("Unterminated group");
  16566. }
  16567. state.lastAssertionIsQuantifiable = !lookbehind;
  16568. return true
  16569. }
  16570. }
  16571. state.pos = start;
  16572. return false
  16573. };
  16574. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  16575. pp$8.regexp_eatQuantifier = function(state, noError) {
  16576. if ( noError === void 0 ) noError = false;
  16577. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  16578. state.eat(0x3F /* ? */);
  16579. return true
  16580. }
  16581. return false
  16582. };
  16583. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  16584. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  16585. return (
  16586. state.eat(0x2A /* * */) ||
  16587. state.eat(0x2B /* + */) ||
  16588. state.eat(0x3F /* ? */) ||
  16589. this.regexp_eatBracedQuantifier(state, noError)
  16590. )
  16591. };
  16592. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  16593. var start = state.pos;
  16594. if (state.eat(0x7B /* { */)) {
  16595. var min = 0, max = -1;
  16596. if (this.regexp_eatDecimalDigits(state)) {
  16597. min = state.lastIntValue;
  16598. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  16599. max = state.lastIntValue;
  16600. }
  16601. if (state.eat(0x7D /* } */)) {
  16602. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  16603. if (max !== -1 && max < min && !noError) {
  16604. state.raise("numbers out of order in {} quantifier");
  16605. }
  16606. return true
  16607. }
  16608. }
  16609. if (state.switchU && !noError) {
  16610. state.raise("Incomplete quantifier");
  16611. }
  16612. state.pos = start;
  16613. }
  16614. return false
  16615. };
  16616. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  16617. pp$8.regexp_eatAtom = function(state) {
  16618. return (
  16619. this.regexp_eatPatternCharacters(state) ||
  16620. state.eat(0x2E /* . */) ||
  16621. this.regexp_eatReverseSolidusAtomEscape(state) ||
  16622. this.regexp_eatCharacterClass(state) ||
  16623. this.regexp_eatUncapturingGroup(state) ||
  16624. this.regexp_eatCapturingGroup(state)
  16625. )
  16626. };
  16627. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  16628. var start = state.pos;
  16629. if (state.eat(0x5C /* \ */)) {
  16630. if (this.regexp_eatAtomEscape(state)) {
  16631. return true
  16632. }
  16633. state.pos = start;
  16634. }
  16635. return false
  16636. };
  16637. pp$8.regexp_eatUncapturingGroup = function(state) {
  16638. var start = state.pos;
  16639. if (state.eat(0x28 /* ( */)) {
  16640. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  16641. this.regexp_disjunction(state);
  16642. if (state.eat(0x29 /* ) */)) {
  16643. return true
  16644. }
  16645. state.raise("Unterminated group");
  16646. }
  16647. state.pos = start;
  16648. }
  16649. return false
  16650. };
  16651. pp$8.regexp_eatCapturingGroup = function(state) {
  16652. if (state.eat(0x28 /* ( */)) {
  16653. if (this.options.ecmaVersion >= 9) {
  16654. this.regexp_groupSpecifier(state);
  16655. } else if (state.current() === 0x3F /* ? */) {
  16656. state.raise("Invalid group");
  16657. }
  16658. this.regexp_disjunction(state);
  16659. if (state.eat(0x29 /* ) */)) {
  16660. state.numCapturingParens += 1;
  16661. return true
  16662. }
  16663. state.raise("Unterminated group");
  16664. }
  16665. return false
  16666. };
  16667. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  16668. pp$8.regexp_eatExtendedAtom = function(state) {
  16669. return (
  16670. state.eat(0x2E /* . */) ||
  16671. this.regexp_eatReverseSolidusAtomEscape(state) ||
  16672. this.regexp_eatCharacterClass(state) ||
  16673. this.regexp_eatUncapturingGroup(state) ||
  16674. this.regexp_eatCapturingGroup(state) ||
  16675. this.regexp_eatInvalidBracedQuantifier(state) ||
  16676. this.regexp_eatExtendedPatternCharacter(state)
  16677. )
  16678. };
  16679. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  16680. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  16681. if (this.regexp_eatBracedQuantifier(state, true)) {
  16682. state.raise("Nothing to repeat");
  16683. }
  16684. return false
  16685. };
  16686. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  16687. pp$8.regexp_eatSyntaxCharacter = function(state) {
  16688. var ch = state.current();
  16689. if (isSyntaxCharacter(ch)) {
  16690. state.lastIntValue = ch;
  16691. state.advance();
  16692. return true
  16693. }
  16694. return false
  16695. };
  16696. function isSyntaxCharacter(ch) {
  16697. return (
  16698. ch === 0x24 /* $ */ ||
  16699. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  16700. ch === 0x2E /* . */ ||
  16701. ch === 0x3F /* ? */ ||
  16702. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  16703. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  16704. )
  16705. }
  16706. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  16707. // But eat eager.
  16708. pp$8.regexp_eatPatternCharacters = function(state) {
  16709. var start = state.pos;
  16710. var ch = 0;
  16711. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  16712. state.advance();
  16713. }
  16714. return state.pos !== start
  16715. };
  16716. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  16717. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  16718. var ch = state.current();
  16719. if (
  16720. ch !== -1 &&
  16721. ch !== 0x24 /* $ */ &&
  16722. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  16723. ch !== 0x2E /* . */ &&
  16724. ch !== 0x3F /* ? */ &&
  16725. ch !== 0x5B /* [ */ &&
  16726. ch !== 0x5E /* ^ */ &&
  16727. ch !== 0x7C /* | */
  16728. ) {
  16729. state.advance();
  16730. return true
  16731. }
  16732. return false
  16733. };
  16734. // GroupSpecifier ::
  16735. // [empty]
  16736. // `?` GroupName
  16737. pp$8.regexp_groupSpecifier = function(state) {
  16738. if (state.eat(0x3F /* ? */)) {
  16739. if (this.regexp_eatGroupName(state)) {
  16740. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  16741. state.raise("Duplicate capture group name");
  16742. }
  16743. state.groupNames.push(state.lastStringValue);
  16744. return
  16745. }
  16746. state.raise("Invalid group");
  16747. }
  16748. };
  16749. // GroupName ::
  16750. // `<` RegExpIdentifierName `>`
  16751. // Note: this updates `state.lastStringValue` property with the eaten name.
  16752. pp$8.regexp_eatGroupName = function(state) {
  16753. state.lastStringValue = "";
  16754. if (state.eat(0x3C /* < */)) {
  16755. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  16756. return true
  16757. }
  16758. state.raise("Invalid capture group name");
  16759. }
  16760. return false
  16761. };
  16762. // RegExpIdentifierName ::
  16763. // RegExpIdentifierStart
  16764. // RegExpIdentifierName RegExpIdentifierPart
  16765. // Note: this updates `state.lastStringValue` property with the eaten name.
  16766. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  16767. state.lastStringValue = "";
  16768. if (this.regexp_eatRegExpIdentifierStart(state)) {
  16769. state.lastStringValue += codePointToString(state.lastIntValue);
  16770. while (this.regexp_eatRegExpIdentifierPart(state)) {
  16771. state.lastStringValue += codePointToString(state.lastIntValue);
  16772. }
  16773. return true
  16774. }
  16775. return false
  16776. };
  16777. // RegExpIdentifierStart ::
  16778. // UnicodeIDStart
  16779. // `$`
  16780. // `_`
  16781. // `\` RegExpUnicodeEscapeSequence[+U]
  16782. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  16783. var start = state.pos;
  16784. var forceU = this.options.ecmaVersion >= 11;
  16785. var ch = state.current(forceU);
  16786. state.advance(forceU);
  16787. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  16788. ch = state.lastIntValue;
  16789. }
  16790. if (isRegExpIdentifierStart(ch)) {
  16791. state.lastIntValue = ch;
  16792. return true
  16793. }
  16794. state.pos = start;
  16795. return false
  16796. };
  16797. function isRegExpIdentifierStart(ch) {
  16798. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  16799. }
  16800. // RegExpIdentifierPart ::
  16801. // UnicodeIDContinue
  16802. // `$`
  16803. // `_`
  16804. // `\` RegExpUnicodeEscapeSequence[+U]
  16805. // <ZWNJ>
  16806. // <ZWJ>
  16807. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  16808. var start = state.pos;
  16809. var forceU = this.options.ecmaVersion >= 11;
  16810. var ch = state.current(forceU);
  16811. state.advance(forceU);
  16812. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  16813. ch = state.lastIntValue;
  16814. }
  16815. if (isRegExpIdentifierPart(ch)) {
  16816. state.lastIntValue = ch;
  16817. return true
  16818. }
  16819. state.pos = start;
  16820. return false
  16821. };
  16822. function isRegExpIdentifierPart(ch) {
  16823. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  16824. }
  16825. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  16826. pp$8.regexp_eatAtomEscape = function(state) {
  16827. if (
  16828. this.regexp_eatBackReference(state) ||
  16829. this.regexp_eatCharacterClassEscape(state) ||
  16830. this.regexp_eatCharacterEscape(state) ||
  16831. (state.switchN && this.regexp_eatKGroupName(state))
  16832. ) {
  16833. return true
  16834. }
  16835. if (state.switchU) {
  16836. // Make the same message as V8.
  16837. if (state.current() === 0x63 /* c */) {
  16838. state.raise("Invalid unicode escape");
  16839. }
  16840. state.raise("Invalid escape");
  16841. }
  16842. return false
  16843. };
  16844. pp$8.regexp_eatBackReference = function(state) {
  16845. var start = state.pos;
  16846. if (this.regexp_eatDecimalEscape(state)) {
  16847. var n = state.lastIntValue;
  16848. if (state.switchU) {
  16849. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  16850. if (n > state.maxBackReference) {
  16851. state.maxBackReference = n;
  16852. }
  16853. return true
  16854. }
  16855. if (n <= state.numCapturingParens) {
  16856. return true
  16857. }
  16858. state.pos = start;
  16859. }
  16860. return false
  16861. };
  16862. pp$8.regexp_eatKGroupName = function(state) {
  16863. if (state.eat(0x6B /* k */)) {
  16864. if (this.regexp_eatGroupName(state)) {
  16865. state.backReferenceNames.push(state.lastStringValue);
  16866. return true
  16867. }
  16868. state.raise("Invalid named reference");
  16869. }
  16870. return false
  16871. };
  16872. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  16873. pp$8.regexp_eatCharacterEscape = function(state) {
  16874. return (
  16875. this.regexp_eatControlEscape(state) ||
  16876. this.regexp_eatCControlLetter(state) ||
  16877. this.regexp_eatZero(state) ||
  16878. this.regexp_eatHexEscapeSequence(state) ||
  16879. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  16880. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  16881. this.regexp_eatIdentityEscape(state)
  16882. )
  16883. };
  16884. pp$8.regexp_eatCControlLetter = function(state) {
  16885. var start = state.pos;
  16886. if (state.eat(0x63 /* c */)) {
  16887. if (this.regexp_eatControlLetter(state)) {
  16888. return true
  16889. }
  16890. state.pos = start;
  16891. }
  16892. return false
  16893. };
  16894. pp$8.regexp_eatZero = function(state) {
  16895. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  16896. state.lastIntValue = 0;
  16897. state.advance();
  16898. return true
  16899. }
  16900. return false
  16901. };
  16902. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  16903. pp$8.regexp_eatControlEscape = function(state) {
  16904. var ch = state.current();
  16905. if (ch === 0x74 /* t */) {
  16906. state.lastIntValue = 0x09; /* \t */
  16907. state.advance();
  16908. return true
  16909. }
  16910. if (ch === 0x6E /* n */) {
  16911. state.lastIntValue = 0x0A; /* \n */
  16912. state.advance();
  16913. return true
  16914. }
  16915. if (ch === 0x76 /* v */) {
  16916. state.lastIntValue = 0x0B; /* \v */
  16917. state.advance();
  16918. return true
  16919. }
  16920. if (ch === 0x66 /* f */) {
  16921. state.lastIntValue = 0x0C; /* \f */
  16922. state.advance();
  16923. return true
  16924. }
  16925. if (ch === 0x72 /* r */) {
  16926. state.lastIntValue = 0x0D; /* \r */
  16927. state.advance();
  16928. return true
  16929. }
  16930. return false
  16931. };
  16932. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  16933. pp$8.regexp_eatControlLetter = function(state) {
  16934. var ch = state.current();
  16935. if (isControlLetter(ch)) {
  16936. state.lastIntValue = ch % 0x20;
  16937. state.advance();
  16938. return true
  16939. }
  16940. return false
  16941. };
  16942. function isControlLetter(ch) {
  16943. return (
  16944. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  16945. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  16946. )
  16947. }
  16948. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  16949. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  16950. if ( forceU === void 0 ) forceU = false;
  16951. var start = state.pos;
  16952. var switchU = forceU || state.switchU;
  16953. if (state.eat(0x75 /* u */)) {
  16954. if (this.regexp_eatFixedHexDigits(state, 4)) {
  16955. var lead = state.lastIntValue;
  16956. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  16957. var leadSurrogateEnd = state.pos;
  16958. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  16959. var trail = state.lastIntValue;
  16960. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  16961. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  16962. return true
  16963. }
  16964. }
  16965. state.pos = leadSurrogateEnd;
  16966. state.lastIntValue = lead;
  16967. }
  16968. return true
  16969. }
  16970. if (
  16971. switchU &&
  16972. state.eat(0x7B /* { */) &&
  16973. this.regexp_eatHexDigits(state) &&
  16974. state.eat(0x7D /* } */) &&
  16975. isValidUnicode(state.lastIntValue)
  16976. ) {
  16977. return true
  16978. }
  16979. if (switchU) {
  16980. state.raise("Invalid unicode escape");
  16981. }
  16982. state.pos = start;
  16983. }
  16984. return false
  16985. };
  16986. function isValidUnicode(ch) {
  16987. return ch >= 0 && ch <= 0x10FFFF
  16988. }
  16989. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  16990. pp$8.regexp_eatIdentityEscape = function(state) {
  16991. if (state.switchU) {
  16992. if (this.regexp_eatSyntaxCharacter(state)) {
  16993. return true
  16994. }
  16995. if (state.eat(0x2F /* / */)) {
  16996. state.lastIntValue = 0x2F; /* / */
  16997. return true
  16998. }
  16999. return false
  17000. }
  17001. var ch = state.current();
  17002. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  17003. state.lastIntValue = ch;
  17004. state.advance();
  17005. return true
  17006. }
  17007. return false
  17008. };
  17009. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  17010. pp$8.regexp_eatDecimalEscape = function(state) {
  17011. state.lastIntValue = 0;
  17012. var ch = state.current();
  17013. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  17014. do {
  17015. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  17016. state.advance();
  17017. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  17018. return true
  17019. }
  17020. return false
  17021. };
  17022. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  17023. pp$8.regexp_eatCharacterClassEscape = function(state) {
  17024. var ch = state.current();
  17025. if (isCharacterClassEscape(ch)) {
  17026. state.lastIntValue = -1;
  17027. state.advance();
  17028. return true
  17029. }
  17030. if (
  17031. state.switchU &&
  17032. this.options.ecmaVersion >= 9 &&
  17033. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  17034. ) {
  17035. state.lastIntValue = -1;
  17036. state.advance();
  17037. if (
  17038. state.eat(0x7B /* { */) &&
  17039. this.regexp_eatUnicodePropertyValueExpression(state) &&
  17040. state.eat(0x7D /* } */)
  17041. ) {
  17042. return true
  17043. }
  17044. state.raise("Invalid property name");
  17045. }
  17046. return false
  17047. };
  17048. function isCharacterClassEscape(ch) {
  17049. return (
  17050. ch === 0x64 /* d */ ||
  17051. ch === 0x44 /* D */ ||
  17052. ch === 0x73 /* s */ ||
  17053. ch === 0x53 /* S */ ||
  17054. ch === 0x77 /* w */ ||
  17055. ch === 0x57 /* W */
  17056. )
  17057. }
  17058. // UnicodePropertyValueExpression ::
  17059. // UnicodePropertyName `=` UnicodePropertyValue
  17060. // LoneUnicodePropertyNameOrValue
  17061. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  17062. var start = state.pos;
  17063. // UnicodePropertyName `=` UnicodePropertyValue
  17064. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  17065. var name = state.lastStringValue;
  17066. if (this.regexp_eatUnicodePropertyValue(state)) {
  17067. var value = state.lastStringValue;
  17068. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  17069. return true
  17070. }
  17071. }
  17072. state.pos = start;
  17073. // LoneUnicodePropertyNameOrValue
  17074. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  17075. var nameOrValue = state.lastStringValue;
  17076. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  17077. return true
  17078. }
  17079. return false
  17080. };
  17081. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  17082. if (!has(state.unicodeProperties.nonBinary, name))
  17083. { state.raise("Invalid property name"); }
  17084. if (!state.unicodeProperties.nonBinary[name].test(value))
  17085. { state.raise("Invalid property value"); }
  17086. };
  17087. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  17088. if (!state.unicodeProperties.binary.test(nameOrValue))
  17089. { state.raise("Invalid property name"); }
  17090. };
  17091. // UnicodePropertyName ::
  17092. // UnicodePropertyNameCharacters
  17093. pp$8.regexp_eatUnicodePropertyName = function(state) {
  17094. var ch = 0;
  17095. state.lastStringValue = "";
  17096. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  17097. state.lastStringValue += codePointToString(ch);
  17098. state.advance();
  17099. }
  17100. return state.lastStringValue !== ""
  17101. };
  17102. function isUnicodePropertyNameCharacter(ch) {
  17103. return isControlLetter(ch) || ch === 0x5F /* _ */
  17104. }
  17105. // UnicodePropertyValue ::
  17106. // UnicodePropertyValueCharacters
  17107. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  17108. var ch = 0;
  17109. state.lastStringValue = "";
  17110. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  17111. state.lastStringValue += codePointToString(ch);
  17112. state.advance();
  17113. }
  17114. return state.lastStringValue !== ""
  17115. };
  17116. function isUnicodePropertyValueCharacter(ch) {
  17117. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  17118. }
  17119. // LoneUnicodePropertyNameOrValue ::
  17120. // UnicodePropertyValueCharacters
  17121. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  17122. return this.regexp_eatUnicodePropertyValue(state)
  17123. };
  17124. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  17125. pp$8.regexp_eatCharacterClass = function(state) {
  17126. if (state.eat(0x5B /* [ */)) {
  17127. state.eat(0x5E /* ^ */);
  17128. this.regexp_classRanges(state);
  17129. if (state.eat(0x5D /* ] */)) {
  17130. return true
  17131. }
  17132. // Unreachable since it threw "unterminated regular expression" error before.
  17133. state.raise("Unterminated character class");
  17134. }
  17135. return false
  17136. };
  17137. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  17138. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  17139. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  17140. pp$8.regexp_classRanges = function(state) {
  17141. while (this.regexp_eatClassAtom(state)) {
  17142. var left = state.lastIntValue;
  17143. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  17144. var right = state.lastIntValue;
  17145. if (state.switchU && (left === -1 || right === -1)) {
  17146. state.raise("Invalid character class");
  17147. }
  17148. if (left !== -1 && right !== -1 && left > right) {
  17149. state.raise("Range out of order in character class");
  17150. }
  17151. }
  17152. }
  17153. };
  17154. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  17155. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  17156. pp$8.regexp_eatClassAtom = function(state) {
  17157. var start = state.pos;
  17158. if (state.eat(0x5C /* \ */)) {
  17159. if (this.regexp_eatClassEscape(state)) {
  17160. return true
  17161. }
  17162. if (state.switchU) {
  17163. // Make the same message as V8.
  17164. var ch$1 = state.current();
  17165. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  17166. state.raise("Invalid class escape");
  17167. }
  17168. state.raise("Invalid escape");
  17169. }
  17170. state.pos = start;
  17171. }
  17172. var ch = state.current();
  17173. if (ch !== 0x5D /* ] */) {
  17174. state.lastIntValue = ch;
  17175. state.advance();
  17176. return true
  17177. }
  17178. return false
  17179. };
  17180. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  17181. pp$8.regexp_eatClassEscape = function(state) {
  17182. var start = state.pos;
  17183. if (state.eat(0x62 /* b */)) {
  17184. state.lastIntValue = 0x08; /* <BS> */
  17185. return true
  17186. }
  17187. if (state.switchU && state.eat(0x2D /* - */)) {
  17188. state.lastIntValue = 0x2D; /* - */
  17189. return true
  17190. }
  17191. if (!state.switchU && state.eat(0x63 /* c */)) {
  17192. if (this.regexp_eatClassControlLetter(state)) {
  17193. return true
  17194. }
  17195. state.pos = start;
  17196. }
  17197. return (
  17198. this.regexp_eatCharacterClassEscape(state) ||
  17199. this.regexp_eatCharacterEscape(state)
  17200. )
  17201. };
  17202. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  17203. pp$8.regexp_eatClassControlLetter = function(state) {
  17204. var ch = state.current();
  17205. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  17206. state.lastIntValue = ch % 0x20;
  17207. state.advance();
  17208. return true
  17209. }
  17210. return false
  17211. };
  17212. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  17213. pp$8.regexp_eatHexEscapeSequence = function(state) {
  17214. var start = state.pos;
  17215. if (state.eat(0x78 /* x */)) {
  17216. if (this.regexp_eatFixedHexDigits(state, 2)) {
  17217. return true
  17218. }
  17219. if (state.switchU) {
  17220. state.raise("Invalid escape");
  17221. }
  17222. state.pos = start;
  17223. }
  17224. return false
  17225. };
  17226. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  17227. pp$8.regexp_eatDecimalDigits = function(state) {
  17228. var start = state.pos;
  17229. var ch = 0;
  17230. state.lastIntValue = 0;
  17231. while (isDecimalDigit(ch = state.current())) {
  17232. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  17233. state.advance();
  17234. }
  17235. return state.pos !== start
  17236. };
  17237. function isDecimalDigit(ch) {
  17238. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  17239. }
  17240. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  17241. pp$8.regexp_eatHexDigits = function(state) {
  17242. var start = state.pos;
  17243. var ch = 0;
  17244. state.lastIntValue = 0;
  17245. while (isHexDigit(ch = state.current())) {
  17246. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  17247. state.advance();
  17248. }
  17249. return state.pos !== start
  17250. };
  17251. function isHexDigit(ch) {
  17252. return (
  17253. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  17254. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  17255. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  17256. )
  17257. }
  17258. function hexToInt(ch) {
  17259. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  17260. return 10 + (ch - 0x41 /* A */)
  17261. }
  17262. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  17263. return 10 + (ch - 0x61 /* a */)
  17264. }
  17265. return ch - 0x30 /* 0 */
  17266. }
  17267. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  17268. // Allows only 0-377(octal) i.e. 0-255(decimal).
  17269. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  17270. if (this.regexp_eatOctalDigit(state)) {
  17271. var n1 = state.lastIntValue;
  17272. if (this.regexp_eatOctalDigit(state)) {
  17273. var n2 = state.lastIntValue;
  17274. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  17275. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  17276. } else {
  17277. state.lastIntValue = n1 * 8 + n2;
  17278. }
  17279. } else {
  17280. state.lastIntValue = n1;
  17281. }
  17282. return true
  17283. }
  17284. return false
  17285. };
  17286. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  17287. pp$8.regexp_eatOctalDigit = function(state) {
  17288. var ch = state.current();
  17289. if (isOctalDigit(ch)) {
  17290. state.lastIntValue = ch - 0x30; /* 0 */
  17291. state.advance();
  17292. return true
  17293. }
  17294. state.lastIntValue = 0;
  17295. return false
  17296. };
  17297. function isOctalDigit(ch) {
  17298. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  17299. }
  17300. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  17301. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  17302. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  17303. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  17304. var start = state.pos;
  17305. state.lastIntValue = 0;
  17306. for (var i = 0; i < length; ++i) {
  17307. var ch = state.current();
  17308. if (!isHexDigit(ch)) {
  17309. state.pos = start;
  17310. return false
  17311. }
  17312. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  17313. state.advance();
  17314. }
  17315. return true
  17316. };
  17317. // Object type used to represent tokens. Note that normally, tokens
  17318. // simply exist as properties on the parser object. This is only
  17319. // used for the onToken callback and the external tokenizer.
  17320. var Token = function Token(p) {
  17321. this.type = p.type;
  17322. this.value = p.value;
  17323. this.start = p.start;
  17324. this.end = p.end;
  17325. if (p.options.locations)
  17326. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  17327. if (p.options.ranges)
  17328. { this.range = [p.start, p.end]; }
  17329. };
  17330. // ## Tokenizer
  17331. var pp$9 = Parser.prototype;
  17332. // Move to the next token
  17333. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  17334. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  17335. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  17336. if (this.options.onToken)
  17337. { this.options.onToken(new Token(this)); }
  17338. this.lastTokEnd = this.end;
  17339. this.lastTokStart = this.start;
  17340. this.lastTokEndLoc = this.endLoc;
  17341. this.lastTokStartLoc = this.startLoc;
  17342. this.nextToken();
  17343. };
  17344. pp$9.getToken = function() {
  17345. this.next();
  17346. return new Token(this)
  17347. };
  17348. // If we're in an ES6 environment, make parsers iterable
  17349. if (typeof Symbol !== "undefined")
  17350. { pp$9[Symbol.iterator] = function() {
  17351. var this$1$1 = this;
  17352. return {
  17353. next: function () {
  17354. var token = this$1$1.getToken();
  17355. return {
  17356. done: token.type === types.eof,
  17357. value: token
  17358. }
  17359. }
  17360. }
  17361. }; }
  17362. // Toggle strict mode. Re-reads the next number or string to please
  17363. // pedantic tests (`"use strict"; 010;` should fail).
  17364. pp$9.curContext = function() {
  17365. return this.context[this.context.length - 1]
  17366. };
  17367. // Read a single token, updating the parser object's token-related
  17368. // properties.
  17369. pp$9.nextToken = function() {
  17370. var curContext = this.curContext();
  17371. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  17372. this.start = this.pos;
  17373. if (this.options.locations) { this.startLoc = this.curPosition(); }
  17374. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  17375. if (curContext.override) { return curContext.override(this) }
  17376. else { this.readToken(this.fullCharCodeAtPos()); }
  17377. };
  17378. pp$9.readToken = function(code) {
  17379. // Identifier or keyword. '\uXXXX' sequences are allowed in
  17380. // identifiers, so '\' also dispatches to that.
  17381. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  17382. { return this.readWord() }
  17383. return this.getTokenFromCode(code)
  17384. };
  17385. pp$9.fullCharCodeAtPos = function() {
  17386. var code = this.input.charCodeAt(this.pos);
  17387. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  17388. var next = this.input.charCodeAt(this.pos + 1);
  17389. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  17390. };
  17391. pp$9.skipBlockComment = function() {
  17392. var startLoc = this.options.onComment && this.curPosition();
  17393. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  17394. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  17395. this.pos = end + 2;
  17396. if (this.options.locations) {
  17397. lineBreakG.lastIndex = start;
  17398. var match;
  17399. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  17400. ++this.curLine;
  17401. this.lineStart = match.index + match[0].length;
  17402. }
  17403. }
  17404. if (this.options.onComment)
  17405. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  17406. startLoc, this.curPosition()); }
  17407. };
  17408. pp$9.skipLineComment = function(startSkip) {
  17409. var start = this.pos;
  17410. var startLoc = this.options.onComment && this.curPosition();
  17411. var ch = this.input.charCodeAt(this.pos += startSkip);
  17412. while (this.pos < this.input.length && !isNewLine(ch)) {
  17413. ch = this.input.charCodeAt(++this.pos);
  17414. }
  17415. if (this.options.onComment)
  17416. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  17417. startLoc, this.curPosition()); }
  17418. };
  17419. // Called at the start of the parse and after every token. Skips
  17420. // whitespace and comments, and.
  17421. pp$9.skipSpace = function() {
  17422. loop: while (this.pos < this.input.length) {
  17423. var ch = this.input.charCodeAt(this.pos);
  17424. switch (ch) {
  17425. case 32: case 160: // ' '
  17426. ++this.pos;
  17427. break
  17428. case 13:
  17429. if (this.input.charCodeAt(this.pos + 1) === 10) {
  17430. ++this.pos;
  17431. }
  17432. case 10: case 8232: case 8233:
  17433. ++this.pos;
  17434. if (this.options.locations) {
  17435. ++this.curLine;
  17436. this.lineStart = this.pos;
  17437. }
  17438. break
  17439. case 47: // '/'
  17440. switch (this.input.charCodeAt(this.pos + 1)) {
  17441. case 42: // '*'
  17442. this.skipBlockComment();
  17443. break
  17444. case 47:
  17445. this.skipLineComment(2);
  17446. break
  17447. default:
  17448. break loop
  17449. }
  17450. break
  17451. default:
  17452. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  17453. ++this.pos;
  17454. } else {
  17455. break loop
  17456. }
  17457. }
  17458. }
  17459. };
  17460. // Called at the end of every token. Sets `end`, `val`, and
  17461. // maintains `context` and `exprAllowed`, and skips the space after
  17462. // the token, so that the next one's `start` will point at the
  17463. // right position.
  17464. pp$9.finishToken = function(type, val) {
  17465. this.end = this.pos;
  17466. if (this.options.locations) { this.endLoc = this.curPosition(); }
  17467. var prevType = this.type;
  17468. this.type = type;
  17469. this.value = val;
  17470. this.updateContext(prevType);
  17471. };
  17472. // ### Token reading
  17473. // This is the function that is called to fetch the next token. It
  17474. // is somewhat obscure, because it works in character codes rather
  17475. // than characters, and because operator parsing has been inlined
  17476. // into it.
  17477. //
  17478. // All in the name of speed.
  17479. //
  17480. pp$9.readToken_dot = function() {
  17481. var next = this.input.charCodeAt(this.pos + 1);
  17482. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  17483. var next2 = this.input.charCodeAt(this.pos + 2);
  17484. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  17485. this.pos += 3;
  17486. return this.finishToken(types.ellipsis)
  17487. } else {
  17488. ++this.pos;
  17489. return this.finishToken(types.dot)
  17490. }
  17491. };
  17492. pp$9.readToken_slash = function() { // '/'
  17493. var next = this.input.charCodeAt(this.pos + 1);
  17494. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  17495. if (next === 61) { return this.finishOp(types.assign, 2) }
  17496. return this.finishOp(types.slash, 1)
  17497. };
  17498. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  17499. var next = this.input.charCodeAt(this.pos + 1);
  17500. var size = 1;
  17501. var tokentype = code === 42 ? types.star : types.modulo;
  17502. // exponentiation operator ** and **=
  17503. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  17504. ++size;
  17505. tokentype = types.starstar;
  17506. next = this.input.charCodeAt(this.pos + 2);
  17507. }
  17508. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  17509. return this.finishOp(tokentype, size)
  17510. };
  17511. pp$9.readToken_pipe_amp = function(code) { // '|&'
  17512. var next = this.input.charCodeAt(this.pos + 1);
  17513. if (next === code) {
  17514. if (this.options.ecmaVersion >= 12) {
  17515. var next2 = this.input.charCodeAt(this.pos + 2);
  17516. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  17517. }
  17518. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  17519. }
  17520. if (next === 61) { return this.finishOp(types.assign, 2) }
  17521. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  17522. };
  17523. pp$9.readToken_caret = function() { // '^'
  17524. var next = this.input.charCodeAt(this.pos + 1);
  17525. if (next === 61) { return this.finishOp(types.assign, 2) }
  17526. return this.finishOp(types.bitwiseXOR, 1)
  17527. };
  17528. pp$9.readToken_plus_min = function(code) { // '+-'
  17529. var next = this.input.charCodeAt(this.pos + 1);
  17530. if (next === code) {
  17531. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  17532. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  17533. // A `-->` line comment
  17534. this.skipLineComment(3);
  17535. this.skipSpace();
  17536. return this.nextToken()
  17537. }
  17538. return this.finishOp(types.incDec, 2)
  17539. }
  17540. if (next === 61) { return this.finishOp(types.assign, 2) }
  17541. return this.finishOp(types.plusMin, 1)
  17542. };
  17543. pp$9.readToken_lt_gt = function(code) { // '<>'
  17544. var next = this.input.charCodeAt(this.pos + 1);
  17545. var size = 1;
  17546. if (next === code) {
  17547. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  17548. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  17549. return this.finishOp(types.bitShift, size)
  17550. }
  17551. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  17552. this.input.charCodeAt(this.pos + 3) === 45) {
  17553. // `<!--`, an XML-style comment that should be interpreted as a line comment
  17554. this.skipLineComment(4);
  17555. this.skipSpace();
  17556. return this.nextToken()
  17557. }
  17558. if (next === 61) { size = 2; }
  17559. return this.finishOp(types.relational, size)
  17560. };
  17561. pp$9.readToken_eq_excl = function(code) { // '=!'
  17562. var next = this.input.charCodeAt(this.pos + 1);
  17563. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  17564. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  17565. this.pos += 2;
  17566. return this.finishToken(types.arrow)
  17567. }
  17568. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  17569. };
  17570. pp$9.readToken_question = function() { // '?'
  17571. var ecmaVersion = this.options.ecmaVersion;
  17572. if (ecmaVersion >= 11) {
  17573. var next = this.input.charCodeAt(this.pos + 1);
  17574. if (next === 46) {
  17575. var next2 = this.input.charCodeAt(this.pos + 2);
  17576. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  17577. }
  17578. if (next === 63) {
  17579. if (ecmaVersion >= 12) {
  17580. var next2$1 = this.input.charCodeAt(this.pos + 2);
  17581. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  17582. }
  17583. return this.finishOp(types.coalesce, 2)
  17584. }
  17585. }
  17586. return this.finishOp(types.question, 1)
  17587. };
  17588. pp$9.readToken_numberSign = function() { // '#'
  17589. var ecmaVersion = this.options.ecmaVersion;
  17590. var code = 35; // '#'
  17591. if (ecmaVersion >= 13) {
  17592. ++this.pos;
  17593. code = this.fullCharCodeAtPos();
  17594. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  17595. return this.finishToken(types.privateId, this.readWord1())
  17596. }
  17597. }
  17598. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  17599. };
  17600. pp$9.getTokenFromCode = function(code) {
  17601. switch (code) {
  17602. // The interpretation of a dot depends on whether it is followed
  17603. // by a digit or another two dots.
  17604. case 46: // '.'
  17605. return this.readToken_dot()
  17606. // Punctuation tokens.
  17607. case 40: ++this.pos; return this.finishToken(types.parenL)
  17608. case 41: ++this.pos; return this.finishToken(types.parenR)
  17609. case 59: ++this.pos; return this.finishToken(types.semi)
  17610. case 44: ++this.pos; return this.finishToken(types.comma)
  17611. case 91: ++this.pos; return this.finishToken(types.bracketL)
  17612. case 93: ++this.pos; return this.finishToken(types.bracketR)
  17613. case 123: ++this.pos; return this.finishToken(types.braceL)
  17614. case 125: ++this.pos; return this.finishToken(types.braceR)
  17615. case 58: ++this.pos; return this.finishToken(types.colon)
  17616. case 96: // '`'
  17617. if (this.options.ecmaVersion < 6) { break }
  17618. ++this.pos;
  17619. return this.finishToken(types.backQuote)
  17620. case 48: // '0'
  17621. var next = this.input.charCodeAt(this.pos + 1);
  17622. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  17623. if (this.options.ecmaVersion >= 6) {
  17624. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  17625. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  17626. }
  17627. // Anything else beginning with a digit is an integer, octal
  17628. // number, or float.
  17629. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  17630. return this.readNumber(false)
  17631. // Quotes produce strings.
  17632. case 34: case 39: // '"', "'"
  17633. return this.readString(code)
  17634. // Operators are parsed inline in tiny state machines. '=' (61) is
  17635. // often referred to. `finishOp` simply skips the amount of
  17636. // characters it is given as second argument, and returns a token
  17637. // of the type given by its first argument.
  17638. case 47: // '/'
  17639. return this.readToken_slash()
  17640. case 37: case 42: // '%*'
  17641. return this.readToken_mult_modulo_exp(code)
  17642. case 124: case 38: // '|&'
  17643. return this.readToken_pipe_amp(code)
  17644. case 94: // '^'
  17645. return this.readToken_caret()
  17646. case 43: case 45: // '+-'
  17647. return this.readToken_plus_min(code)
  17648. case 60: case 62: // '<>'
  17649. return this.readToken_lt_gt(code)
  17650. case 61: case 33: // '=!'
  17651. return this.readToken_eq_excl(code)
  17652. case 63: // '?'
  17653. return this.readToken_question()
  17654. case 126: // '~'
  17655. return this.finishOp(types.prefix, 1)
  17656. case 35: // '#'
  17657. return this.readToken_numberSign()
  17658. }
  17659. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  17660. };
  17661. pp$9.finishOp = function(type, size) {
  17662. var str = this.input.slice(this.pos, this.pos + size);
  17663. this.pos += size;
  17664. return this.finishToken(type, str)
  17665. };
  17666. pp$9.readRegexp = function() {
  17667. var escaped, inClass, start = this.pos;
  17668. for (;;) {
  17669. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  17670. var ch = this.input.charAt(this.pos);
  17671. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  17672. if (!escaped) {
  17673. if (ch === "[") { inClass = true; }
  17674. else if (ch === "]" && inClass) { inClass = false; }
  17675. else if (ch === "/" && !inClass) { break }
  17676. escaped = ch === "\\";
  17677. } else { escaped = false; }
  17678. ++this.pos;
  17679. }
  17680. var pattern = this.input.slice(start, this.pos);
  17681. ++this.pos;
  17682. var flagsStart = this.pos;
  17683. var flags = this.readWord1();
  17684. if (this.containsEsc) { this.unexpected(flagsStart); }
  17685. // Validate pattern
  17686. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  17687. state.reset(start, pattern, flags);
  17688. this.validateRegExpFlags(state);
  17689. this.validateRegExpPattern(state);
  17690. // Create Literal#value property value.
  17691. var value = null;
  17692. try {
  17693. value = new RegExp(pattern, flags);
  17694. } catch (e) {
  17695. // ESTree requires null if it failed to instantiate RegExp object.
  17696. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  17697. }
  17698. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  17699. };
  17700. // Read an integer in the given radix. Return null if zero digits
  17701. // were read, the integer value otherwise. When `len` is given, this
  17702. // will return `null` unless the integer has exactly `len` digits.
  17703. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  17704. // `len` is used for character escape sequences. In that case, disallow separators.
  17705. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  17706. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  17707. // and isn't fraction part nor exponent part. In that case, if the first digit
  17708. // is zero then disallow separators.
  17709. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  17710. var start = this.pos, total = 0, lastCode = 0;
  17711. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  17712. var code = this.input.charCodeAt(this.pos), val = (void 0);
  17713. if (allowSeparators && code === 95) {
  17714. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  17715. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  17716. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  17717. lastCode = code;
  17718. continue
  17719. }
  17720. if (code >= 97) { val = code - 97 + 10; } // a
  17721. else if (code >= 65) { val = code - 65 + 10; } // A
  17722. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  17723. else { val = Infinity; }
  17724. if (val >= radix) { break }
  17725. lastCode = code;
  17726. total = total * radix + val;
  17727. }
  17728. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  17729. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  17730. return total
  17731. };
  17732. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  17733. if (isLegacyOctalNumericLiteral) {
  17734. return parseInt(str, 8)
  17735. }
  17736. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  17737. return parseFloat(str.replace(/_/g, ""))
  17738. }
  17739. function stringToBigInt(str) {
  17740. if (typeof BigInt !== "function") {
  17741. return null
  17742. }
  17743. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  17744. return BigInt(str.replace(/_/g, ""))
  17745. }
  17746. pp$9.readRadixNumber = function(radix) {
  17747. var start = this.pos;
  17748. this.pos += 2; // 0x
  17749. var val = this.readInt(radix);
  17750. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  17751. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  17752. val = stringToBigInt(this.input.slice(start, this.pos));
  17753. ++this.pos;
  17754. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  17755. return this.finishToken(types.num, val)
  17756. };
  17757. // Read an integer, octal integer, or floating-point number.
  17758. pp$9.readNumber = function(startsWithDot) {
  17759. var start = this.pos;
  17760. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  17761. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  17762. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  17763. var next = this.input.charCodeAt(this.pos);
  17764. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  17765. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  17766. ++this.pos;
  17767. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  17768. return this.finishToken(types.num, val$1)
  17769. }
  17770. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  17771. if (next === 46 && !octal) { // '.'
  17772. ++this.pos;
  17773. this.readInt(10);
  17774. next = this.input.charCodeAt(this.pos);
  17775. }
  17776. if ((next === 69 || next === 101) && !octal) { // 'eE'
  17777. next = this.input.charCodeAt(++this.pos);
  17778. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  17779. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  17780. }
  17781. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  17782. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  17783. return this.finishToken(types.num, val)
  17784. };
  17785. // Read a string value, interpreting backslash-escapes.
  17786. pp$9.readCodePoint = function() {
  17787. var ch = this.input.charCodeAt(this.pos), code;
  17788. if (ch === 123) { // '{'
  17789. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  17790. var codePos = ++this.pos;
  17791. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  17792. ++this.pos;
  17793. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  17794. } else {
  17795. code = this.readHexChar(4);
  17796. }
  17797. return code
  17798. };
  17799. function codePointToString$1(code) {
  17800. // UTF-16 Decoding
  17801. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  17802. code -= 0x10000;
  17803. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  17804. }
  17805. pp$9.readString = function(quote) {
  17806. var out = "", chunkStart = ++this.pos;
  17807. for (;;) {
  17808. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  17809. var ch = this.input.charCodeAt(this.pos);
  17810. if (ch === quote) { break }
  17811. if (ch === 92) { // '\'
  17812. out += this.input.slice(chunkStart, this.pos);
  17813. out += this.readEscapedChar(false);
  17814. chunkStart = this.pos;
  17815. } else {
  17816. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  17817. ++this.pos;
  17818. }
  17819. }
  17820. out += this.input.slice(chunkStart, this.pos++);
  17821. return this.finishToken(types.string, out)
  17822. };
  17823. // Reads template string tokens.
  17824. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  17825. pp$9.tryReadTemplateToken = function() {
  17826. this.inTemplateElement = true;
  17827. try {
  17828. this.readTmplToken();
  17829. } catch (err) {
  17830. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  17831. this.readInvalidTemplateToken();
  17832. } else {
  17833. throw err
  17834. }
  17835. }
  17836. this.inTemplateElement = false;
  17837. };
  17838. pp$9.invalidStringToken = function(position, message) {
  17839. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  17840. throw INVALID_TEMPLATE_ESCAPE_ERROR
  17841. } else {
  17842. this.raise(position, message);
  17843. }
  17844. };
  17845. pp$9.readTmplToken = function() {
  17846. var out = "", chunkStart = this.pos;
  17847. for (;;) {
  17848. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  17849. var ch = this.input.charCodeAt(this.pos);
  17850. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  17851. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  17852. if (ch === 36) {
  17853. this.pos += 2;
  17854. return this.finishToken(types.dollarBraceL)
  17855. } else {
  17856. ++this.pos;
  17857. return this.finishToken(types.backQuote)
  17858. }
  17859. }
  17860. out += this.input.slice(chunkStart, this.pos);
  17861. return this.finishToken(types.template, out)
  17862. }
  17863. if (ch === 92) { // '\'
  17864. out += this.input.slice(chunkStart, this.pos);
  17865. out += this.readEscapedChar(true);
  17866. chunkStart = this.pos;
  17867. } else if (isNewLine(ch)) {
  17868. out += this.input.slice(chunkStart, this.pos);
  17869. ++this.pos;
  17870. switch (ch) {
  17871. case 13:
  17872. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  17873. case 10:
  17874. out += "\n";
  17875. break
  17876. default:
  17877. out += String.fromCharCode(ch);
  17878. break
  17879. }
  17880. if (this.options.locations) {
  17881. ++this.curLine;
  17882. this.lineStart = this.pos;
  17883. }
  17884. chunkStart = this.pos;
  17885. } else {
  17886. ++this.pos;
  17887. }
  17888. }
  17889. };
  17890. // Reads a template token to search for the end, without validating any escape sequences
  17891. pp$9.readInvalidTemplateToken = function() {
  17892. for (; this.pos < this.input.length; this.pos++) {
  17893. switch (this.input[this.pos]) {
  17894. case "\\":
  17895. ++this.pos;
  17896. break
  17897. case "$":
  17898. if (this.input[this.pos + 1] !== "{") {
  17899. break
  17900. }
  17901. // falls through
  17902. case "`":
  17903. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  17904. // no default
  17905. }
  17906. }
  17907. this.raise(this.start, "Unterminated template");
  17908. };
  17909. // Used to read escaped characters
  17910. pp$9.readEscapedChar = function(inTemplate) {
  17911. var ch = this.input.charCodeAt(++this.pos);
  17912. ++this.pos;
  17913. switch (ch) {
  17914. case 110: return "\n" // 'n' -> '\n'
  17915. case 114: return "\r" // 'r' -> '\r'
  17916. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  17917. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  17918. case 116: return "\t" // 't' -> '\t'
  17919. case 98: return "\b" // 'b' -> '\b'
  17920. case 118: return "\u000b" // 'v' -> '\u000b'
  17921. case 102: return "\f" // 'f' -> '\f'
  17922. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  17923. case 10: // ' \n'
  17924. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  17925. return ""
  17926. case 56:
  17927. case 57:
  17928. if (this.strict) {
  17929. this.invalidStringToken(
  17930. this.pos - 1,
  17931. "Invalid escape sequence"
  17932. );
  17933. }
  17934. if (inTemplate) {
  17935. var codePos = this.pos - 1;
  17936. this.invalidStringToken(
  17937. codePos,
  17938. "Invalid escape sequence in template string"
  17939. );
  17940. return null
  17941. }
  17942. default:
  17943. if (ch >= 48 && ch <= 55) {
  17944. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  17945. var octal = parseInt(octalStr, 8);
  17946. if (octal > 255) {
  17947. octalStr = octalStr.slice(0, -1);
  17948. octal = parseInt(octalStr, 8);
  17949. }
  17950. this.pos += octalStr.length - 1;
  17951. ch = this.input.charCodeAt(this.pos);
  17952. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  17953. this.invalidStringToken(
  17954. this.pos - 1 - octalStr.length,
  17955. inTemplate
  17956. ? "Octal literal in template string"
  17957. : "Octal literal in strict mode"
  17958. );
  17959. }
  17960. return String.fromCharCode(octal)
  17961. }
  17962. if (isNewLine(ch)) {
  17963. // Unicode new line characters after \ get removed from output in both
  17964. // template literals and strings
  17965. return ""
  17966. }
  17967. return String.fromCharCode(ch)
  17968. }
  17969. };
  17970. // Used to read character escape sequences ('\x', '\u', '\U').
  17971. pp$9.readHexChar = function(len) {
  17972. var codePos = this.pos;
  17973. var n = this.readInt(16, len);
  17974. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  17975. return n
  17976. };
  17977. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  17978. // to whether the word contained a '\u' escape.
  17979. //
  17980. // Incrementally adds only escaped chars, adding other chunks as-is
  17981. // as a micro-optimization.
  17982. pp$9.readWord1 = function() {
  17983. this.containsEsc = false;
  17984. var word = "", first = true, chunkStart = this.pos;
  17985. var astral = this.options.ecmaVersion >= 6;
  17986. while (this.pos < this.input.length) {
  17987. var ch = this.fullCharCodeAtPos();
  17988. if (isIdentifierChar(ch, astral)) {
  17989. this.pos += ch <= 0xffff ? 1 : 2;
  17990. } else if (ch === 92) { // "\"
  17991. this.containsEsc = true;
  17992. word += this.input.slice(chunkStart, this.pos);
  17993. var escStart = this.pos;
  17994. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  17995. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  17996. ++this.pos;
  17997. var esc = this.readCodePoint();
  17998. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  17999. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  18000. word += codePointToString$1(esc);
  18001. chunkStart = this.pos;
  18002. } else {
  18003. break
  18004. }
  18005. first = false;
  18006. }
  18007. return word + this.input.slice(chunkStart, this.pos)
  18008. };
  18009. // Read an identifier or keyword token. Will check for reserved
  18010. // words when necessary.
  18011. pp$9.readWord = function() {
  18012. var word = this.readWord1();
  18013. var type = types.name;
  18014. if (this.keywords.test(word)) {
  18015. type = keywords$1[word];
  18016. }
  18017. return this.finishToken(type, word)
  18018. };
  18019. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  18020. var version = "8.4.0";
  18021. Parser.acorn = {
  18022. Parser: Parser,
  18023. version: version,
  18024. defaultOptions: defaultOptions,
  18025. Position: Position,
  18026. SourceLocation: SourceLocation,
  18027. getLineInfo: getLineInfo,
  18028. Node: Node,
  18029. TokenType: TokenType,
  18030. tokTypes: types,
  18031. keywordTypes: keywords$1,
  18032. TokContext: TokContext,
  18033. tokContexts: types$1,
  18034. isIdentifierChar: isIdentifierChar,
  18035. isIdentifierStart: isIdentifierStart,
  18036. Token: Token,
  18037. isNewLine: isNewLine,
  18038. lineBreak: lineBreak,
  18039. lineBreakG: lineBreakG,
  18040. nonASCIIwhitespace: nonASCIIwhitespace
  18041. };
  18042. const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
  18043. function mkdirpath(path$1) {
  18044. const dir = path.dirname(path$1);
  18045. try {
  18046. fs.readdirSync(dir);
  18047. }
  18048. catch (err) {
  18049. mkdirpath(dir);
  18050. try {
  18051. fs.mkdirSync(dir);
  18052. }
  18053. catch (err2) {
  18054. if (err2.code !== 'EEXIST') {
  18055. throw err2;
  18056. }
  18057. }
  18058. }
  18059. }
  18060. function writeFile(dest, data) {
  18061. return new Promise((fulfil, reject) => {
  18062. mkdirpath(dest);
  18063. fs.writeFile(dest, data, err => {
  18064. if (err) {
  18065. reject(err);
  18066. }
  18067. else {
  18068. fulfil();
  18069. }
  18070. });
  18071. });
  18072. }
  18073. class Queue {
  18074. constructor(maxParallel = 1) {
  18075. this.maxParallel = maxParallel;
  18076. this.queue = new Array();
  18077. this.workerCount = 0;
  18078. }
  18079. run(task) {
  18080. return new Promise((resolve, reject) => {
  18081. this.queue.push({ reject, resolve, task });
  18082. this.work();
  18083. });
  18084. }
  18085. async work() {
  18086. if (this.workerCount >= this.maxParallel)
  18087. return;
  18088. this.workerCount++;
  18089. let entry;
  18090. while ((entry = this.queue.shift())) {
  18091. const { reject, resolve, task } = entry;
  18092. try {
  18093. const result = await task();
  18094. resolve(result);
  18095. }
  18096. catch (err) {
  18097. reject(err);
  18098. }
  18099. }
  18100. this.workerCount--;
  18101. }
  18102. }
  18103. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions) {
  18104. let skipped = null;
  18105. let replaceContext = null;
  18106. if (skip) {
  18107. skipped = new Set();
  18108. for (const skippedCall of skip) {
  18109. if (source === skippedCall.source && importer === skippedCall.importer) {
  18110. skipped.add(skippedCall.plugin);
  18111. }
  18112. }
  18113. replaceContext = (pluginContext, plugin) => ({
  18114. ...pluginContext,
  18115. resolve: (source, importer, { custom, skipSelf } = BLANK) => {
  18116. return moduleLoaderResolveId(source, importer, custom, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  18117. }
  18118. });
  18119. }
  18120. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], replaceContext, skipped);
  18121. }
  18122. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions) {
  18123. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions);
  18124. if (pluginResult != null)
  18125. return pluginResult;
  18126. // external modules (non-entry modules that start with neither '.' or '/')
  18127. // are skipped at this stage.
  18128. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  18129. return null;
  18130. // `resolve` processes paths from right to left, prepending them until an
  18131. // absolute path is created. Absolute importees therefore shortcircuit the
  18132. // resolve call and require no special handing on our part.
  18133. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  18134. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks);
  18135. }
  18136. function addJsExtensionIfNecessary(file, preserveSymlinks) {
  18137. let found = findFile(file, preserveSymlinks);
  18138. if (found)
  18139. return found;
  18140. found = findFile(file + '.mjs', preserveSymlinks);
  18141. if (found)
  18142. return found;
  18143. found = findFile(file + '.js', preserveSymlinks);
  18144. return found;
  18145. }
  18146. function findFile(file, preserveSymlinks) {
  18147. try {
  18148. const stats = fs.lstatSync(file);
  18149. if (!preserveSymlinks && stats.isSymbolicLink())
  18150. return findFile(fs.realpathSync(file), preserveSymlinks);
  18151. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  18152. // check case
  18153. const name = path.basename(file);
  18154. const files = fs.readdirSync(path.dirname(file));
  18155. if (files.indexOf(name) !== -1)
  18156. return file;
  18157. }
  18158. }
  18159. catch (_a) {
  18160. // suppress
  18161. }
  18162. }
  18163. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  18164. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  18165. function throwPluginError(err, plugin, { hook, id } = {}) {
  18166. if (typeof err === 'string')
  18167. err = { message: err };
  18168. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  18169. err.pluginCode = err.code;
  18170. }
  18171. err.code = Errors.PLUGIN_ERROR;
  18172. err.plugin = plugin;
  18173. if (hook) {
  18174. err.hook = hook;
  18175. }
  18176. if (id) {
  18177. err.id = id;
  18178. }
  18179. return error(err);
  18180. }
  18181. const deprecatedHooks = [
  18182. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  18183. ];
  18184. function warnDeprecatedHooks(plugins, options) {
  18185. for (const { active, deprecated, replacement } of deprecatedHooks) {
  18186. for (const plugin of plugins) {
  18187. if (deprecated in plugin) {
  18188. warnDeprecation({
  18189. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  18190. plugin: plugin.name
  18191. }, active, options);
  18192. }
  18193. }
  18194. }
  18195. }
  18196. function createPluginCache(cache) {
  18197. return {
  18198. delete(id) {
  18199. return delete cache[id];
  18200. },
  18201. get(id) {
  18202. const item = cache[id];
  18203. if (!item)
  18204. return undefined;
  18205. item[0] = 0;
  18206. return item[1];
  18207. },
  18208. has(id) {
  18209. const item = cache[id];
  18210. if (!item)
  18211. return false;
  18212. item[0] = 0;
  18213. return true;
  18214. },
  18215. set(id, value) {
  18216. cache[id] = [0, value];
  18217. }
  18218. };
  18219. }
  18220. function getTrackedPluginCache(pluginCache, onUse) {
  18221. return {
  18222. delete(id) {
  18223. onUse();
  18224. return pluginCache.delete(id);
  18225. },
  18226. get(id) {
  18227. onUse();
  18228. return pluginCache.get(id);
  18229. },
  18230. has(id) {
  18231. onUse();
  18232. return pluginCache.has(id);
  18233. },
  18234. set(id, value) {
  18235. onUse();
  18236. return pluginCache.set(id, value);
  18237. }
  18238. };
  18239. }
  18240. const NO_CACHE = {
  18241. delete() {
  18242. return false;
  18243. },
  18244. get() {
  18245. return undefined;
  18246. },
  18247. has() {
  18248. return false;
  18249. },
  18250. set() { }
  18251. };
  18252. function uncacheablePluginError(pluginName) {
  18253. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  18254. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  18255. return error({
  18256. code: 'ANONYMOUS_PLUGIN_CACHE',
  18257. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  18258. });
  18259. }
  18260. return error({
  18261. code: 'DUPLICATE_PLUGIN_NAME',
  18262. 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).`
  18263. });
  18264. }
  18265. function getCacheForUncacheablePlugin(pluginName) {
  18266. return {
  18267. delete() {
  18268. return uncacheablePluginError(pluginName);
  18269. },
  18270. get() {
  18271. return uncacheablePluginError(pluginName);
  18272. },
  18273. has() {
  18274. return uncacheablePluginError(pluginName);
  18275. },
  18276. set() {
  18277. return uncacheablePluginError(pluginName);
  18278. }
  18279. };
  18280. }
  18281. function transform(source, module, pluginDriver, warn) {
  18282. const id = module.id;
  18283. const sourcemapChain = [];
  18284. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  18285. const originalCode = source.code;
  18286. let ast = source.ast;
  18287. const transformDependencies = [];
  18288. const emittedFiles = [];
  18289. let customTransformCache = false;
  18290. const useCustomTransformCache = () => (customTransformCache = true);
  18291. let curPlugin;
  18292. const curSource = source.code;
  18293. function transformReducer(previousCode, result, plugin) {
  18294. let code;
  18295. let map;
  18296. if (typeof result === 'string') {
  18297. code = result;
  18298. }
  18299. else if (result && typeof result === 'object') {
  18300. module.updateOptions(result);
  18301. if (result.code == null) {
  18302. if (result.map || result.ast) {
  18303. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  18304. }
  18305. return previousCode;
  18306. }
  18307. ({ code, map, ast } = result);
  18308. }
  18309. else {
  18310. return previousCode;
  18311. }
  18312. // strict null check allows 'null' maps to not be pushed to the chain,
  18313. // while 'undefined' gets the missing map warning
  18314. if (map !== null) {
  18315. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  18316. missing: true,
  18317. plugin: plugin.name
  18318. });
  18319. }
  18320. return code;
  18321. }
  18322. return pluginDriver
  18323. .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  18324. curPlugin = plugin;
  18325. return {
  18326. ...pluginContext,
  18327. addWatchFile(id) {
  18328. transformDependencies.push(id);
  18329. pluginContext.addWatchFile(id);
  18330. },
  18331. cache: customTransformCache
  18332. ? pluginContext.cache
  18333. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  18334. emitAsset(name, source) {
  18335. emittedFiles.push({ name, source, type: 'asset' });
  18336. return pluginContext.emitAsset(name, source);
  18337. },
  18338. emitChunk(id, options) {
  18339. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  18340. return pluginContext.emitChunk(id, options);
  18341. },
  18342. emitFile(emittedFile) {
  18343. emittedFiles.push(emittedFile);
  18344. return pluginDriver.emitFile(emittedFile);
  18345. },
  18346. error(err, pos) {
  18347. if (typeof err === 'string')
  18348. err = { message: err };
  18349. if (pos)
  18350. augmentCodeLocation(err, pos, curSource, id);
  18351. err.id = id;
  18352. err.hook = 'transform';
  18353. return pluginContext.error(err);
  18354. },
  18355. getCombinedSourcemap() {
  18356. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  18357. if (!combinedMap) {
  18358. const magicString = new MagicString$1(originalCode);
  18359. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  18360. }
  18361. if (originalSourcemap !== combinedMap) {
  18362. originalSourcemap = combinedMap;
  18363. sourcemapChain.length = 0;
  18364. }
  18365. return new SourceMap({
  18366. ...combinedMap,
  18367. file: null,
  18368. sourcesContent: combinedMap.sourcesContent
  18369. });
  18370. },
  18371. setAssetSource() {
  18372. return this.error({
  18373. code: 'INVALID_SETASSETSOURCE',
  18374. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  18375. });
  18376. },
  18377. warn(warning, pos) {
  18378. if (typeof warning === 'string')
  18379. warning = { message: warning };
  18380. if (pos)
  18381. augmentCodeLocation(warning, pos, curSource, id);
  18382. warning.id = id;
  18383. warning.hook = 'transform';
  18384. pluginContext.warn(warning);
  18385. }
  18386. };
  18387. })
  18388. .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
  18389. .then(code => {
  18390. if (!customTransformCache) {
  18391. // files emitted by a transform hook need to be emitted again if the hook is skipped
  18392. if (emittedFiles.length)
  18393. module.transformFiles = emittedFiles;
  18394. }
  18395. return {
  18396. ast,
  18397. code,
  18398. customTransformCache,
  18399. meta: module.info.meta,
  18400. originalCode,
  18401. originalSourcemap,
  18402. sourcemapChain,
  18403. transformDependencies
  18404. };
  18405. });
  18406. }
  18407. class ModuleLoader {
  18408. constructor(graph, modulesById, options, pluginDriver) {
  18409. this.graph = graph;
  18410. this.modulesById = modulesById;
  18411. this.options = options;
  18412. this.pluginDriver = pluginDriver;
  18413. this.implicitEntryModules = new Set();
  18414. this.indexedEntryModules = [];
  18415. this.latestLoadModulesPromise = Promise.resolve();
  18416. this.nextEntryModuleIndex = 0;
  18417. this.readQueue = new Queue();
  18418. this.resolveId = async (source, importer, customOptions, skip = null) => {
  18419. return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  18420. ? false
  18421. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions), importer, source));
  18422. };
  18423. this.hasModuleSideEffects = options.treeshake
  18424. ? options.treeshake.moduleSideEffects
  18425. : () => true;
  18426. this.readQueue.maxParallel = options.maxParallelFileReads;
  18427. }
  18428. async addAdditionalModules(unresolvedModules) {
  18429. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  18430. await this.awaitLoadModulesPromise();
  18431. return result;
  18432. }
  18433. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  18434. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  18435. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  18436. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  18437. let moduleIndex = firstEntryModuleIndex;
  18438. for (let index = 0; index < entryModules.length; index++) {
  18439. const entryModule = entryModules[index];
  18440. entryModule.isUserDefinedEntryPoint =
  18441. entryModule.isUserDefinedEntryPoint || isUserDefined;
  18442. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
  18443. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  18444. if (!existingIndexedModule) {
  18445. this.indexedEntryModules.push({ index: moduleIndex, module: entryModule });
  18446. }
  18447. else {
  18448. existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
  18449. }
  18450. moduleIndex++;
  18451. }
  18452. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  18453. return entryModules;
  18454. }));
  18455. await this.awaitLoadModulesPromise();
  18456. return {
  18457. entryModules: this.indexedEntryModules.map(({ module }) => module),
  18458. implicitEntryModules: [...this.implicitEntryModules],
  18459. newEntryModules
  18460. };
  18461. }
  18462. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  18463. const unresolvedModule = {
  18464. fileName: fileName || null,
  18465. id,
  18466. importer,
  18467. name: name || null
  18468. };
  18469. const module = implicitlyLoadedAfterOneOf
  18470. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  18471. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  18472. if (preserveSignature != null) {
  18473. module.preserveSignature = preserveSignature;
  18474. }
  18475. return module;
  18476. }
  18477. addDefaultsToResolvedId(resolvedId) {
  18478. var _a, _b;
  18479. if (!resolvedId) {
  18480. return null;
  18481. }
  18482. const external = resolvedId.external || false;
  18483. return {
  18484. external,
  18485. id: resolvedId.id,
  18486. meta: resolvedId.meta || EMPTY_OBJECT,
  18487. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  18488. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  18489. };
  18490. }
  18491. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  18492. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  18493. addChunkNamesToModule(entryModule, unresolvedModule, false);
  18494. if (!entryModule.info.isEntry) {
  18495. this.implicitEntryModules.add(entryModule);
  18496. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  18497. for (const module of implicitlyLoadedAfterModules) {
  18498. entryModule.implicitlyLoadedAfter.add(module);
  18499. }
  18500. for (const dependant of entryModule.implicitlyLoadedAfter) {
  18501. dependant.implicitlyLoadedBefore.add(entryModule);
  18502. }
  18503. }
  18504. return entryModule;
  18505. }));
  18506. }
  18507. async addModuleSource(id, importer, module) {
  18508. timeStart('load modules', 3);
  18509. let source;
  18510. try {
  18511. source = await this.readQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id)); });
  18512. }
  18513. catch (err) {
  18514. timeEnd('load modules', 3);
  18515. let msg = `Could not load ${id}`;
  18516. if (importer)
  18517. msg += ` (imported by ${relativeId(importer)})`;
  18518. msg += `: ${err.message}`;
  18519. err.message = msg;
  18520. throw err;
  18521. }
  18522. timeEnd('load modules', 3);
  18523. const sourceDescription = typeof source === 'string'
  18524. ? { code: source }
  18525. : typeof source === 'object' && typeof source.code === 'string'
  18526. ? source
  18527. : error(errBadLoader(id));
  18528. const cachedModule = this.graph.cachedModules.get(id);
  18529. if (cachedModule &&
  18530. !cachedModule.customTransformCache &&
  18531. cachedModule.originalCode === sourceDescription.code) {
  18532. if (cachedModule.transformFiles) {
  18533. for (const emittedFile of cachedModule.transformFiles)
  18534. this.pluginDriver.emitFile(emittedFile);
  18535. }
  18536. module.setSource(cachedModule);
  18537. }
  18538. else {
  18539. module.updateOptions(sourceDescription);
  18540. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  18541. }
  18542. }
  18543. async awaitLoadModulesPromise() {
  18544. let startingPromise;
  18545. do {
  18546. startingPromise = this.latestLoadModulesPromise;
  18547. await startingPromise;
  18548. } while (startingPromise !== this.latestLoadModulesPromise);
  18549. }
  18550. extendLoadModulesPromise(loadNewModulesPromise) {
  18551. this.latestLoadModulesPromise = Promise.all([
  18552. loadNewModulesPromise,
  18553. this.latestLoadModulesPromise
  18554. ]);
  18555. this.latestLoadModulesPromise.catch(() => {
  18556. /* Avoid unhandled Promise rejections */
  18557. });
  18558. return loadNewModulesPromise;
  18559. }
  18560. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  18561. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  18562. if (resolvedId === null)
  18563. return null;
  18564. if (typeof resolvedId === 'string') {
  18565. dynamicImport.resolution = resolvedId;
  18566. return null;
  18567. }
  18568. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  18569. })));
  18570. for (const dependency of dependencies) {
  18571. if (dependency) {
  18572. module.dynamicDependencies.add(dependency);
  18573. dependency.dynamicImporters.push(module.id);
  18574. }
  18575. }
  18576. }
  18577. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
  18578. const existingModule = this.modulesById.get(id);
  18579. if (existingModule instanceof Module) {
  18580. if (isEntry) {
  18581. existingModule.info.isEntry = true;
  18582. this.implicitEntryModules.delete(existingModule);
  18583. for (const dependant of existingModule.implicitlyLoadedAfter) {
  18584. dependant.implicitlyLoadedBefore.delete(existingModule);
  18585. }
  18586. existingModule.implicitlyLoadedAfter.clear();
  18587. }
  18588. return existingModule;
  18589. }
  18590. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  18591. this.modulesById.set(id, module);
  18592. this.graph.watchFiles[id] = true;
  18593. await this.addModuleSource(id, importer, module);
  18594. const resolveStaticDependencyPromises = this.getResolveStaticDependencyPromises(module);
  18595. const resolveDynamicImportPromises = this.getResolveDynamicImportPromises(module);
  18596. Promise.all([
  18597. ...resolveStaticDependencyPromises,
  18598. ...resolveDynamicImportPromises
  18599. ]).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  18600. await Promise.all([
  18601. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  18602. this.fetchDynamicDependencies(module, resolveDynamicImportPromises)
  18603. ]);
  18604. module.linkImports();
  18605. return module;
  18606. }
  18607. fetchResolvedDependency(source, importer, resolvedId) {
  18608. if (resolvedId.external) {
  18609. const { external, id, moduleSideEffects, meta } = resolvedId;
  18610. if (!this.modulesById.has(id)) {
  18611. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  18612. }
  18613. const externalModule = this.modulesById.get(id);
  18614. if (!(externalModule instanceof ExternalModule)) {
  18615. return error(errInternalIdCannotBeExternal(source, importer));
  18616. }
  18617. return Promise.resolve(externalModule);
  18618. }
  18619. else {
  18620. return this.fetchModule(resolvedId, importer, false);
  18621. }
  18622. }
  18623. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  18624. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  18625. module.dependencies.add(dependency);
  18626. dependency.importers.push(module.id);
  18627. }
  18628. if (!this.options.treeshake || module.info.hasModuleSideEffects === 'no-treeshake') {
  18629. for (const dependency of module.dependencies) {
  18630. if (dependency instanceof Module) {
  18631. dependency.importedFromNotTreeshaken = true;
  18632. }
  18633. }
  18634. }
  18635. }
  18636. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  18637. const { makeAbsoluteExternalsRelative } = this.options;
  18638. if (resolveIdResult) {
  18639. if (typeof resolveIdResult === 'object') {
  18640. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  18641. return {
  18642. ...resolveIdResult,
  18643. external: external &&
  18644. (external === 'relative' ||
  18645. !isAbsolute(resolveIdResult.id) ||
  18646. (external === true &&
  18647. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  18648. 'absolute')
  18649. };
  18650. }
  18651. const external = this.options.external(resolveIdResult, importer, true);
  18652. return {
  18653. external: external &&
  18654. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  18655. 'absolute'),
  18656. id: external && makeAbsoluteExternalsRelative
  18657. ? normalizeRelativeExternalId(resolveIdResult, importer)
  18658. : resolveIdResult
  18659. };
  18660. }
  18661. const id = makeAbsoluteExternalsRelative
  18662. ? normalizeRelativeExternalId(source, importer)
  18663. : source;
  18664. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  18665. return null;
  18666. }
  18667. return {
  18668. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  18669. id
  18670. };
  18671. }
  18672. getResolveDynamicImportPromises(module) {
  18673. return module.dynamicImports.map(async (dynamicImport) => {
  18674. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  18675. ? dynamicImport.argument
  18676. : dynamicImport.argument.esTreeNode, module.id);
  18677. if (resolvedId && typeof resolvedId === 'object') {
  18678. dynamicImport.id = resolvedId.id;
  18679. }
  18680. return [dynamicImport, resolvedId];
  18681. });
  18682. }
  18683. getResolveStaticDependencyPromises(module) {
  18684. return Array.from(module.sources, async (source) => [
  18685. source,
  18686. (module.resolvedIds[source] =
  18687. module.resolvedIds[source] ||
  18688. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id))
  18689. ]);
  18690. }
  18691. handleResolveId(resolvedId, source, importer) {
  18692. if (resolvedId === null) {
  18693. if (isRelative(source)) {
  18694. return error(errUnresolvedImport(source, importer));
  18695. }
  18696. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  18697. return {
  18698. external: true,
  18699. id: source,
  18700. meta: EMPTY_OBJECT,
  18701. moduleSideEffects: this.hasModuleSideEffects(source, true),
  18702. syntheticNamedExports: false
  18703. };
  18704. }
  18705. else {
  18706. if (resolvedId.external && resolvedId.syntheticNamedExports) {
  18707. this.options.onwarn(errExternalSyntheticExports(source, importer));
  18708. }
  18709. }
  18710. return resolvedId;
  18711. }
  18712. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  18713. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT);
  18714. if (resolveIdResult == null) {
  18715. return error(implicitlyLoadedBefore === null
  18716. ? errUnresolvedEntry(unresolvedId)
  18717. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  18718. }
  18719. if (resolveIdResult === false ||
  18720. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  18721. return error(implicitlyLoadedBefore === null
  18722. ? errEntryCannotBeExternal(unresolvedId)
  18723. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  18724. }
  18725. return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object'
  18726. ? resolveIdResult
  18727. : { id: resolveIdResult }), undefined, isEntry);
  18728. }
  18729. async resolveDynamicImport(module, specifier, importer) {
  18730. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  18731. specifier,
  18732. importer
  18733. ]);
  18734. if (typeof specifier !== 'string') {
  18735. if (typeof resolution === 'string') {
  18736. return resolution;
  18737. }
  18738. if (!resolution) {
  18739. return null;
  18740. }
  18741. return {
  18742. external: false,
  18743. moduleSideEffects: true,
  18744. ...resolution
  18745. };
  18746. }
  18747. if (resolution == null) {
  18748. return (module.resolvedIds[specifier] =
  18749. module.resolvedIds[specifier] ||
  18750. this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
  18751. }
  18752. return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  18753. }
  18754. }
  18755. function normalizeRelativeExternalId(source, importer) {
  18756. return isRelative(source)
  18757. ? importer
  18758. ? path.resolve(importer, '..', source)
  18759. : path.resolve(source)
  18760. : source;
  18761. }
  18762. function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
  18763. if (fileName !== null) {
  18764. module.chunkFileNames.add(fileName);
  18765. }
  18766. else if (name !== null) {
  18767. if (module.chunkName === null) {
  18768. module.chunkName = name;
  18769. }
  18770. if (isUserDefined) {
  18771. module.userChunkNames.add(name);
  18772. }
  18773. }
  18774. }
  18775. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  18776. return (makeAbsoluteExternalsRelative === true ||
  18777. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  18778. !isAbsolute(id));
  18779. }
  18780. class GlobalScope extends Scope$1 {
  18781. constructor() {
  18782. super();
  18783. this.variables.set('undefined', new UndefinedVariable());
  18784. }
  18785. findVariable(name) {
  18786. let variable = this.variables.get(name);
  18787. if (!variable) {
  18788. variable = new GlobalVariable(name);
  18789. this.variables.set(name, variable);
  18790. }
  18791. return variable;
  18792. }
  18793. }
  18794. // eslint-disable-next-line @typescript-eslint/ban-types
  18795. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  18796. let deprecationWarningShown = false;
  18797. return ((...args) => {
  18798. if (!deprecationWarningShown) {
  18799. deprecationWarningShown = true;
  18800. warnDeprecation({
  18801. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  18802. plugin: pluginName
  18803. }, activeDeprecation, options);
  18804. }
  18805. return handler(...args);
  18806. });
  18807. }
  18808. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  18809. let cacheable = true;
  18810. if (typeof plugin.cacheKey !== 'string') {
  18811. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  18812. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  18813. existingPluginNames.has(plugin.name)) {
  18814. cacheable = false;
  18815. }
  18816. else {
  18817. existingPluginNames.add(plugin.name);
  18818. }
  18819. }
  18820. let cacheInstance;
  18821. if (!pluginCache) {
  18822. cacheInstance = NO_CACHE;
  18823. }
  18824. else if (cacheable) {
  18825. const cacheKey = plugin.cacheKey || plugin.name;
  18826. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  18827. }
  18828. else {
  18829. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  18830. }
  18831. const context = {
  18832. addWatchFile(id) {
  18833. if (graph.phase >= BuildPhase.GENERATE) {
  18834. return this.error(errInvalidRollupPhaseForAddWatchFile());
  18835. }
  18836. graph.watchFiles[id] = true;
  18837. },
  18838. cache: cacheInstance,
  18839. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  18840. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  18841. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  18842. error(err) {
  18843. return throwPluginError(err, plugin.name);
  18844. },
  18845. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  18846. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  18847. getFileName: fileEmitter.getFileName,
  18848. getModuleIds: () => graph.modulesById.keys(),
  18849. getModuleInfo: graph.getModuleInfo,
  18850. getWatchFiles: () => Object.keys(graph.watchFiles),
  18851. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  18852. meta: {
  18853. rollupVersion: version$1,
  18854. watchMode: graph.watchMode
  18855. },
  18856. get moduleIds() {
  18857. function* wrappedModuleIds() {
  18858. warnDeprecation({
  18859. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  18860. plugin: plugin.name
  18861. }, false, options);
  18862. yield* moduleIds;
  18863. }
  18864. const moduleIds = graph.modulesById.keys();
  18865. return wrappedModuleIds();
  18866. },
  18867. parse: graph.contextParse.bind(graph),
  18868. resolve(source, importer, { custom, skipSelf } = BLANK) {
  18869. return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? [{ importer, plugin, source }] : null);
  18870. },
  18871. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  18872. .resolveId(source, importer, BLANK)
  18873. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  18874. setAssetSource: fileEmitter.setAssetSource,
  18875. warn(warning) {
  18876. if (typeof warning === 'string')
  18877. warning = { message: warning };
  18878. if (warning.code)
  18879. warning.pluginCode = warning.code;
  18880. warning.code = 'PLUGIN_WARNING';
  18881. warning.plugin = plugin.name;
  18882. options.onwarn(warning);
  18883. }
  18884. };
  18885. return context;
  18886. }
  18887. const inputHookNames = {
  18888. buildEnd: 1,
  18889. buildStart: 1,
  18890. closeBundle: 1,
  18891. closeWatcher: 1,
  18892. load: 1,
  18893. moduleParsed: 1,
  18894. options: 1,
  18895. resolveDynamicImport: 1,
  18896. resolveId: 1,
  18897. transform: 1,
  18898. watchChange: 1
  18899. };
  18900. const inputHooks = Object.keys(inputHookNames);
  18901. function throwInvalidHookError(hookName, pluginName) {
  18902. return error({
  18903. code: 'INVALID_PLUGIN_HOOK',
  18904. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  18905. });
  18906. }
  18907. class PluginDriver {
  18908. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  18909. this.graph = graph;
  18910. this.options = options;
  18911. this.pluginContexts = new Map();
  18912. warnDeprecatedHooks(userPlugins, options);
  18913. this.pluginCache = pluginCache;
  18914. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  18915. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  18916. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  18917. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  18918. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  18919. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  18920. const existingPluginNames = new Set();
  18921. for (const plugin of this.plugins) {
  18922. this.pluginContexts.set(plugin, getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames));
  18923. }
  18924. if (basePluginDriver) {
  18925. for (const plugin of userPlugins) {
  18926. for (const hook of inputHooks) {
  18927. if (hook in plugin) {
  18928. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  18929. }
  18930. }
  18931. }
  18932. }
  18933. }
  18934. createOutputPluginDriver(plugins) {
  18935. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  18936. }
  18937. // chains, first non-null result stops and returns
  18938. hookFirst(hookName, args, replaceContext, skipped) {
  18939. let promise = Promise.resolve(undefined);
  18940. for (const plugin of this.plugins) {
  18941. if (skipped && skipped.has(plugin))
  18942. continue;
  18943. promise = promise.then(result => {
  18944. if (result != null)
  18945. return result;
  18946. return this.runHook(hookName, args, plugin, false, replaceContext);
  18947. });
  18948. }
  18949. return promise;
  18950. }
  18951. // chains synchronously, first non-null result stops and returns
  18952. hookFirstSync(hookName, args, replaceContext) {
  18953. for (const plugin of this.plugins) {
  18954. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  18955. if (result != null)
  18956. return result;
  18957. }
  18958. return null;
  18959. }
  18960. // parallel, ignores returns
  18961. hookParallel(hookName, args, replaceContext) {
  18962. const promises = [];
  18963. for (const plugin of this.plugins) {
  18964. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  18965. if (!hookPromise)
  18966. continue;
  18967. promises.push(hookPromise);
  18968. }
  18969. return Promise.all(promises).then(() => { });
  18970. }
  18971. // chains, reduces returned value, handling the reduced value as the first hook argument
  18972. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  18973. let promise = Promise.resolve(arg0);
  18974. for (const plugin of this.plugins) {
  18975. promise = promise.then(arg0 => {
  18976. const args = [arg0, ...rest];
  18977. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  18978. if (!hookPromise)
  18979. return arg0;
  18980. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin));
  18981. });
  18982. }
  18983. return promise;
  18984. }
  18985. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  18986. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  18987. for (const plugin of this.plugins) {
  18988. const args = [arg0, ...rest];
  18989. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  18990. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  18991. }
  18992. return arg0;
  18993. }
  18994. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  18995. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  18996. let promise = Promise.resolve(initialValue);
  18997. for (const plugin of this.plugins) {
  18998. promise = promise.then(value => {
  18999. const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
  19000. if (!hookPromise)
  19001. return value;
  19002. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), value, result, plugin));
  19003. });
  19004. }
  19005. return promise;
  19006. }
  19007. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  19008. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  19009. let acc = initialValue;
  19010. for (const plugin of this.plugins) {
  19011. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  19012. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  19013. }
  19014. return acc;
  19015. }
  19016. // chains, ignores returns
  19017. hookSeq(hookName, args, replaceContext) {
  19018. let promise = Promise.resolve();
  19019. for (const plugin of this.plugins) {
  19020. promise = promise.then(() => this.runHook(hookName, args, plugin, false, replaceContext));
  19021. }
  19022. return promise;
  19023. }
  19024. // chains synchronously, ignores returns
  19025. hookSeqSync(hookName, args, replaceContext) {
  19026. for (const plugin of this.plugins) {
  19027. this.runHookSync(hookName, args, plugin, replaceContext);
  19028. }
  19029. }
  19030. runHook(hookName, args, plugin, permitValues, hookContext) {
  19031. const hook = plugin[hookName];
  19032. if (!hook)
  19033. return undefined;
  19034. let context = this.pluginContexts.get(plugin);
  19035. if (hookContext) {
  19036. context = hookContext(context, plugin);
  19037. }
  19038. return Promise.resolve()
  19039. .then(() => {
  19040. // permit values allows values to be returned instead of a functional hook
  19041. if (typeof hook !== 'function') {
  19042. if (permitValues)
  19043. return hook;
  19044. return throwInvalidHookError(hookName, plugin.name);
  19045. }
  19046. // eslint-disable-next-line @typescript-eslint/ban-types
  19047. return hook.apply(context, args);
  19048. })
  19049. .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
  19050. }
  19051. /**
  19052. * Run a sync plugin hook and return the result.
  19053. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  19054. * @param args Arguments passed to the plugin hook.
  19055. * @param plugin The acutal plugin
  19056. * @param hookContext When passed, the plugin context can be overridden.
  19057. */
  19058. runHookSync(hookName, args, plugin, hookContext) {
  19059. const hook = plugin[hookName];
  19060. if (!hook)
  19061. return undefined;
  19062. let context = this.pluginContexts.get(plugin);
  19063. if (hookContext) {
  19064. context = hookContext(context, plugin);
  19065. }
  19066. try {
  19067. // permit values allows values to be returned instead of a functional hook
  19068. if (typeof hook !== 'function') {
  19069. return throwInvalidHookError(hookName, plugin.name);
  19070. }
  19071. // eslint-disable-next-line @typescript-eslint/ban-types
  19072. return hook.apply(context, args);
  19073. }
  19074. catch (err) {
  19075. return throwPluginError(err, plugin.name, { hook: hookName });
  19076. }
  19077. }
  19078. }
  19079. function normalizeEntryModules(entryModules) {
  19080. if (Array.isArray(entryModules)) {
  19081. return entryModules.map(id => ({
  19082. fileName: null,
  19083. id,
  19084. implicitlyLoadedAfter: [],
  19085. importer: undefined,
  19086. name: null
  19087. }));
  19088. }
  19089. return Object.entries(entryModules).map(([name, id]) => ({
  19090. fileName: null,
  19091. id,
  19092. implicitlyLoadedAfter: [],
  19093. importer: undefined,
  19094. name
  19095. }));
  19096. }
  19097. class Graph {
  19098. constructor(options, watcher) {
  19099. var _a, _b;
  19100. this.options = options;
  19101. this.entryModules = [];
  19102. this.modulesById = new Map();
  19103. this.needsTreeshakingPass = false;
  19104. this.phase = BuildPhase.LOAD_AND_PARSE;
  19105. this.watchFiles = Object.create(null);
  19106. this.watchMode = false;
  19107. this.externalModules = [];
  19108. this.implicitEntryModules = [];
  19109. this.modules = [];
  19110. this.getModuleInfo = (moduleId) => {
  19111. const foundModule = this.modulesById.get(moduleId);
  19112. if (!foundModule)
  19113. return null;
  19114. return foundModule.info;
  19115. };
  19116. this.deoptimizationTracker = new PathTracker();
  19117. this.cachedModules = new Map();
  19118. if (options.cache !== false) {
  19119. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  19120. for (const module of options.cache.modules)
  19121. this.cachedModules.set(module.id, module);
  19122. }
  19123. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  19124. // increment access counter
  19125. for (const name in this.pluginCache) {
  19126. const cache = this.pluginCache[name];
  19127. for (const value of Object.values(cache))
  19128. value[0]++;
  19129. }
  19130. }
  19131. if (watcher) {
  19132. this.watchMode = true;
  19133. const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
  19134. const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
  19135. watcher.on('change', handleChange);
  19136. watcher.on('close', handleClose);
  19137. watcher.once('restart', () => {
  19138. watcher.removeListener('change', handleChange);
  19139. watcher.removeListener('close', handleClose);
  19140. });
  19141. }
  19142. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  19143. this.scope = new GlobalScope();
  19144. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  19145. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  19146. }
  19147. async build() {
  19148. timeStart('generate module graph', 2);
  19149. await this.generateModuleGraph();
  19150. timeEnd('generate module graph', 2);
  19151. timeStart('sort modules', 2);
  19152. this.phase = BuildPhase.ANALYSE;
  19153. this.sortModules();
  19154. timeEnd('sort modules', 2);
  19155. timeStart('mark included statements', 2);
  19156. this.includeStatements();
  19157. timeEnd('mark included statements', 2);
  19158. this.phase = BuildPhase.GENERATE;
  19159. }
  19160. contextParse(code, options = {}) {
  19161. const onCommentOrig = options.onComment;
  19162. const comments = [];
  19163. if (onCommentOrig && typeof onCommentOrig == 'function') {
  19164. options.onComment = (block, text, start, end, ...args) => {
  19165. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  19166. return onCommentOrig.call(options, block, text, start, end, ...args);
  19167. };
  19168. }
  19169. else {
  19170. options.onComment = comments;
  19171. }
  19172. const ast = this.acornParser.parse(code, {
  19173. ...this.options.acorn,
  19174. ...options
  19175. });
  19176. if (typeof onCommentOrig == 'object') {
  19177. onCommentOrig.push(...comments);
  19178. }
  19179. options.onComment = onCommentOrig;
  19180. addAnnotations(comments, ast, code);
  19181. return ast;
  19182. }
  19183. getCache() {
  19184. // handle plugin cache eviction
  19185. for (const name in this.pluginCache) {
  19186. const cache = this.pluginCache[name];
  19187. let allDeleted = true;
  19188. for (const [key, value] of Object.entries(cache)) {
  19189. if (value[0] >= this.options.experimentalCacheExpiry)
  19190. delete cache[key];
  19191. else
  19192. allDeleted = false;
  19193. }
  19194. if (allDeleted)
  19195. delete this.pluginCache[name];
  19196. }
  19197. return {
  19198. modules: this.modules.map(module => module.toJSON()),
  19199. plugins: this.pluginCache
  19200. };
  19201. }
  19202. async generateModuleGraph() {
  19203. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  19204. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  19205. if (this.entryModules.length === 0) {
  19206. throw new Error('You must supply options.input to rollup');
  19207. }
  19208. for (const module of this.modulesById.values()) {
  19209. if (module instanceof Module) {
  19210. this.modules.push(module);
  19211. }
  19212. else {
  19213. this.externalModules.push(module);
  19214. }
  19215. }
  19216. }
  19217. includeStatements() {
  19218. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  19219. markModuleAndImpureDependenciesAsExecuted(module);
  19220. }
  19221. if (this.options.treeshake) {
  19222. let treeshakingPass = 1;
  19223. do {
  19224. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  19225. this.needsTreeshakingPass = false;
  19226. for (const module of this.modules) {
  19227. if (module.isExecuted) {
  19228. if (module.info.hasModuleSideEffects === 'no-treeshake') {
  19229. module.includeAllInBundle();
  19230. }
  19231. else {
  19232. module.include();
  19233. }
  19234. }
  19235. }
  19236. if (treeshakingPass === 1) {
  19237. // We only include exports after the first pass to avoid issues with
  19238. // the TDZ detection logic
  19239. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  19240. if (module.preserveSignature !== false) {
  19241. module.includeAllExports(false);
  19242. this.needsTreeshakingPass = true;
  19243. }
  19244. }
  19245. }
  19246. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  19247. } while (this.needsTreeshakingPass);
  19248. }
  19249. else {
  19250. for (const module of this.modules)
  19251. module.includeAllInBundle();
  19252. }
  19253. for (const externalModule of this.externalModules)
  19254. externalModule.warnUnusedImports();
  19255. for (const module of this.implicitEntryModules) {
  19256. for (const dependant of module.implicitlyLoadedAfter) {
  19257. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  19258. error(errImplicitDependantIsNotIncluded(dependant));
  19259. }
  19260. }
  19261. }
  19262. }
  19263. sortModules() {
  19264. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  19265. for (const cyclePath of cyclePaths) {
  19266. this.options.onwarn({
  19267. code: 'CIRCULAR_DEPENDENCY',
  19268. cycle: cyclePath,
  19269. importer: cyclePath[0],
  19270. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  19271. });
  19272. }
  19273. this.modules = orderedModules;
  19274. for (const module of this.modules) {
  19275. module.bindReferences();
  19276. }
  19277. this.warnForMissingExports();
  19278. }
  19279. warnForMissingExports() {
  19280. for (const module of this.modules) {
  19281. for (const importDescription of Object.values(module.importDescriptions)) {
  19282. if (importDescription.name !== '*' &&
  19283. !importDescription.module.getVariableForExportName(importDescription.name)) {
  19284. module.warn({
  19285. code: 'NON_EXISTENT_EXPORT',
  19286. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  19287. name: importDescription.name,
  19288. source: importDescription.module.id
  19289. }, importDescription.start);
  19290. }
  19291. }
  19292. }
  19293. }
  19294. }
  19295. function normalizeInputOptions(config) {
  19296. var _a, _b, _c;
  19297. // These are options that may trigger special warnings or behaviour later
  19298. // if the user did not select an explicit value
  19299. const unsetOptions = new Set();
  19300. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  19301. const onwarn = getOnwarn(config);
  19302. const strictDeprecations = config.strictDeprecations || false;
  19303. const options = {
  19304. acorn: getAcorn(config),
  19305. acornInjectPlugins: getAcornInjectPlugins(config),
  19306. cache: getCache(config),
  19307. context,
  19308. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  19309. external: getIdMatcher(config.external),
  19310. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  19311. input: getInput(config),
  19312. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  19313. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  19314. maxParallelFileReads: getMaxParallelFileReads(config),
  19315. moduleContext: getModuleContext(config, context),
  19316. onwarn,
  19317. perf: config.perf || false,
  19318. plugins: ensureArray(config.plugins),
  19319. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  19320. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  19321. preserveSymlinks: config.preserveSymlinks || false,
  19322. shimMissingExports: config.shimMissingExports || false,
  19323. strictDeprecations,
  19324. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  19325. };
  19326. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  19327. return { options, unsetOptions };
  19328. }
  19329. const getOnwarn = (config) => {
  19330. const { onwarn } = config;
  19331. return onwarn
  19332. ? warning => {
  19333. warning.toString = () => {
  19334. let str = '';
  19335. if (warning.plugin)
  19336. str += `(${warning.plugin} plugin) `;
  19337. if (warning.loc)
  19338. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  19339. str += warning.message;
  19340. return str;
  19341. };
  19342. onwarn(warning, defaultOnWarn);
  19343. }
  19344. : defaultOnWarn;
  19345. };
  19346. const getAcorn = (config) => ({
  19347. allowAwaitOutsideFunction: true,
  19348. ecmaVersion: 'latest',
  19349. preserveParens: false,
  19350. sourceType: 'module',
  19351. ...config.acorn
  19352. });
  19353. const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
  19354. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  19355. const getIdMatcher = (option) => {
  19356. if (option === true) {
  19357. return () => true;
  19358. }
  19359. if (typeof option === 'function') {
  19360. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  19361. }
  19362. if (option) {
  19363. const ids = new Set();
  19364. const matchers = [];
  19365. for (const value of ensureArray(option)) {
  19366. if (value instanceof RegExp) {
  19367. matchers.push(value);
  19368. }
  19369. else {
  19370. ids.add(value);
  19371. }
  19372. }
  19373. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  19374. }
  19375. return () => false;
  19376. };
  19377. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  19378. const configInlineDynamicImports = config.inlineDynamicImports;
  19379. if (configInlineDynamicImports) {
  19380. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  19381. }
  19382. return configInlineDynamicImports;
  19383. };
  19384. const getInput = (config) => {
  19385. const configInput = config.input;
  19386. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  19387. };
  19388. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  19389. const configManualChunks = config.manualChunks;
  19390. if (configManualChunks) {
  19391. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  19392. }
  19393. return configManualChunks;
  19394. };
  19395. const getMaxParallelFileReads = (config) => {
  19396. const maxParallelFileReads = config.maxParallelFileReads;
  19397. if (typeof maxParallelFileReads === 'number') {
  19398. if (maxParallelFileReads <= 0)
  19399. return Infinity;
  19400. return maxParallelFileReads;
  19401. }
  19402. return 20;
  19403. };
  19404. const getModuleContext = (config, context) => {
  19405. const configModuleContext = config.moduleContext;
  19406. if (typeof configModuleContext === 'function') {
  19407. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  19408. }
  19409. if (configModuleContext) {
  19410. const contextByModuleId = Object.create(null);
  19411. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  19412. contextByModuleId[path.resolve(key)] = moduleContext;
  19413. }
  19414. return id => contextByModuleId[id] || context;
  19415. }
  19416. return () => context;
  19417. };
  19418. const getPreserveEntrySignatures = (config, unsetOptions) => {
  19419. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  19420. if (configPreserveEntrySignatures == null) {
  19421. unsetOptions.add('preserveEntrySignatures');
  19422. }
  19423. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  19424. };
  19425. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  19426. const configPreserveModules = config.preserveModules;
  19427. if (configPreserveModules) {
  19428. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  19429. }
  19430. return configPreserveModules;
  19431. };
  19432. const getTreeshake = (config, warn, strictDeprecations) => {
  19433. const configTreeshake = config.treeshake;
  19434. if (configTreeshake === false) {
  19435. return false;
  19436. }
  19437. if (typeof configTreeshake === 'string') {
  19438. const preset = treeshakePresets[configTreeshake];
  19439. if (preset) {
  19440. return preset;
  19441. }
  19442. error(errInvalidOption('treeshake', `valid values are false, true, ${printQuotedStringList(Object.keys(treeshakePresets))}. You can also supply an object for more fine-grained control`));
  19443. }
  19444. let configWithPreset = {};
  19445. if (typeof configTreeshake === 'object') {
  19446. if (typeof configTreeshake.pureExternalModules !== 'undefined') {
  19447. 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);
  19448. }
  19449. configWithPreset = configTreeshake;
  19450. const presetName = configTreeshake.preset;
  19451. if (presetName) {
  19452. const preset = treeshakePresets[presetName];
  19453. if (preset) {
  19454. configWithPreset = { ...preset, ...configTreeshake };
  19455. }
  19456. else {
  19457. error(errInvalidOption('treeshake.preset', `valid values are ${printQuotedStringList(Object.keys(treeshakePresets))}`));
  19458. }
  19459. }
  19460. }
  19461. return {
  19462. annotations: configWithPreset.annotations !== false,
  19463. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  19464. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  19465. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  19466. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  19467. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  19468. ? 'always'
  19469. : configWithPreset.propertyReadSideEffects !== false,
  19470. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  19471. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  19472. };
  19473. };
  19474. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  19475. if (typeof moduleSideEffectsOption === 'boolean') {
  19476. return () => moduleSideEffectsOption;
  19477. }
  19478. if (moduleSideEffectsOption === 'no-external') {
  19479. return (_id, external) => !external;
  19480. }
  19481. if (typeof moduleSideEffectsOption === 'function') {
  19482. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  19483. }
  19484. if (Array.isArray(moduleSideEffectsOption)) {
  19485. const ids = new Set(moduleSideEffectsOption);
  19486. return id => ids.has(id);
  19487. }
  19488. if (moduleSideEffectsOption) {
  19489. error(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
  19490. }
  19491. const isPureExternalModule = getIdMatcher(pureExternalModules);
  19492. return (id, external) => !(external && isPureExternalModule(id));
  19493. };
  19494. function sanitizeFileName(name) {
  19495. const match = /^[a-z]:/i.exec(name);
  19496. const driveLetter = match ? match[0] : '';
  19497. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  19498. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  19499. return driveLetter + name.substr(driveLetter.length).replace(/[\0?*:]/g, '_');
  19500. }
  19501. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  19502. var _a, _b, _c, _d, _e, _f, _g;
  19503. // These are options that may trigger special warnings or behaviour later
  19504. // if the user did not select an explicit value
  19505. const unsetOptions = new Set(unsetInputOptions);
  19506. const compact = config.compact || false;
  19507. const format = getFormat(config);
  19508. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  19509. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  19510. const file = getFile(config, preserveModules, inputOptions);
  19511. const outputOptions = {
  19512. amd: getAmd(config),
  19513. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  19514. banner: getAddon(config, 'banner'),
  19515. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  19516. compact,
  19517. dir: getDir(config, file),
  19518. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  19519. entryFileNames: getEntryFileNames(config, unsetOptions),
  19520. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  19521. exports: getExports(config, unsetOptions),
  19522. extend: config.extend || false,
  19523. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  19524. file,
  19525. footer: getAddon(config, 'footer'),
  19526. format,
  19527. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  19528. globals: config.globals || {},
  19529. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  19530. indent: getIndent(config, compact),
  19531. inlineDynamicImports,
  19532. interop: getInterop(config, inputOptions),
  19533. intro: getAddon(config, 'intro'),
  19534. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  19535. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  19536. name: config.name,
  19537. namespaceToStringTag: config.namespaceToStringTag || false,
  19538. noConflict: config.noConflict || false,
  19539. outro: getAddon(config, 'outro'),
  19540. paths: config.paths || {},
  19541. plugins: ensureArray(config.plugins),
  19542. preferConst: config.preferConst || false,
  19543. preserveModules,
  19544. preserveModulesRoot: getPreserveModulesRoot(config),
  19545. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  19546. ? config.sanitizeFileName
  19547. : config.sanitizeFileName === false
  19548. ? id => id
  19549. : sanitizeFileName,
  19550. sourcemap: config.sourcemap || false,
  19551. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  19552. sourcemapFile: config.sourcemapFile,
  19553. sourcemapPathTransform: config.sourcemapPathTransform,
  19554. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  19555. systemNullSetters: config.systemNullSetters || false,
  19556. validate: config.validate || false
  19557. };
  19558. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  19559. return { options: outputOptions, unsetOptions };
  19560. }
  19561. const getFile = (config, preserveModules, inputOptions) => {
  19562. const { file } = config;
  19563. if (typeof file === 'string') {
  19564. if (preserveModules) {
  19565. return error({
  19566. code: 'INVALID_OPTION',
  19567. message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
  19568. });
  19569. }
  19570. if (!Array.isArray(inputOptions.input))
  19571. return error({
  19572. code: 'INVALID_OPTION',
  19573. message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
  19574. });
  19575. }
  19576. return file;
  19577. };
  19578. const getFormat = (config) => {
  19579. const configFormat = config.format;
  19580. switch (configFormat) {
  19581. case undefined:
  19582. case 'es':
  19583. case 'esm':
  19584. case 'module':
  19585. return 'es';
  19586. case 'cjs':
  19587. case 'commonjs':
  19588. return 'cjs';
  19589. case 'system':
  19590. case 'systemjs':
  19591. return 'system';
  19592. case 'amd':
  19593. case 'iife':
  19594. case 'umd':
  19595. return configFormat;
  19596. default:
  19597. return error({
  19598. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  19599. url: `https://rollupjs.org/guide/en/#outputformat`
  19600. });
  19601. }
  19602. };
  19603. const getInlineDynamicImports = (config, inputOptions) => {
  19604. var _a;
  19605. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  19606. const { input } = inputOptions;
  19607. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  19608. return error({
  19609. code: 'INVALID_OPTION',
  19610. message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
  19611. });
  19612. }
  19613. return inlineDynamicImports;
  19614. };
  19615. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  19616. var _a;
  19617. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  19618. if (preserveModules) {
  19619. if (inlineDynamicImports) {
  19620. return error({
  19621. code: 'INVALID_OPTION',
  19622. message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
  19623. });
  19624. }
  19625. if (inputOptions.preserveEntrySignatures === false) {
  19626. return error({
  19627. code: 'INVALID_OPTION',
  19628. message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
  19629. });
  19630. }
  19631. }
  19632. return preserveModules;
  19633. };
  19634. const getPreserveModulesRoot = (config) => {
  19635. const { preserveModulesRoot } = config;
  19636. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  19637. return undefined;
  19638. }
  19639. return path.resolve(preserveModulesRoot);
  19640. };
  19641. const getAmd = (config) => {
  19642. const collection = {
  19643. autoId: false,
  19644. basePath: '',
  19645. define: 'define',
  19646. ...config.amd
  19647. };
  19648. if ((collection.autoId || collection.basePath) && collection.id) {
  19649. return error({
  19650. code: 'INVALID_OPTION',
  19651. message: '"output.amd.autoId"/"output.amd.basePath" and "output.amd.id" cannot be used together.'
  19652. });
  19653. }
  19654. if (collection.basePath && !collection.autoId) {
  19655. return error({
  19656. code: 'INVALID_OPTION',
  19657. message: '"output.amd.basePath" only works with "output.amd.autoId".'
  19658. });
  19659. }
  19660. let normalized;
  19661. if (collection.autoId) {
  19662. normalized = {
  19663. autoId: true,
  19664. basePath: collection.basePath,
  19665. define: collection.define
  19666. };
  19667. }
  19668. else {
  19669. normalized = {
  19670. autoId: false,
  19671. define: collection.define,
  19672. id: collection.id
  19673. };
  19674. }
  19675. return normalized;
  19676. };
  19677. const getAddon = (config, name) => {
  19678. const configAddon = config[name];
  19679. if (typeof configAddon === 'function') {
  19680. return configAddon;
  19681. }
  19682. return () => configAddon || '';
  19683. };
  19684. const getDir = (config, file) => {
  19685. const { dir } = config;
  19686. if (typeof dir === 'string' && typeof file === 'string') {
  19687. return error({
  19688. code: 'INVALID_OPTION',
  19689. message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
  19690. });
  19691. }
  19692. return dir;
  19693. };
  19694. const getDynamicImportFunction = (config, inputOptions) => {
  19695. const configDynamicImportFunction = config.dynamicImportFunction;
  19696. if (configDynamicImportFunction) {
  19697. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  19698. }
  19699. return configDynamicImportFunction;
  19700. };
  19701. const getEntryFileNames = (config, unsetOptions) => {
  19702. const configEntryFileNames = config.entryFileNames;
  19703. if (configEntryFileNames == null) {
  19704. unsetOptions.add('entryFileNames');
  19705. }
  19706. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  19707. };
  19708. function getExports(config, unsetOptions) {
  19709. const configExports = config.exports;
  19710. if (configExports == null) {
  19711. unsetOptions.add('exports');
  19712. }
  19713. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  19714. return error(errInvalidExportOptionValue(configExports));
  19715. }
  19716. return configExports || 'auto';
  19717. }
  19718. const getIndent = (config, compact) => {
  19719. if (compact) {
  19720. return '';
  19721. }
  19722. const configIndent = config.indent;
  19723. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  19724. };
  19725. const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
  19726. const getInterop = (config, inputOptions) => {
  19727. const configInterop = config.interop;
  19728. const validatedInteropTypes = new Set();
  19729. const validateInterop = (interop) => {
  19730. if (!validatedInteropTypes.has(interop)) {
  19731. validatedInteropTypes.add(interop);
  19732. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  19733. return error({
  19734. code: 'INVALID_OPTION',
  19735. message: `The value ${JSON.stringify(interop)} is not supported for "output.interop". Use one of ${Array.from(ALLOWED_INTEROP_TYPES.values(), value => JSON.stringify(value)).join(', ')} instead.`,
  19736. url: 'https://rollupjs.org/guide/en/#outputinterop'
  19737. });
  19738. }
  19739. if (typeof interop === 'boolean') {
  19740. warnDeprecation({
  19741. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  19742. url: 'https://rollupjs.org/guide/en/#outputinterop'
  19743. }, false, inputOptions);
  19744. }
  19745. }
  19746. return interop;
  19747. };
  19748. if (typeof configInterop === 'function') {
  19749. const interopPerId = Object.create(null);
  19750. let defaultInterop = null;
  19751. return id => id === null
  19752. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  19753. : id in interopPerId
  19754. ? interopPerId[id]
  19755. : validateInterop((interopPerId[id] = configInterop(id)));
  19756. }
  19757. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  19758. };
  19759. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  19760. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  19761. if (configManualChunks) {
  19762. if (inlineDynamicImports) {
  19763. return error({
  19764. code: 'INVALID_OPTION',
  19765. message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
  19766. });
  19767. }
  19768. if (preserveModules) {
  19769. return error({
  19770. code: 'INVALID_OPTION',
  19771. message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
  19772. });
  19773. }
  19774. }
  19775. return configManualChunks || {};
  19776. };
  19777. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  19778. function rollup(rawInputOptions) {
  19779. return rollupInternal(rawInputOptions, null);
  19780. }
  19781. async function rollupInternal(rawInputOptions, watcher) {
  19782. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  19783. initialiseTimers(inputOptions);
  19784. const graph = new Graph(inputOptions, watcher);
  19785. // remove the cache option from the memory after graph creation (cache is not used anymore)
  19786. const useCache = rawInputOptions.cache !== false;
  19787. delete inputOptions.cache;
  19788. delete rawInputOptions.cache;
  19789. timeStart('BUILD', 1);
  19790. try {
  19791. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  19792. await graph.build();
  19793. }
  19794. catch (err) {
  19795. const watchFiles = Object.keys(graph.watchFiles);
  19796. if (watchFiles.length > 0) {
  19797. err.watchFiles = watchFiles;
  19798. }
  19799. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  19800. await graph.pluginDriver.hookParallel('closeBundle', []);
  19801. throw err;
  19802. }
  19803. await graph.pluginDriver.hookParallel('buildEnd', []);
  19804. timeEnd('BUILD', 1);
  19805. const result = {
  19806. cache: useCache ? graph.getCache() : undefined,
  19807. async close() {
  19808. if (result.closed)
  19809. return;
  19810. result.closed = true;
  19811. await graph.pluginDriver.hookParallel('closeBundle', []);
  19812. },
  19813. closed: false,
  19814. async generate(rawOutputOptions) {
  19815. if (result.closed)
  19816. return error(errAlreadyClosed());
  19817. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  19818. },
  19819. watchFiles: Object.keys(graph.watchFiles),
  19820. async write(rawOutputOptions) {
  19821. if (result.closed)
  19822. return error(errAlreadyClosed());
  19823. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  19824. }
  19825. };
  19826. if (inputOptions.perf)
  19827. result.getTimings = getTimings;
  19828. return result;
  19829. }
  19830. async function getInputOptions(rawInputOptions, watchMode) {
  19831. if (!rawInputOptions) {
  19832. throw new Error('You must supply an options object to rollup');
  19833. }
  19834. const rawPlugins = ensureArray(rawInputOptions.plugins);
  19835. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  19836. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  19837. return { options, unsetOptions };
  19838. }
  19839. function applyOptionHook(watchMode) {
  19840. return async (inputOptions, plugin) => {
  19841. if (plugin.options) {
  19842. return ((await plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  19843. }
  19844. return inputOptions;
  19845. };
  19846. }
  19847. function normalizePlugins(plugins, anonymousPrefix) {
  19848. for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
  19849. const plugin = plugins[pluginIndex];
  19850. if (!plugin.name) {
  19851. plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
  19852. }
  19853. }
  19854. }
  19855. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  19856. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  19857. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  19858. const generated = await bundle.generate(isWrite);
  19859. if (isWrite) {
  19860. if (!outputOptions.dir && !outputOptions.file) {
  19861. return error({
  19862. code: 'MISSING_OPTION',
  19863. message: 'You must specify "output.file" or "output.dir" for the build.'
  19864. });
  19865. }
  19866. await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions)));
  19867. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  19868. }
  19869. return createOutput(generated);
  19870. }
  19871. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  19872. if (!rawOutputOptions) {
  19873. throw new Error('You must supply an options object');
  19874. }
  19875. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  19876. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  19877. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  19878. return {
  19879. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  19880. outputPluginDriver
  19881. };
  19882. }
  19883. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  19884. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  19885. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  19886. return {
  19887. ...pluginContext,
  19888. emitFile: emitError,
  19889. setAssetSource: emitError
  19890. };
  19891. }), inputOptions, unsetInputOptions);
  19892. }
  19893. function createOutput(outputBundle) {
  19894. return {
  19895. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  19896. const fileTypeA = getSortingFileType(outputFileA);
  19897. const fileTypeB = getSortingFileType(outputFileB);
  19898. if (fileTypeA === fileTypeB)
  19899. return 0;
  19900. return fileTypeA < fileTypeB ? -1 : 1;
  19901. })
  19902. };
  19903. }
  19904. var SortingFileType;
  19905. (function (SortingFileType) {
  19906. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  19907. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  19908. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  19909. })(SortingFileType || (SortingFileType = {}));
  19910. function getSortingFileType(file) {
  19911. if (file.type === 'asset') {
  19912. return SortingFileType.ASSET;
  19913. }
  19914. if (file.isEntry) {
  19915. return SortingFileType.ENTRY_CHUNK;
  19916. }
  19917. return SortingFileType.SECONDARY_CHUNK;
  19918. }
  19919. function writeOutputFile(outputFile, outputOptions) {
  19920. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  19921. let writeSourceMapPromise;
  19922. let source;
  19923. if (outputFile.type === 'asset') {
  19924. source = outputFile.source;
  19925. }
  19926. else {
  19927. source = outputFile.code;
  19928. if (outputOptions.sourcemap && outputFile.map) {
  19929. let url;
  19930. if (outputOptions.sourcemap === 'inline') {
  19931. url = outputFile.map.toUrl();
  19932. }
  19933. else {
  19934. url = `${path.basename(outputFile.fileName)}.map`;
  19935. writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
  19936. }
  19937. if (outputOptions.sourcemap !== 'hidden') {
  19938. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19939. }
  19940. }
  19941. }
  19942. return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
  19943. }
  19944. /**
  19945. * Auxiliary function for defining rollup configuration
  19946. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  19947. * @param options
  19948. */
  19949. function defineConfig(options) {
  19950. return options;
  19951. }
  19952. class WatchEmitter extends require$$0.EventEmitter {
  19953. constructor() {
  19954. super();
  19955. // Allows more than 10 bundles to be watched without
  19956. // showing the `MaxListenersExceededWarning` to the user.
  19957. this.setMaxListeners(Infinity);
  19958. }
  19959. close() { }
  19960. }
  19961. function watch(configs) {
  19962. const emitter = new WatchEmitter();
  19963. const configArray = ensureArray(configs);
  19964. const watchConfigs = configArray.filter(config => config.watch !== false);
  19965. if (watchConfigs.length === 0) {
  19966. throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
  19967. }
  19968. loadFsEvents()
  19969. .then(() => Promise.resolve().then(function () { return require('./watch.js'); }))
  19970. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  19971. return emitter;
  19972. }
  19973. exports.defaultOnWarn = defaultOnWarn;
  19974. exports.defineConfig = defineConfig;
  19975. exports.ensureArray = ensureArray;
  19976. exports.errInvalidOption = errInvalidOption;
  19977. exports.error = error;
  19978. exports.fseventsImporter = fseventsImporter;
  19979. exports.getAliasName = getAliasName;
  19980. exports.getOrCreate = getOrCreate;
  19981. exports.loadFsEvents = loadFsEvents;
  19982. exports.printQuotedStringList = printQuotedStringList;
  19983. exports.relativeId = relativeId;
  19984. exports.rollup = rollup;
  19985. exports.rollupInternal = rollupInternal;
  19986. exports.treeshakePresets = treeshakePresets;
  19987. exports.version = version$1;
  19988. exports.warnUnknownOptions = warnUnknownOptions;
  19989. exports.watch = watch;
  19990. //# sourceMappingURL=rollup.js.map