rollup.js 730 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041
  1. /*
  2. @license
  3. Rollup.js v2.33.1
  4. Mon, 02 Nov 2020 06:50:50 GMT - commit d861c91c068bc4e64d84db3b84232d3fb7f1d073
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { relative as relative$1, extname, basename, dirname, resolve } from 'path';
  9. import { createHash as createHash$1 } from 'crypto';
  10. import { writeFile as writeFile$1, readdirSync, mkdirSync, readFile as readFile$1, lstatSync, realpathSync } from 'fs';
  11. import { EventEmitter } from 'events';
  12. var version = "2.33.1";
  13. var charToInteger = {};
  14. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15. for (var i = 0; i < chars.length; i++) {
  16. charToInteger[chars.charCodeAt(i)] = i;
  17. }
  18. function decode(mappings) {
  19. var decoded = [];
  20. var line = [];
  21. var segment = [
  22. 0,
  23. 0,
  24. 0,
  25. 0,
  26. 0,
  27. ];
  28. var j = 0;
  29. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  30. var c = mappings.charCodeAt(i);
  31. if (c === 44) { // ","
  32. segmentify(line, segment, j);
  33. j = 0;
  34. }
  35. else if (c === 59) { // ";"
  36. segmentify(line, segment, j);
  37. j = 0;
  38. decoded.push(line);
  39. line = [];
  40. segment[0] = 0;
  41. }
  42. else {
  43. var integer = charToInteger[c];
  44. if (integer === undefined) {
  45. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  46. }
  47. var hasContinuationBit = integer & 32;
  48. integer &= 31;
  49. value += integer << shift;
  50. if (hasContinuationBit) {
  51. shift += 5;
  52. }
  53. else {
  54. var shouldNegate = value & 1;
  55. value >>>= 1;
  56. if (shouldNegate) {
  57. value = value === 0 ? -0x80000000 : -value;
  58. }
  59. segment[j] += value;
  60. j++;
  61. value = shift = 0; // reset
  62. }
  63. }
  64. }
  65. segmentify(line, segment, j);
  66. decoded.push(line);
  67. return decoded;
  68. }
  69. function segmentify(line, segment, j) {
  70. // This looks ugly, but we're creating specialized arrays with a specific
  71. // length. This is much faster than creating a new array (which v8 expands to
  72. // a capacity of 17 after pushing the first item), or slicing out a subarray
  73. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  74. // length 5 (since not everything will have an associated name), followed by
  75. // length 1 (it's probably rare for a source substring to not have an
  76. // associated segment data).
  77. if (j === 4)
  78. line.push([segment[0], segment[1], segment[2], segment[3]]);
  79. else if (j === 5)
  80. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  81. else if (j === 1)
  82. line.push([segment[0]]);
  83. }
  84. function encode(decoded) {
  85. var sourceFileIndex = 0; // second field
  86. var sourceCodeLine = 0; // third field
  87. var sourceCodeColumn = 0; // fourth field
  88. var nameIndex = 0; // fifth field
  89. var mappings = '';
  90. for (var i = 0; i < decoded.length; i++) {
  91. var line = decoded[i];
  92. if (i > 0)
  93. mappings += ';';
  94. if (line.length === 0)
  95. continue;
  96. var generatedCodeColumn = 0; // first field
  97. var lineMappings = [];
  98. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  99. var segment = line_1[_i];
  100. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  101. generatedCodeColumn = segment[0];
  102. if (segment.length > 1) {
  103. segmentMappings +=
  104. encodeInteger(segment[1] - sourceFileIndex) +
  105. encodeInteger(segment[2] - sourceCodeLine) +
  106. encodeInteger(segment[3] - sourceCodeColumn);
  107. sourceFileIndex = segment[1];
  108. sourceCodeLine = segment[2];
  109. sourceCodeColumn = segment[3];
  110. }
  111. if (segment.length === 5) {
  112. segmentMappings += encodeInteger(segment[4] - nameIndex);
  113. nameIndex = segment[4];
  114. }
  115. lineMappings.push(segmentMappings);
  116. }
  117. mappings += lineMappings.join(',');
  118. }
  119. return mappings;
  120. }
  121. function encodeInteger(num) {
  122. var result = '';
  123. num = num < 0 ? (-num << 1) | 1 : num << 1;
  124. do {
  125. var clamped = num & 31;
  126. num >>>= 5;
  127. if (num > 0) {
  128. clamped |= 32;
  129. }
  130. result += chars[clamped];
  131. } while (num > 0);
  132. return result;
  133. }
  134. var BitSet = function BitSet(arg) {
  135. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  136. };
  137. BitSet.prototype.add = function add (n) {
  138. this.bits[n >> 5] |= 1 << (n & 31);
  139. };
  140. BitSet.prototype.has = function has (n) {
  141. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  142. };
  143. var Chunk = function Chunk(start, end, content) {
  144. this.start = start;
  145. this.end = end;
  146. this.original = content;
  147. this.intro = '';
  148. this.outro = '';
  149. this.content = content;
  150. this.storeName = false;
  151. this.edited = false;
  152. // we make these non-enumerable, for sanity while debugging
  153. Object.defineProperties(this, {
  154. previous: { writable: true, value: null },
  155. next: { writable: true, value: null }
  156. });
  157. };
  158. Chunk.prototype.appendLeft = function appendLeft (content) {
  159. this.outro += content;
  160. };
  161. Chunk.prototype.appendRight = function appendRight (content) {
  162. this.intro = this.intro + content;
  163. };
  164. Chunk.prototype.clone = function clone () {
  165. var chunk = new Chunk(this.start, this.end, this.original);
  166. chunk.intro = this.intro;
  167. chunk.outro = this.outro;
  168. chunk.content = this.content;
  169. chunk.storeName = this.storeName;
  170. chunk.edited = this.edited;
  171. return chunk;
  172. };
  173. Chunk.prototype.contains = function contains (index) {
  174. return this.start < index && index < this.end;
  175. };
  176. Chunk.prototype.eachNext = function eachNext (fn) {
  177. var chunk = this;
  178. while (chunk) {
  179. fn(chunk);
  180. chunk = chunk.next;
  181. }
  182. };
  183. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  184. var chunk = this;
  185. while (chunk) {
  186. fn(chunk);
  187. chunk = chunk.previous;
  188. }
  189. };
  190. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  191. this.content = content;
  192. if (!contentOnly) {
  193. this.intro = '';
  194. this.outro = '';
  195. }
  196. this.storeName = storeName;
  197. this.edited = true;
  198. return this;
  199. };
  200. Chunk.prototype.prependLeft = function prependLeft (content) {
  201. this.outro = content + this.outro;
  202. };
  203. Chunk.prototype.prependRight = function prependRight (content) {
  204. this.intro = content + this.intro;
  205. };
  206. Chunk.prototype.split = function split (index) {
  207. var sliceIndex = index - this.start;
  208. var originalBefore = this.original.slice(0, sliceIndex);
  209. var originalAfter = this.original.slice(sliceIndex);
  210. this.original = originalBefore;
  211. var newChunk = new Chunk(index, this.end, originalAfter);
  212. newChunk.outro = this.outro;
  213. this.outro = '';
  214. this.end = index;
  215. if (this.edited) {
  216. // TODO is this block necessary?...
  217. newChunk.edit('', false);
  218. this.content = '';
  219. } else {
  220. this.content = originalBefore;
  221. }
  222. newChunk.next = this.next;
  223. if (newChunk.next) { newChunk.next.previous = newChunk; }
  224. newChunk.previous = this;
  225. this.next = newChunk;
  226. return newChunk;
  227. };
  228. Chunk.prototype.toString = function toString () {
  229. return this.intro + this.content + this.outro;
  230. };
  231. Chunk.prototype.trimEnd = function trimEnd (rx) {
  232. this.outro = this.outro.replace(rx, '');
  233. if (this.outro.length) { return true; }
  234. var trimmed = this.content.replace(rx, '');
  235. if (trimmed.length) {
  236. if (trimmed !== this.content) {
  237. this.split(this.start + trimmed.length).edit('', undefined, true);
  238. }
  239. return true;
  240. } else {
  241. this.edit('', undefined, true);
  242. this.intro = this.intro.replace(rx, '');
  243. if (this.intro.length) { return true; }
  244. }
  245. };
  246. Chunk.prototype.trimStart = function trimStart (rx) {
  247. this.intro = this.intro.replace(rx, '');
  248. if (this.intro.length) { return true; }
  249. var trimmed = this.content.replace(rx, '');
  250. if (trimmed.length) {
  251. if (trimmed !== this.content) {
  252. this.split(this.end - trimmed.length);
  253. this.edit('', undefined, true);
  254. }
  255. return true;
  256. } else {
  257. this.edit('', undefined, true);
  258. this.outro = this.outro.replace(rx, '');
  259. if (this.outro.length) { return true; }
  260. }
  261. };
  262. var btoa = function () {
  263. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  264. };
  265. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  266. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  267. } else if (typeof Buffer === 'function') {
  268. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  269. }
  270. var SourceMap = function SourceMap(properties) {
  271. this.version = 3;
  272. this.file = properties.file;
  273. this.sources = properties.sources;
  274. this.sourcesContent = properties.sourcesContent;
  275. this.names = properties.names;
  276. this.mappings = encode(properties.mappings);
  277. };
  278. SourceMap.prototype.toString = function toString () {
  279. return JSON.stringify(this);
  280. };
  281. SourceMap.prototype.toUrl = function toUrl () {
  282. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  283. };
  284. function guessIndent(code) {
  285. var lines = code.split('\n');
  286. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  287. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  288. if (tabbed.length === 0 && spaced.length === 0) {
  289. return null;
  290. }
  291. // More lines tabbed than spaced? Assume tabs, and
  292. // default to tabs in the case of a tie (or nothing
  293. // to go on)
  294. if (tabbed.length >= spaced.length) {
  295. return '\t';
  296. }
  297. // Otherwise, we need to guess the multiple
  298. var min = spaced.reduce(function (previous, current) {
  299. var numSpaces = /^ +/.exec(current)[0].length;
  300. return Math.min(numSpaces, previous);
  301. }, Infinity);
  302. return new Array(min + 1).join(' ');
  303. }
  304. function getRelativePath(from, to) {
  305. var fromParts = from.split(/[/\\]/);
  306. var toParts = to.split(/[/\\]/);
  307. fromParts.pop(); // get dirname
  308. while (fromParts[0] === toParts[0]) {
  309. fromParts.shift();
  310. toParts.shift();
  311. }
  312. if (fromParts.length) {
  313. var i = fromParts.length;
  314. while (i--) { fromParts[i] = '..'; }
  315. }
  316. return fromParts.concat(toParts).join('/');
  317. }
  318. var toString = Object.prototype.toString;
  319. function isObject(thing) {
  320. return toString.call(thing) === '[object Object]';
  321. }
  322. function getLocator(source) {
  323. var originalLines = source.split('\n');
  324. var lineOffsets = [];
  325. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  326. lineOffsets.push(pos);
  327. pos += originalLines[i].length + 1;
  328. }
  329. return function locate(index) {
  330. var i = 0;
  331. var j = lineOffsets.length;
  332. while (i < j) {
  333. var m = (i + j) >> 1;
  334. if (index < lineOffsets[m]) {
  335. j = m;
  336. } else {
  337. i = m + 1;
  338. }
  339. }
  340. var line = i - 1;
  341. var column = index - lineOffsets[line];
  342. return { line: line, column: column };
  343. };
  344. }
  345. var Mappings = function Mappings(hires) {
  346. this.hires = hires;
  347. this.generatedCodeLine = 0;
  348. this.generatedCodeColumn = 0;
  349. this.raw = [];
  350. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  351. this.pending = null;
  352. };
  353. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  354. if (content.length) {
  355. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  356. if (nameIndex >= 0) {
  357. segment.push(nameIndex);
  358. }
  359. this.rawSegments.push(segment);
  360. } else if (this.pending) {
  361. this.rawSegments.push(this.pending);
  362. }
  363. this.advance(content);
  364. this.pending = null;
  365. };
  366. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  367. var originalCharIndex = chunk.start;
  368. var first = true;
  369. while (originalCharIndex < chunk.end) {
  370. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  371. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  372. }
  373. if (original[originalCharIndex] === '\n') {
  374. loc.line += 1;
  375. loc.column = 0;
  376. this.generatedCodeLine += 1;
  377. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  378. this.generatedCodeColumn = 0;
  379. first = true;
  380. } else {
  381. loc.column += 1;
  382. this.generatedCodeColumn += 1;
  383. first = false;
  384. }
  385. originalCharIndex += 1;
  386. }
  387. this.pending = null;
  388. };
  389. Mappings.prototype.advance = function advance (str) {
  390. if (!str) { return; }
  391. var lines = str.split('\n');
  392. if (lines.length > 1) {
  393. for (var i = 0; i < lines.length - 1; i++) {
  394. this.generatedCodeLine++;
  395. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  396. }
  397. this.generatedCodeColumn = 0;
  398. }
  399. this.generatedCodeColumn += lines[lines.length - 1].length;
  400. };
  401. var n = '\n';
  402. var warned = {
  403. insertLeft: false,
  404. insertRight: false,
  405. storeName: false
  406. };
  407. var MagicString = function MagicString(string, options) {
  408. if ( options === void 0 ) options = {};
  409. var chunk = new Chunk(0, string.length, string);
  410. Object.defineProperties(this, {
  411. original: { writable: true, value: string },
  412. outro: { writable: true, value: '' },
  413. intro: { writable: true, value: '' },
  414. firstChunk: { writable: true, value: chunk },
  415. lastChunk: { writable: true, value: chunk },
  416. lastSearchedChunk: { writable: true, value: chunk },
  417. byStart: { writable: true, value: {} },
  418. byEnd: { writable: true, value: {} },
  419. filename: { writable: true, value: options.filename },
  420. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  421. sourcemapLocations: { writable: true, value: new BitSet() },
  422. storedNames: { writable: true, value: {} },
  423. indentStr: { writable: true, value: guessIndent(string) }
  424. });
  425. this.byStart[0] = chunk;
  426. this.byEnd[string.length] = chunk;
  427. };
  428. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  429. this.sourcemapLocations.add(char);
  430. };
  431. MagicString.prototype.append = function append (content) {
  432. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  433. this.outro += content;
  434. return this;
  435. };
  436. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  437. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  438. this._split(index);
  439. var chunk = this.byEnd[index];
  440. if (chunk) {
  441. chunk.appendLeft(content);
  442. } else {
  443. this.intro += content;
  444. }
  445. return this;
  446. };
  447. MagicString.prototype.appendRight = function appendRight (index, content) {
  448. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  449. this._split(index);
  450. var chunk = this.byStart[index];
  451. if (chunk) {
  452. chunk.appendRight(content);
  453. } else {
  454. this.outro += content;
  455. }
  456. return this;
  457. };
  458. MagicString.prototype.clone = function clone () {
  459. var cloned = new MagicString(this.original, { filename: this.filename });
  460. var originalChunk = this.firstChunk;
  461. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  462. while (originalChunk) {
  463. cloned.byStart[clonedChunk.start] = clonedChunk;
  464. cloned.byEnd[clonedChunk.end] = clonedChunk;
  465. var nextOriginalChunk = originalChunk.next;
  466. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  467. if (nextClonedChunk) {
  468. clonedChunk.next = nextClonedChunk;
  469. nextClonedChunk.previous = clonedChunk;
  470. clonedChunk = nextClonedChunk;
  471. }
  472. originalChunk = nextOriginalChunk;
  473. }
  474. cloned.lastChunk = clonedChunk;
  475. if (this.indentExclusionRanges) {
  476. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  477. }
  478. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  479. cloned.intro = this.intro;
  480. cloned.outro = this.outro;
  481. return cloned;
  482. };
  483. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  484. var this$1 = this;
  485. options = options || {};
  486. var sourceIndex = 0;
  487. var names = Object.keys(this.storedNames);
  488. var mappings = new Mappings(options.hires);
  489. var locate = getLocator(this.original);
  490. if (this.intro) {
  491. mappings.advance(this.intro);
  492. }
  493. this.firstChunk.eachNext(function (chunk) {
  494. var loc = locate(chunk.start);
  495. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  496. if (chunk.edited) {
  497. mappings.addEdit(
  498. sourceIndex,
  499. chunk.content,
  500. loc,
  501. chunk.storeName ? names.indexOf(chunk.original) : -1
  502. );
  503. } else {
  504. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  505. }
  506. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  507. });
  508. return {
  509. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  510. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  511. sourcesContent: options.includeContent ? [this.original] : [null],
  512. names: names,
  513. mappings: mappings.raw
  514. };
  515. };
  516. MagicString.prototype.generateMap = function generateMap (options) {
  517. return new SourceMap(this.generateDecodedMap(options));
  518. };
  519. MagicString.prototype.getIndentString = function getIndentString () {
  520. return this.indentStr === null ? '\t' : this.indentStr;
  521. };
  522. MagicString.prototype.indent = function indent (indentStr, options) {
  523. var pattern = /^[^\r\n]/gm;
  524. if (isObject(indentStr)) {
  525. options = indentStr;
  526. indentStr = undefined;
  527. }
  528. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  529. if (indentStr === '') { return this; } // noop
  530. options = options || {};
  531. // Process exclusion ranges
  532. var isExcluded = {};
  533. if (options.exclude) {
  534. var exclusions =
  535. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  536. exclusions.forEach(function (exclusion) {
  537. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  538. isExcluded[i] = true;
  539. }
  540. });
  541. }
  542. var shouldIndentNextCharacter = options.indentStart !== false;
  543. var replacer = function (match) {
  544. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  545. shouldIndentNextCharacter = true;
  546. return match;
  547. };
  548. this.intro = this.intro.replace(pattern, replacer);
  549. var charIndex = 0;
  550. var chunk = this.firstChunk;
  551. while (chunk) {
  552. var end = chunk.end;
  553. if (chunk.edited) {
  554. if (!isExcluded[charIndex]) {
  555. chunk.content = chunk.content.replace(pattern, replacer);
  556. if (chunk.content.length) {
  557. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  558. }
  559. }
  560. } else {
  561. charIndex = chunk.start;
  562. while (charIndex < end) {
  563. if (!isExcluded[charIndex]) {
  564. var char = this.original[charIndex];
  565. if (char === '\n') {
  566. shouldIndentNextCharacter = true;
  567. } else if (char !== '\r' && shouldIndentNextCharacter) {
  568. shouldIndentNextCharacter = false;
  569. if (charIndex === chunk.start) {
  570. chunk.prependRight(indentStr);
  571. } else {
  572. this._splitChunk(chunk, charIndex);
  573. chunk = chunk.next;
  574. chunk.prependRight(indentStr);
  575. }
  576. }
  577. }
  578. charIndex += 1;
  579. }
  580. }
  581. charIndex = chunk.end;
  582. chunk = chunk.next;
  583. }
  584. this.outro = this.outro.replace(pattern, replacer);
  585. return this;
  586. };
  587. MagicString.prototype.insert = function insert () {
  588. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  589. };
  590. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  591. if (!warned.insertLeft) {
  592. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  593. warned.insertLeft = true;
  594. }
  595. return this.appendLeft(index, content);
  596. };
  597. MagicString.prototype.insertRight = function insertRight (index, content) {
  598. if (!warned.insertRight) {
  599. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  600. warned.insertRight = true;
  601. }
  602. return this.prependRight(index, content);
  603. };
  604. MagicString.prototype.move = function move (start, end, index) {
  605. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  606. this._split(start);
  607. this._split(end);
  608. this._split(index);
  609. var first = this.byStart[start];
  610. var last = this.byEnd[end];
  611. var oldLeft = first.previous;
  612. var oldRight = last.next;
  613. var newRight = this.byStart[index];
  614. if (!newRight && last === this.lastChunk) { return this; }
  615. var newLeft = newRight ? newRight.previous : this.lastChunk;
  616. if (oldLeft) { oldLeft.next = oldRight; }
  617. if (oldRight) { oldRight.previous = oldLeft; }
  618. if (newLeft) { newLeft.next = first; }
  619. if (newRight) { newRight.previous = last; }
  620. if (!first.previous) { this.firstChunk = last.next; }
  621. if (!last.next) {
  622. this.lastChunk = first.previous;
  623. this.lastChunk.next = null;
  624. }
  625. first.previous = newLeft;
  626. last.next = newRight || null;
  627. if (!newLeft) { this.firstChunk = first; }
  628. if (!newRight) { this.lastChunk = last; }
  629. return this;
  630. };
  631. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  632. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  633. while (start < 0) { start += this.original.length; }
  634. while (end < 0) { end += this.original.length; }
  635. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  636. if (start === end)
  637. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  638. this._split(start);
  639. this._split(end);
  640. if (options === true) {
  641. if (!warned.storeName) {
  642. 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
  643. warned.storeName = true;
  644. }
  645. options = { storeName: true };
  646. }
  647. var storeName = options !== undefined ? options.storeName : false;
  648. var contentOnly = options !== undefined ? options.contentOnly : false;
  649. if (storeName) {
  650. var original = this.original.slice(start, end);
  651. this.storedNames[original] = true;
  652. }
  653. var first = this.byStart[start];
  654. var last = this.byEnd[end];
  655. if (first) {
  656. if (end > first.end && first.next !== this.byStart[first.end]) {
  657. throw new Error('Cannot overwrite across a split point');
  658. }
  659. first.edit(content, storeName, contentOnly);
  660. if (first !== last) {
  661. var chunk = first.next;
  662. while (chunk !== last) {
  663. chunk.edit('', false);
  664. chunk = chunk.next;
  665. }
  666. chunk.edit('', false);
  667. }
  668. } else {
  669. // must be inserting at the end
  670. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  671. // TODO last chunk in the array may not be the last chunk, if it's moved...
  672. last.next = newChunk;
  673. newChunk.previous = last;
  674. }
  675. return this;
  676. };
  677. MagicString.prototype.prepend = function prepend (content) {
  678. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  679. this.intro = content + this.intro;
  680. return this;
  681. };
  682. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  683. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  684. this._split(index);
  685. var chunk = this.byEnd[index];
  686. if (chunk) {
  687. chunk.prependLeft(content);
  688. } else {
  689. this.intro = content + this.intro;
  690. }
  691. return this;
  692. };
  693. MagicString.prototype.prependRight = function prependRight (index, content) {
  694. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  695. this._split(index);
  696. var chunk = this.byStart[index];
  697. if (chunk) {
  698. chunk.prependRight(content);
  699. } else {
  700. this.outro = content + this.outro;
  701. }
  702. return this;
  703. };
  704. MagicString.prototype.remove = function remove (start, end) {
  705. while (start < 0) { start += this.original.length; }
  706. while (end < 0) { end += this.original.length; }
  707. if (start === end) { return this; }
  708. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  709. if (start > end) { throw new Error('end must be greater than start'); }
  710. this._split(start);
  711. this._split(end);
  712. var chunk = this.byStart[start];
  713. while (chunk) {
  714. chunk.intro = '';
  715. chunk.outro = '';
  716. chunk.edit('');
  717. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  718. }
  719. return this;
  720. };
  721. MagicString.prototype.lastChar = function lastChar () {
  722. if (this.outro.length)
  723. { return this.outro[this.outro.length - 1]; }
  724. var chunk = this.lastChunk;
  725. do {
  726. if (chunk.outro.length)
  727. { return chunk.outro[chunk.outro.length - 1]; }
  728. if (chunk.content.length)
  729. { return chunk.content[chunk.content.length - 1]; }
  730. if (chunk.intro.length)
  731. { return chunk.intro[chunk.intro.length - 1]; }
  732. } while (chunk = chunk.previous);
  733. if (this.intro.length)
  734. { return this.intro[this.intro.length - 1]; }
  735. return '';
  736. };
  737. MagicString.prototype.lastLine = function lastLine () {
  738. var lineIndex = this.outro.lastIndexOf(n);
  739. if (lineIndex !== -1)
  740. { return this.outro.substr(lineIndex + 1); }
  741. var lineStr = this.outro;
  742. var chunk = this.lastChunk;
  743. do {
  744. if (chunk.outro.length > 0) {
  745. lineIndex = chunk.outro.lastIndexOf(n);
  746. if (lineIndex !== -1)
  747. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  748. lineStr = chunk.outro + lineStr;
  749. }
  750. if (chunk.content.length > 0) {
  751. lineIndex = chunk.content.lastIndexOf(n);
  752. if (lineIndex !== -1)
  753. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  754. lineStr = chunk.content + lineStr;
  755. }
  756. if (chunk.intro.length > 0) {
  757. lineIndex = chunk.intro.lastIndexOf(n);
  758. if (lineIndex !== -1)
  759. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  760. lineStr = chunk.intro + lineStr;
  761. }
  762. } while (chunk = chunk.previous);
  763. lineIndex = this.intro.lastIndexOf(n);
  764. if (lineIndex !== -1)
  765. { return this.intro.substr(lineIndex + 1) + lineStr; }
  766. return this.intro + lineStr;
  767. };
  768. MagicString.prototype.slice = function slice (start, end) {
  769. if ( start === void 0 ) start = 0;
  770. if ( end === void 0 ) end = this.original.length;
  771. while (start < 0) { start += this.original.length; }
  772. while (end < 0) { end += this.original.length; }
  773. var result = '';
  774. // find start chunk
  775. var chunk = this.firstChunk;
  776. while (chunk && (chunk.start > start || chunk.end <= start)) {
  777. // found end chunk before start
  778. if (chunk.start < end && chunk.end >= end) {
  779. return result;
  780. }
  781. chunk = chunk.next;
  782. }
  783. if (chunk && chunk.edited && chunk.start !== start)
  784. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  785. var startChunk = chunk;
  786. while (chunk) {
  787. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  788. result += chunk.intro;
  789. }
  790. var containsEnd = chunk.start < end && chunk.end >= end;
  791. if (containsEnd && chunk.edited && chunk.end !== end)
  792. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  793. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  794. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  795. result += chunk.content.slice(sliceStart, sliceEnd);
  796. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  797. result += chunk.outro;
  798. }
  799. if (containsEnd) {
  800. break;
  801. }
  802. chunk = chunk.next;
  803. }
  804. return result;
  805. };
  806. // TODO deprecate this? not really very useful
  807. MagicString.prototype.snip = function snip (start, end) {
  808. var clone = this.clone();
  809. clone.remove(0, start);
  810. clone.remove(end, clone.original.length);
  811. return clone;
  812. };
  813. MagicString.prototype._split = function _split (index) {
  814. if (this.byStart[index] || this.byEnd[index]) { return; }
  815. var chunk = this.lastSearchedChunk;
  816. var searchForward = index > chunk.end;
  817. while (chunk) {
  818. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  819. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  820. }
  821. };
  822. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  823. if (chunk.edited && chunk.content.length) {
  824. // zero-length edited chunks are a special case (overlapping replacements)
  825. var loc = getLocator(this.original)(index);
  826. throw new Error(
  827. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  828. );
  829. }
  830. var newChunk = chunk.split(index);
  831. this.byEnd[index] = chunk;
  832. this.byStart[index] = newChunk;
  833. this.byEnd[newChunk.end] = newChunk;
  834. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  835. this.lastSearchedChunk = chunk;
  836. return true;
  837. };
  838. MagicString.prototype.toString = function toString () {
  839. var str = this.intro;
  840. var chunk = this.firstChunk;
  841. while (chunk) {
  842. str += chunk.toString();
  843. chunk = chunk.next;
  844. }
  845. return str + this.outro;
  846. };
  847. MagicString.prototype.isEmpty = function isEmpty () {
  848. var chunk = this.firstChunk;
  849. do {
  850. if (chunk.intro.length && chunk.intro.trim() ||
  851. chunk.content.length && chunk.content.trim() ||
  852. chunk.outro.length && chunk.outro.trim())
  853. { return false; }
  854. } while (chunk = chunk.next);
  855. return true;
  856. };
  857. MagicString.prototype.length = function length () {
  858. var chunk = this.firstChunk;
  859. var length = 0;
  860. do {
  861. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  862. } while (chunk = chunk.next);
  863. return length;
  864. };
  865. MagicString.prototype.trimLines = function trimLines () {
  866. return this.trim('[\\r\\n]');
  867. };
  868. MagicString.prototype.trim = function trim (charType) {
  869. return this.trimStart(charType).trimEnd(charType);
  870. };
  871. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  872. var rx = new RegExp((charType || '\\s') + '+$');
  873. this.outro = this.outro.replace(rx, '');
  874. if (this.outro.length) { return true; }
  875. var chunk = this.lastChunk;
  876. do {
  877. var end = chunk.end;
  878. var aborted = chunk.trimEnd(rx);
  879. // if chunk was trimmed, we have a new lastChunk
  880. if (chunk.end !== end) {
  881. if (this.lastChunk === chunk) {
  882. this.lastChunk = chunk.next;
  883. }
  884. this.byEnd[chunk.end] = chunk;
  885. this.byStart[chunk.next.start] = chunk.next;
  886. this.byEnd[chunk.next.end] = chunk.next;
  887. }
  888. if (aborted) { return true; }
  889. chunk = chunk.previous;
  890. } while (chunk);
  891. return false;
  892. };
  893. MagicString.prototype.trimEnd = function trimEnd (charType) {
  894. this.trimEndAborted(charType);
  895. return this;
  896. };
  897. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  898. var rx = new RegExp('^' + (charType || '\\s') + '+');
  899. this.intro = this.intro.replace(rx, '');
  900. if (this.intro.length) { return true; }
  901. var chunk = this.firstChunk;
  902. do {
  903. var end = chunk.end;
  904. var aborted = chunk.trimStart(rx);
  905. if (chunk.end !== end) {
  906. // special case...
  907. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  908. this.byEnd[chunk.end] = chunk;
  909. this.byStart[chunk.next.start] = chunk.next;
  910. this.byEnd[chunk.next.end] = chunk.next;
  911. }
  912. if (aborted) { return true; }
  913. chunk = chunk.next;
  914. } while (chunk);
  915. return false;
  916. };
  917. MagicString.prototype.trimStart = function trimStart (charType) {
  918. this.trimStartAborted(charType);
  919. return this;
  920. };
  921. var hasOwnProp = Object.prototype.hasOwnProperty;
  922. var Bundle = function Bundle(options) {
  923. if ( options === void 0 ) options = {};
  924. this.intro = options.intro || '';
  925. this.separator = options.separator !== undefined ? options.separator : '\n';
  926. this.sources = [];
  927. this.uniqueSources = [];
  928. this.uniqueSourceIndexByFilename = {};
  929. };
  930. Bundle.prototype.addSource = function addSource (source) {
  931. if (source instanceof MagicString) {
  932. return this.addSource({
  933. content: source,
  934. filename: source.filename,
  935. separator: this.separator
  936. });
  937. }
  938. if (!isObject(source) || !source.content) {
  939. throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
  940. }
  941. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  942. if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
  943. });
  944. if (source.separator === undefined) {
  945. // TODO there's a bunch of this sort of thing, needs cleaning up
  946. source.separator = this.separator;
  947. }
  948. if (source.filename) {
  949. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  950. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  951. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  952. } else {
  953. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  954. if (source.content.original !== uniqueSource.content) {
  955. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  956. }
  957. }
  958. }
  959. this.sources.push(source);
  960. return this;
  961. };
  962. Bundle.prototype.append = function append (str, options) {
  963. this.addSource({
  964. content: new MagicString(str),
  965. separator: (options && options.separator) || ''
  966. });
  967. return this;
  968. };
  969. Bundle.prototype.clone = function clone () {
  970. var bundle = new Bundle({
  971. intro: this.intro,
  972. separator: this.separator
  973. });
  974. this.sources.forEach(function (source) {
  975. bundle.addSource({
  976. filename: source.filename,
  977. content: source.content.clone(),
  978. separator: source.separator
  979. });
  980. });
  981. return bundle;
  982. };
  983. Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
  984. var this$1 = this;
  985. if ( options === void 0 ) options = {};
  986. var names = [];
  987. this.sources.forEach(function (source) {
  988. Object.keys(source.content.storedNames).forEach(function (name) {
  989. if (!~names.indexOf(name)) { names.push(name); }
  990. });
  991. });
  992. var mappings = new Mappings(options.hires);
  993. if (this.intro) {
  994. mappings.advance(this.intro);
  995. }
  996. this.sources.forEach(function (source, i) {
  997. if (i > 0) {
  998. mappings.advance(this$1.separator);
  999. }
  1000. var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
  1001. var magicString = source.content;
  1002. var locate = getLocator(magicString.original);
  1003. if (magicString.intro) {
  1004. mappings.advance(magicString.intro);
  1005. }
  1006. magicString.firstChunk.eachNext(function (chunk) {
  1007. var loc = locate(chunk.start);
  1008. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  1009. if (source.filename) {
  1010. if (chunk.edited) {
  1011. mappings.addEdit(
  1012. sourceIndex,
  1013. chunk.content,
  1014. loc,
  1015. chunk.storeName ? names.indexOf(chunk.original) : -1
  1016. );
  1017. } else {
  1018. mappings.addUneditedChunk(
  1019. sourceIndex,
  1020. chunk,
  1021. magicString.original,
  1022. loc,
  1023. magicString.sourcemapLocations
  1024. );
  1025. }
  1026. } else {
  1027. mappings.advance(chunk.content);
  1028. }
  1029. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  1030. });
  1031. if (magicString.outro) {
  1032. mappings.advance(magicString.outro);
  1033. }
  1034. });
  1035. return {
  1036. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1037. sources: this.uniqueSources.map(function (source) {
  1038. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1039. }),
  1040. sourcesContent: this.uniqueSources.map(function (source) {
  1041. return options.includeContent ? source.content : null;
  1042. }),
  1043. names: names,
  1044. mappings: mappings.raw
  1045. };
  1046. };
  1047. Bundle.prototype.generateMap = function generateMap (options) {
  1048. return new SourceMap(this.generateDecodedMap(options));
  1049. };
  1050. Bundle.prototype.getIndentString = function getIndentString () {
  1051. var indentStringCounts = {};
  1052. this.sources.forEach(function (source) {
  1053. var indentStr = source.content.indentStr;
  1054. if (indentStr === null) { return; }
  1055. if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
  1056. indentStringCounts[indentStr] += 1;
  1057. });
  1058. return (
  1059. Object.keys(indentStringCounts).sort(function (a, b) {
  1060. return indentStringCounts[a] - indentStringCounts[b];
  1061. })[0] || '\t'
  1062. );
  1063. };
  1064. Bundle.prototype.indent = function indent (indentStr) {
  1065. var this$1 = this;
  1066. if (!arguments.length) {
  1067. indentStr = this.getIndentString();
  1068. }
  1069. if (indentStr === '') { return this; } // noop
  1070. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1071. this.sources.forEach(function (source, i) {
  1072. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  1073. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1074. source.content.indent(indentStr, {
  1075. exclude: source.indentExclusionRanges,
  1076. indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1077. });
  1078. trailingNewline = source.content.lastChar() === '\n';
  1079. });
  1080. if (this.intro) {
  1081. this.intro =
  1082. indentStr +
  1083. this.intro.replace(/^[^\n]/gm, function (match, index) {
  1084. return index > 0 ? indentStr + match : match;
  1085. });
  1086. }
  1087. return this;
  1088. };
  1089. Bundle.prototype.prepend = function prepend (str) {
  1090. this.intro = str + this.intro;
  1091. return this;
  1092. };
  1093. Bundle.prototype.toString = function toString () {
  1094. var this$1 = this;
  1095. var body = this.sources
  1096. .map(function (source, i) {
  1097. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  1098. var str = (i > 0 ? separator : '') + source.content.toString();
  1099. return str;
  1100. })
  1101. .join('');
  1102. return this.intro + body;
  1103. };
  1104. Bundle.prototype.isEmpty = function isEmpty () {
  1105. if (this.intro.length && this.intro.trim())
  1106. { return false; }
  1107. if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
  1108. { return false; }
  1109. return true;
  1110. };
  1111. Bundle.prototype.length = function length () {
  1112. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  1113. };
  1114. Bundle.prototype.trimLines = function trimLines () {
  1115. return this.trim('[\\r\\n]');
  1116. };
  1117. Bundle.prototype.trim = function trim (charType) {
  1118. return this.trimStart(charType).trimEnd(charType);
  1119. };
  1120. Bundle.prototype.trimStart = function trimStart (charType) {
  1121. var rx = new RegExp('^' + (charType || '\\s') + '+');
  1122. this.intro = this.intro.replace(rx, '');
  1123. if (!this.intro) {
  1124. var source;
  1125. var i = 0;
  1126. do {
  1127. source = this.sources[i++];
  1128. if (!source) {
  1129. break;
  1130. }
  1131. } while (!source.content.trimStartAborted(charType));
  1132. }
  1133. return this;
  1134. };
  1135. Bundle.prototype.trimEnd = function trimEnd (charType) {
  1136. var rx = new RegExp((charType || '\\s') + '+$');
  1137. var source;
  1138. var i = this.sources.length - 1;
  1139. do {
  1140. source = this.sources[i--];
  1141. if (!source) {
  1142. this.intro = this.intro.replace(rx, '');
  1143. break;
  1144. }
  1145. } while (!source.content.trimEndAborted(charType));
  1146. return this;
  1147. };
  1148. function relative(from, to) {
  1149. const fromParts = from.split(/[/\\]/).filter(Boolean);
  1150. const toParts = to.split(/[/\\]/).filter(Boolean);
  1151. if (fromParts[0] === '.')
  1152. fromParts.shift();
  1153. if (toParts[0] === '.')
  1154. toParts.shift();
  1155. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1156. fromParts.shift();
  1157. toParts.shift();
  1158. }
  1159. while (toParts[0] === '..' && fromParts.length > 0) {
  1160. toParts.shift();
  1161. fromParts.pop();
  1162. }
  1163. while (fromParts.pop()) {
  1164. toParts.unshift('..');
  1165. }
  1166. return toParts.join('/');
  1167. }
  1168. const ArrowFunctionExpression = 'ArrowFunctionExpression';
  1169. const BlockStatement = 'BlockStatement';
  1170. const CallExpression = 'CallExpression';
  1171. const ExpressionStatement = 'ExpressionStatement';
  1172. const FunctionExpression = 'FunctionExpression';
  1173. const Identifier = 'Identifier';
  1174. const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
  1175. const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
  1176. const Program = 'Program';
  1177. const Property = 'Property';
  1178. const ReturnStatement = 'ReturnStatement';
  1179. function treeshakeNode(node, code, start, end) {
  1180. code.remove(start, end);
  1181. if (node.annotations) {
  1182. for (const annotation of node.annotations) {
  1183. if (annotation.start < start) {
  1184. code.remove(annotation.start, annotation.end);
  1185. }
  1186. else {
  1187. return;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. function removeAnnotations(node, code) {
  1193. if (!node.annotations && node.parent.type === ExpressionStatement) {
  1194. node = node.parent;
  1195. }
  1196. if (node.annotations) {
  1197. for (const annotation of node.annotations) {
  1198. code.remove(annotation.start, annotation.end);
  1199. }
  1200. }
  1201. }
  1202. const NO_SEMICOLON = { isNoStatement: true };
  1203. // This assumes there are only white-space and comments between start and the string we are looking for
  1204. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1205. let searchPos, charCodeAfterSlash;
  1206. searchPos = code.indexOf(searchString, start);
  1207. while (true) {
  1208. start = code.indexOf('/', start);
  1209. if (start === -1 || start >= searchPos)
  1210. return searchPos;
  1211. charCodeAfterSlash = code.charCodeAt(++start);
  1212. ++start;
  1213. // With our assumption, '/' always starts a comment. Determine comment type:
  1214. start =
  1215. charCodeAfterSlash === 47 /*"/"*/
  1216. ? code.indexOf('\n', start) + 1
  1217. : code.indexOf('*/', start) + 2;
  1218. if (start > searchPos) {
  1219. searchPos = code.indexOf(searchString, start);
  1220. }
  1221. }
  1222. }
  1223. const WHITESPACE = /\s/;
  1224. function findNonWhiteSpace(code, index) {
  1225. while (index < code.length && WHITESPACE.test(code[index]))
  1226. index++;
  1227. return index;
  1228. }
  1229. // This assumes "code" only contains white-space and comments
  1230. // Returns position of line-comment if applicable
  1231. function findFirstLineBreakOutsideComment(code) {
  1232. let lineBreakPos, charCodeAfterSlash, start = 0;
  1233. lineBreakPos = code.indexOf('\n', start);
  1234. while (true) {
  1235. start = code.indexOf('/', start);
  1236. if (start === -1 || start > lineBreakPos)
  1237. return [lineBreakPos, lineBreakPos + 1];
  1238. // With our assumption, '/' always starts a comment. Determine comment type:
  1239. charCodeAfterSlash = code.charCodeAt(start + 1);
  1240. if (charCodeAfterSlash === 47 /*"/"*/)
  1241. return [start, lineBreakPos + 1];
  1242. start = code.indexOf('*/', start + 3) + 2;
  1243. if (start > lineBreakPos) {
  1244. lineBreakPos = code.indexOf('\n', start);
  1245. }
  1246. }
  1247. }
  1248. function renderStatementList(statements, code, start, end, options) {
  1249. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1250. let nextNode = statements[0];
  1251. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1252. if (nextNodeNeedsBoundaries) {
  1253. nextNodeStart =
  1254. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  1255. }
  1256. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1257. currentNode = nextNode;
  1258. currentNodeStart = nextNodeStart;
  1259. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1260. nextNode = statements[nextIndex];
  1261. nextNodeNeedsBoundaries =
  1262. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  1263. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  1264. nextNodeStart =
  1265. currentNode.end +
  1266. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  1267. if (currentNode.included) {
  1268. currentNodeNeedsBoundaries
  1269. ? currentNode.render(code, options, {
  1270. end: nextNodeStart,
  1271. start: currentNodeStart
  1272. })
  1273. : currentNode.render(code, options);
  1274. }
  1275. else {
  1276. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  1277. }
  1278. }
  1279. else {
  1280. currentNode.render(code, options);
  1281. }
  1282. }
  1283. }
  1284. // This assumes that the first character is not part of the first node
  1285. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  1286. const splitUpNodes = [];
  1287. let node, nextNode, nextNodeStart, contentEnd, char;
  1288. let separator = start - 1;
  1289. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  1290. nextNode = nodes[nextIndex];
  1291. if (node !== undefined) {
  1292. separator =
  1293. node.end +
  1294. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  1295. }
  1296. nextNodeStart = contentEnd =
  1297. separator +
  1298. 1 +
  1299. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  1300. while (((char = code.original.charCodeAt(nextNodeStart)),
  1301. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  1302. nextNodeStart++;
  1303. if (node !== undefined) {
  1304. splitUpNodes.push({
  1305. contentEnd,
  1306. end: nextNodeStart,
  1307. node,
  1308. separator,
  1309. start
  1310. });
  1311. }
  1312. node = nextNode;
  1313. start = nextNodeStart;
  1314. }
  1315. splitUpNodes.push({
  1316. contentEnd: end,
  1317. end,
  1318. node: node,
  1319. separator: null,
  1320. start
  1321. });
  1322. return splitUpNodes;
  1323. }
  1324. // This assumes there are only white-space and comments between start and end
  1325. function removeLineBreaks(code, start, end) {
  1326. while (true) {
  1327. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  1328. if (removeStart === -1) {
  1329. break;
  1330. }
  1331. code.remove(start + removeStart, (start += removeEnd));
  1332. }
  1333. }
  1334. function getSystemExportStatement(exportedVariables, options) {
  1335. const _ = options.compact ? '' : ' ';
  1336. if (exportedVariables.length === 1 &&
  1337. options.exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  1338. const variable = exportedVariables[0];
  1339. return `exports('${options.exportNamesByVariable.get(variable)}',${_}${variable.getName()})`;
  1340. }
  1341. else {
  1342. return `exports({${_}${exportedVariables
  1343. .map(variable => {
  1344. return options.exportNamesByVariable
  1345. .get(variable)
  1346. .map(exportName => `${exportName}:${_}${variable.getName()}`)
  1347. .join(`,${_}`);
  1348. })
  1349. .join(`,${_}`)}${_}})`;
  1350. }
  1351. }
  1352. function getSystemExportFunctionLeft(exportedVariables, setFromExpression, options) {
  1353. const _ = options.compact ? '' : ' ';
  1354. const s = options.compact ? '' : ';';
  1355. return `function${_}(v)${_}{${_}return exports({${_}${exportedVariables
  1356. .map(variable => {
  1357. return options.exportNamesByVariable
  1358. .get(variable)
  1359. .map(exportName => `${exportName}:${_}${setFromExpression ? variable.getName() : 'v'}`)
  1360. .join(`,${_}`);
  1361. })
  1362. .join(`,${_}`)}${_}}),${_}v${s}${_}}(`;
  1363. }
  1364. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  1365. const base = 64;
  1366. function toBase64(num) {
  1367. let outStr = '';
  1368. do {
  1369. const curDigit = num % base;
  1370. num = Math.floor(num / base);
  1371. outStr = chars$1[curDigit] + outStr;
  1372. } while (num !== 0);
  1373. return outStr;
  1374. }
  1375. const RESERVED_NAMES = {
  1376. // @ts-ignore
  1377. __proto__: null,
  1378. await: true,
  1379. break: true,
  1380. case: true,
  1381. catch: true,
  1382. class: true,
  1383. const: true,
  1384. continue: true,
  1385. debugger: true,
  1386. default: true,
  1387. delete: true,
  1388. do: true,
  1389. else: true,
  1390. enum: true,
  1391. eval: true,
  1392. export: true,
  1393. extends: true,
  1394. false: true,
  1395. finally: true,
  1396. for: true,
  1397. function: true,
  1398. if: true,
  1399. implements: true,
  1400. import: true,
  1401. in: true,
  1402. instanceof: true,
  1403. interface: true,
  1404. let: true,
  1405. new: true,
  1406. null: true,
  1407. package: true,
  1408. private: true,
  1409. protected: true,
  1410. public: true,
  1411. return: true,
  1412. static: true,
  1413. super: true,
  1414. switch: true,
  1415. this: true,
  1416. throw: true,
  1417. true: true,
  1418. try: true,
  1419. typeof: true,
  1420. undefined: true,
  1421. var: true,
  1422. void: true,
  1423. while: true,
  1424. with: true,
  1425. yield: true
  1426. };
  1427. function getSafeName(baseName, usedNames) {
  1428. let safeName = baseName;
  1429. let count = 1;
  1430. while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
  1431. safeName = `${baseName}$${toBase64(count++)}`;
  1432. }
  1433. usedNames.add(safeName);
  1434. return safeName;
  1435. }
  1436. const NO_ARGS = [];
  1437. function getOrCreate(map, key, init) {
  1438. const existing = map.get(key);
  1439. if (existing) {
  1440. return existing;
  1441. }
  1442. const value = init();
  1443. map.set(key, value);
  1444. return value;
  1445. }
  1446. const UnknownKey = Symbol('Unknown Key');
  1447. const EMPTY_PATH = [];
  1448. const UNKNOWN_PATH = [UnknownKey];
  1449. const EntitiesKey = Symbol('Entities');
  1450. class PathTracker {
  1451. constructor() {
  1452. this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1453. }
  1454. getEntities(path) {
  1455. let currentPaths = this.entityPaths;
  1456. for (const pathSegment of path) {
  1457. currentPaths = currentPaths[pathSegment] =
  1458. currentPaths[pathSegment] ||
  1459. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1460. }
  1461. return currentPaths[EntitiesKey];
  1462. }
  1463. }
  1464. const SHARED_RECURSION_TRACKER = new PathTracker();
  1465. class DiscriminatedPathTracker {
  1466. constructor() {
  1467. this.entityPaths = Object.create(null, {
  1468. [EntitiesKey]: { value: new Map() }
  1469. });
  1470. }
  1471. getEntities(path, discriminator) {
  1472. let currentPaths = this.entityPaths;
  1473. for (const pathSegment of path) {
  1474. currentPaths = currentPaths[pathSegment] =
  1475. currentPaths[pathSegment] ||
  1476. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1477. }
  1478. return getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1479. }
  1480. }
  1481. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  1482. return Object.create(inheritedDescriptions, memberDescriptions);
  1483. }
  1484. const UnknownValue = Symbol('Unknown Value');
  1485. const UNKNOWN_EXPRESSION = {
  1486. deoptimizePath: () => { },
  1487. getLiteralValueAtPath: () => UnknownValue,
  1488. getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
  1489. hasEffectsWhenAccessedAtPath: path => path.length > 0,
  1490. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1491. hasEffectsWhenCalledAtPath: () => true,
  1492. include: () => { },
  1493. includeCallArguments(context, args) {
  1494. for (const arg of args) {
  1495. arg.include(context, false);
  1496. }
  1497. },
  1498. included: true,
  1499. toString: () => '[[UNKNOWN]]'
  1500. };
  1501. const UNDEFINED_EXPRESSION = {
  1502. deoptimizePath: () => { },
  1503. getLiteralValueAtPath: () => undefined,
  1504. getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
  1505. hasEffectsWhenAccessedAtPath: path => path.length > 0,
  1506. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1507. hasEffectsWhenCalledAtPath: () => true,
  1508. include: () => { },
  1509. includeCallArguments() { },
  1510. included: true,
  1511. toString: () => 'undefined'
  1512. };
  1513. const returnsUnknown = {
  1514. value: {
  1515. callsArgs: null,
  1516. mutatesSelf: false,
  1517. returns: null,
  1518. returnsPrimitive: UNKNOWN_EXPRESSION
  1519. }
  1520. };
  1521. const mutatesSelfReturnsUnknown = {
  1522. value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
  1523. };
  1524. const callsArgReturnsUnknown = {
  1525. value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
  1526. };
  1527. class UnknownArrayExpression {
  1528. constructor() {
  1529. this.included = false;
  1530. }
  1531. deoptimizePath() { }
  1532. getLiteralValueAtPath() {
  1533. return UnknownValue;
  1534. }
  1535. getReturnExpressionWhenCalledAtPath(path) {
  1536. if (path.length === 1) {
  1537. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  1538. }
  1539. return UNKNOWN_EXPRESSION;
  1540. }
  1541. hasEffectsWhenAccessedAtPath(path) {
  1542. return path.length > 1;
  1543. }
  1544. hasEffectsWhenAssignedAtPath(path) {
  1545. return path.length > 1;
  1546. }
  1547. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  1548. if (path.length === 1) {
  1549. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  1550. }
  1551. return true;
  1552. }
  1553. include() {
  1554. this.included = true;
  1555. }
  1556. includeCallArguments(context, args) {
  1557. for (const arg of args) {
  1558. arg.include(context, false);
  1559. }
  1560. }
  1561. toString() {
  1562. return '[[UNKNOWN ARRAY]]';
  1563. }
  1564. }
  1565. const returnsArray = {
  1566. value: {
  1567. callsArgs: null,
  1568. mutatesSelf: false,
  1569. returns: UnknownArrayExpression,
  1570. returnsPrimitive: null
  1571. }
  1572. };
  1573. const mutatesSelfReturnsArray = {
  1574. value: {
  1575. callsArgs: null,
  1576. mutatesSelf: true,
  1577. returns: UnknownArrayExpression,
  1578. returnsPrimitive: null
  1579. }
  1580. };
  1581. const callsArgReturnsArray = {
  1582. value: {
  1583. callsArgs: [0],
  1584. mutatesSelf: false,
  1585. returns: UnknownArrayExpression,
  1586. returnsPrimitive: null
  1587. }
  1588. };
  1589. const callsArgMutatesSelfReturnsArray = {
  1590. value: {
  1591. callsArgs: [0],
  1592. mutatesSelf: true,
  1593. returns: UnknownArrayExpression,
  1594. returnsPrimitive: null
  1595. }
  1596. };
  1597. const UNKNOWN_LITERAL_BOOLEAN = {
  1598. deoptimizePath: () => { },
  1599. getLiteralValueAtPath: () => UnknownValue,
  1600. getReturnExpressionWhenCalledAtPath: path => {
  1601. if (path.length === 1) {
  1602. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  1603. }
  1604. return UNKNOWN_EXPRESSION;
  1605. },
  1606. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  1607. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1608. hasEffectsWhenCalledAtPath: path => {
  1609. if (path.length === 1) {
  1610. const subPath = path[0];
  1611. return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
  1612. }
  1613. return true;
  1614. },
  1615. include: () => { },
  1616. includeCallArguments(context, args) {
  1617. for (const arg of args) {
  1618. arg.include(context, false);
  1619. }
  1620. },
  1621. included: true,
  1622. toString: () => '[[UNKNOWN BOOLEAN]]'
  1623. };
  1624. const returnsBoolean = {
  1625. value: {
  1626. callsArgs: null,
  1627. mutatesSelf: false,
  1628. returns: null,
  1629. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  1630. }
  1631. };
  1632. const callsArgReturnsBoolean = {
  1633. value: {
  1634. callsArgs: [0],
  1635. mutatesSelf: false,
  1636. returns: null,
  1637. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  1638. }
  1639. };
  1640. const UNKNOWN_LITERAL_NUMBER = {
  1641. deoptimizePath: () => { },
  1642. getLiteralValueAtPath: () => UnknownValue,
  1643. getReturnExpressionWhenCalledAtPath: path => {
  1644. if (path.length === 1) {
  1645. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  1646. }
  1647. return UNKNOWN_EXPRESSION;
  1648. },
  1649. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  1650. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1651. hasEffectsWhenCalledAtPath: path => {
  1652. if (path.length === 1) {
  1653. const subPath = path[0];
  1654. return typeof subPath !== 'string' || !literalNumberMembers[subPath];
  1655. }
  1656. return true;
  1657. },
  1658. include: () => { },
  1659. includeCallArguments(context, args) {
  1660. for (const arg of args) {
  1661. arg.include(context, false);
  1662. }
  1663. },
  1664. included: true,
  1665. toString: () => '[[UNKNOWN NUMBER]]'
  1666. };
  1667. const returnsNumber = {
  1668. value: {
  1669. callsArgs: null,
  1670. mutatesSelf: false,
  1671. returns: null,
  1672. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  1673. }
  1674. };
  1675. const mutatesSelfReturnsNumber = {
  1676. value: {
  1677. callsArgs: null,
  1678. mutatesSelf: true,
  1679. returns: null,
  1680. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  1681. }
  1682. };
  1683. const callsArgReturnsNumber = {
  1684. value: {
  1685. callsArgs: [0],
  1686. mutatesSelf: false,
  1687. returns: null,
  1688. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  1689. }
  1690. };
  1691. const UNKNOWN_LITERAL_STRING = {
  1692. deoptimizePath: () => { },
  1693. getLiteralValueAtPath: () => UnknownValue,
  1694. getReturnExpressionWhenCalledAtPath: path => {
  1695. if (path.length === 1) {
  1696. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  1697. }
  1698. return UNKNOWN_EXPRESSION;
  1699. },
  1700. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  1701. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1702. hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
  1703. if (path.length === 1) {
  1704. return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
  1705. }
  1706. return true;
  1707. },
  1708. include: () => { },
  1709. includeCallArguments(context, args) {
  1710. for (const arg of args) {
  1711. arg.include(context, false);
  1712. }
  1713. },
  1714. included: true,
  1715. toString: () => '[[UNKNOWN STRING]]'
  1716. };
  1717. const returnsString = {
  1718. value: {
  1719. callsArgs: null,
  1720. mutatesSelf: false,
  1721. returns: null,
  1722. returnsPrimitive: UNKNOWN_LITERAL_STRING
  1723. }
  1724. };
  1725. class UnknownObjectExpression {
  1726. constructor() {
  1727. this.included = false;
  1728. }
  1729. deoptimizePath() { }
  1730. getLiteralValueAtPath() {
  1731. return UnknownValue;
  1732. }
  1733. getReturnExpressionWhenCalledAtPath(path) {
  1734. if (path.length === 1) {
  1735. return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
  1736. }
  1737. return UNKNOWN_EXPRESSION;
  1738. }
  1739. hasEffectsWhenAccessedAtPath(path) {
  1740. return path.length > 1;
  1741. }
  1742. hasEffectsWhenAssignedAtPath(path) {
  1743. return path.length > 1;
  1744. }
  1745. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  1746. if (path.length === 1) {
  1747. return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
  1748. }
  1749. return true;
  1750. }
  1751. include() {
  1752. this.included = true;
  1753. }
  1754. includeCallArguments(context, args) {
  1755. for (const arg of args) {
  1756. arg.include(context, false);
  1757. }
  1758. }
  1759. toString() {
  1760. return '[[UNKNOWN OBJECT]]';
  1761. }
  1762. }
  1763. const objectMembers = assembleMemberDescriptions({
  1764. hasOwnProperty: returnsBoolean,
  1765. isPrototypeOf: returnsBoolean,
  1766. propertyIsEnumerable: returnsBoolean,
  1767. toLocaleString: returnsString,
  1768. toString: returnsString,
  1769. valueOf: returnsUnknown
  1770. });
  1771. const arrayMembers = assembleMemberDescriptions({
  1772. concat: returnsArray,
  1773. copyWithin: mutatesSelfReturnsArray,
  1774. every: callsArgReturnsBoolean,
  1775. fill: mutatesSelfReturnsArray,
  1776. filter: callsArgReturnsArray,
  1777. find: callsArgReturnsUnknown,
  1778. findIndex: callsArgReturnsNumber,
  1779. forEach: callsArgReturnsUnknown,
  1780. includes: returnsBoolean,
  1781. indexOf: returnsNumber,
  1782. join: returnsString,
  1783. lastIndexOf: returnsNumber,
  1784. map: callsArgReturnsArray,
  1785. pop: mutatesSelfReturnsUnknown,
  1786. push: mutatesSelfReturnsNumber,
  1787. reduce: callsArgReturnsUnknown,
  1788. reduceRight: callsArgReturnsUnknown,
  1789. reverse: mutatesSelfReturnsArray,
  1790. shift: mutatesSelfReturnsUnknown,
  1791. slice: returnsArray,
  1792. some: callsArgReturnsBoolean,
  1793. sort: callsArgMutatesSelfReturnsArray,
  1794. splice: mutatesSelfReturnsArray,
  1795. unshift: mutatesSelfReturnsNumber
  1796. }, objectMembers);
  1797. const literalBooleanMembers = assembleMemberDescriptions({
  1798. valueOf: returnsBoolean
  1799. }, objectMembers);
  1800. const literalNumberMembers = assembleMemberDescriptions({
  1801. toExponential: returnsString,
  1802. toFixed: returnsString,
  1803. toLocaleString: returnsString,
  1804. toPrecision: returnsString,
  1805. valueOf: returnsNumber
  1806. }, objectMembers);
  1807. const literalStringMembers = assembleMemberDescriptions({
  1808. charAt: returnsString,
  1809. charCodeAt: returnsNumber,
  1810. codePointAt: returnsNumber,
  1811. concat: returnsString,
  1812. endsWith: returnsBoolean,
  1813. includes: returnsBoolean,
  1814. indexOf: returnsNumber,
  1815. lastIndexOf: returnsNumber,
  1816. localeCompare: returnsNumber,
  1817. match: returnsBoolean,
  1818. normalize: returnsString,
  1819. padEnd: returnsString,
  1820. padStart: returnsString,
  1821. repeat: returnsString,
  1822. replace: {
  1823. value: {
  1824. callsArgs: [1],
  1825. mutatesSelf: false,
  1826. returns: null,
  1827. returnsPrimitive: UNKNOWN_LITERAL_STRING
  1828. }
  1829. },
  1830. search: returnsNumber,
  1831. slice: returnsString,
  1832. split: returnsArray,
  1833. startsWith: returnsBoolean,
  1834. substr: returnsString,
  1835. substring: returnsString,
  1836. toLocaleLowerCase: returnsString,
  1837. toLocaleUpperCase: returnsString,
  1838. toLowerCase: returnsString,
  1839. toUpperCase: returnsString,
  1840. trim: returnsString,
  1841. valueOf: returnsString
  1842. }, objectMembers);
  1843. function getLiteralMembersForValue(value) {
  1844. switch (typeof value) {
  1845. case 'boolean':
  1846. return literalBooleanMembers;
  1847. case 'number':
  1848. return literalNumberMembers;
  1849. case 'string':
  1850. return literalStringMembers;
  1851. default:
  1852. return Object.create(null);
  1853. }
  1854. }
  1855. function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
  1856. if (typeof memberName !== 'string' ||
  1857. !members[memberName] ||
  1858. (members[memberName].mutatesSelf && parentIncluded))
  1859. return true;
  1860. if (!members[memberName].callsArgs)
  1861. return false;
  1862. for (const argIndex of members[memberName].callsArgs) {
  1863. if (callOptions.args[argIndex] &&
  1864. callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  1865. args: NO_ARGS,
  1866. withNew: false
  1867. }, context))
  1868. return true;
  1869. }
  1870. return false;
  1871. }
  1872. function getMemberReturnExpressionWhenCalled(members, memberName) {
  1873. if (typeof memberName !== 'string' || !members[memberName])
  1874. return UNKNOWN_EXPRESSION;
  1875. return members[memberName].returnsPrimitive !== null
  1876. ? members[memberName].returnsPrimitive
  1877. : new members[memberName].returns();
  1878. }
  1879. class Variable {
  1880. constructor(name) {
  1881. this.alwaysRendered = false;
  1882. this.included = false;
  1883. this.isId = false;
  1884. this.isReassigned = false;
  1885. this.renderBaseName = null;
  1886. this.renderName = null;
  1887. this.name = name;
  1888. }
  1889. /**
  1890. * Binds identifiers that reference this variable to this variable.
  1891. * Necessary to be able to change variable names.
  1892. */
  1893. addReference(_identifier) { }
  1894. deoptimizePath(_path) { }
  1895. getBaseVariableName() {
  1896. return this.renderBaseName || this.renderName || this.name;
  1897. }
  1898. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1899. return UnknownValue;
  1900. }
  1901. getName() {
  1902. const name = this.renderName || this.name;
  1903. return this.renderBaseName
  1904. ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
  1905. : name;
  1906. }
  1907. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  1908. return UNKNOWN_EXPRESSION;
  1909. }
  1910. hasEffectsWhenAccessedAtPath(path, _context) {
  1911. return path.length > 0;
  1912. }
  1913. hasEffectsWhenAssignedAtPath(_path, _context) {
  1914. return true;
  1915. }
  1916. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  1917. return true;
  1918. }
  1919. /**
  1920. * Marks this variable as being part of the bundle, which is usually the case when one of
  1921. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1922. * previously.
  1923. * Once a variable is included, it should take care all its declarations are included.
  1924. */
  1925. include() {
  1926. this.included = true;
  1927. }
  1928. includeCallArguments(context, args) {
  1929. for (const arg of args) {
  1930. arg.include(context, false);
  1931. }
  1932. }
  1933. markCalledFromTryStatement() { }
  1934. setRenderNames(baseName, name) {
  1935. this.renderBaseName = baseName;
  1936. this.renderName = name;
  1937. }
  1938. }
  1939. class ExternalVariable extends Variable {
  1940. constructor(module, name) {
  1941. super(name);
  1942. this.module = module;
  1943. this.isNamespace = name === '*';
  1944. this.referenced = false;
  1945. }
  1946. addReference(identifier) {
  1947. this.referenced = true;
  1948. if (this.name === 'default' || this.name === '*') {
  1949. this.module.suggestName(identifier.name);
  1950. }
  1951. }
  1952. include() {
  1953. if (!this.included) {
  1954. this.included = true;
  1955. this.module.used = true;
  1956. }
  1957. }
  1958. }
  1959. const BLANK = Object.freeze(Object.create(null));
  1960. const EMPTY_OBJECT = Object.freeze({});
  1961. const EMPTY_ARRAY = Object.freeze([]);
  1962. const reservedWords = '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(' ');
  1963. const builtins = '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(' ');
  1964. const blacklisted = new Set(reservedWords.concat(builtins));
  1965. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  1966. const startsWithDigit = (str) => /\d/.test(str[0]);
  1967. function isLegal(str) {
  1968. if (startsWithDigit(str) || blacklisted.has(str)) {
  1969. return false;
  1970. }
  1971. return !illegalCharacters.test(str);
  1972. }
  1973. function makeLegal(str) {
  1974. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  1975. if (startsWithDigit(str) || blacklisted.has(str))
  1976. str = `_${str}`;
  1977. return str || '_';
  1978. }
  1979. const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  1980. const relativePath = /^\.?\.\//;
  1981. function isAbsolute(path) {
  1982. return absolutePath.test(path);
  1983. }
  1984. function isRelative(path) {
  1985. return relativePath.test(path);
  1986. }
  1987. function normalize(path) {
  1988. if (path.indexOf('\\') == -1)
  1989. return path;
  1990. return path.replace(/\\/g, '/');
  1991. }
  1992. class ExternalModule {
  1993. constructor(options, id, hasModuleSideEffects, meta) {
  1994. this.options = options;
  1995. this.id = id;
  1996. this.defaultVariableName = '';
  1997. this.dynamicImporters = [];
  1998. this.importers = [];
  1999. this.mostCommonSuggestion = 0;
  2000. this.namespaceVariableName = '';
  2001. this.reexported = false;
  2002. this.renderPath = undefined;
  2003. this.renormalizeRenderPath = false;
  2004. this.used = false;
  2005. this.variableName = '';
  2006. this.execIndex = Infinity;
  2007. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  2008. this.nameSuggestions = Object.create(null);
  2009. this.declarations = Object.create(null);
  2010. this.exportedVariables = new Map();
  2011. const module = this;
  2012. this.info = {
  2013. ast: null,
  2014. code: null,
  2015. dynamicallyImportedIds: EMPTY_ARRAY,
  2016. get dynamicImporters() {
  2017. return module.dynamicImporters.sort();
  2018. },
  2019. hasModuleSideEffects,
  2020. id,
  2021. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2022. implicitlyLoadedBefore: EMPTY_ARRAY,
  2023. importedIds: EMPTY_ARRAY,
  2024. get importers() {
  2025. return module.importers.sort();
  2026. },
  2027. isEntry: false,
  2028. isExternal: true,
  2029. meta,
  2030. syntheticNamedExports: false
  2031. };
  2032. }
  2033. getVariableForExportName(name) {
  2034. let declaration = this.declarations[name];
  2035. if (declaration)
  2036. return declaration;
  2037. this.declarations[name] = declaration = new ExternalVariable(this, name);
  2038. this.exportedVariables.set(declaration, name);
  2039. return declaration;
  2040. }
  2041. setRenderPath(options, inputBase) {
  2042. this.renderPath =
  2043. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2044. if (!this.renderPath) {
  2045. if (!isAbsolute(this.id)) {
  2046. this.renderPath = this.id;
  2047. }
  2048. else {
  2049. this.renderPath = normalize(relative$1(inputBase, this.id));
  2050. this.renormalizeRenderPath = true;
  2051. }
  2052. }
  2053. return this.renderPath;
  2054. }
  2055. suggestName(name) {
  2056. if (!this.nameSuggestions[name])
  2057. this.nameSuggestions[name] = 0;
  2058. this.nameSuggestions[name] += 1;
  2059. if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
  2060. this.mostCommonSuggestion = this.nameSuggestions[name];
  2061. this.suggestedVariableName = name;
  2062. }
  2063. }
  2064. warnUnusedImports() {
  2065. const unused = Object.keys(this.declarations).filter(name => {
  2066. if (name === '*')
  2067. return false;
  2068. const declaration = this.declarations[name];
  2069. return !declaration.included && !this.reexported && !declaration.referenced;
  2070. });
  2071. if (unused.length === 0)
  2072. return;
  2073. const names = unused.length === 1
  2074. ? `'${unused[0]}' is`
  2075. : `${unused
  2076. .slice(0, -1)
  2077. .map(name => `'${name}'`)
  2078. .join(', ')} and '${unused.slice(-1)}' are`;
  2079. this.options.onwarn({
  2080. code: 'UNUSED_EXTERNAL_IMPORT',
  2081. message: `${names} imported from external module '${this.id}' but never used`,
  2082. names: unused,
  2083. source: this.id
  2084. });
  2085. }
  2086. }
  2087. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2088. baseModule.isExecuted = true;
  2089. const modules = [baseModule];
  2090. const visitedModules = new Set();
  2091. for (const module of modules) {
  2092. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  2093. if (!(dependency instanceof ExternalModule) &&
  2094. !dependency.isExecuted &&
  2095. (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  2096. !visitedModules.has(dependency.id)) {
  2097. dependency.isExecuted = true;
  2098. visitedModules.add(dependency.id);
  2099. modules.push(dependency);
  2100. }
  2101. }
  2102. }
  2103. }
  2104. const BROKEN_FLOW_NONE = 0;
  2105. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  2106. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  2107. function createInclusionContext() {
  2108. return {
  2109. brokenFlow: BROKEN_FLOW_NONE,
  2110. includedCallArguments: new Set(),
  2111. includedLabels: new Set()
  2112. };
  2113. }
  2114. function createHasEffectsContext() {
  2115. return {
  2116. accessed: new PathTracker(),
  2117. assigned: new PathTracker(),
  2118. brokenFlow: BROKEN_FLOW_NONE,
  2119. called: new DiscriminatedPathTracker(),
  2120. ignore: {
  2121. breaks: false,
  2122. continues: false,
  2123. labels: new Set(),
  2124. returnAwaitYield: false
  2125. },
  2126. includedLabels: new Set(),
  2127. instantiated: new DiscriminatedPathTracker(),
  2128. replacedVariableInits: new Map()
  2129. };
  2130. }
  2131. // To avoid infinite recursions
  2132. const MAX_PATH_DEPTH = 7;
  2133. class LocalVariable extends Variable {
  2134. constructor(name, declarator, init, context) {
  2135. super(name);
  2136. this.additionalInitializers = null;
  2137. this.calledFromTryStatement = false;
  2138. this.expressionsToBeDeoptimized = [];
  2139. this.declarations = declarator ? [declarator] : [];
  2140. this.init = init;
  2141. this.deoptimizationTracker = context.deoptimizationTracker;
  2142. this.module = context.module;
  2143. }
  2144. addDeclaration(identifier, init) {
  2145. this.declarations.push(identifier);
  2146. if (this.additionalInitializers === null) {
  2147. this.additionalInitializers = this.init === null ? [] : [this.init];
  2148. this.init = UNKNOWN_EXPRESSION;
  2149. this.isReassigned = true;
  2150. }
  2151. if (init !== null) {
  2152. this.additionalInitializers.push(init);
  2153. }
  2154. }
  2155. consolidateInitializers() {
  2156. if (this.additionalInitializers !== null) {
  2157. for (const initializer of this.additionalInitializers) {
  2158. initializer.deoptimizePath(UNKNOWN_PATH);
  2159. }
  2160. this.additionalInitializers = null;
  2161. }
  2162. }
  2163. deoptimizePath(path) {
  2164. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2165. return;
  2166. const trackedEntities = this.deoptimizationTracker.getEntities(path);
  2167. if (trackedEntities.has(this))
  2168. return;
  2169. trackedEntities.add(this);
  2170. if (path.length === 0) {
  2171. if (!this.isReassigned) {
  2172. this.isReassigned = true;
  2173. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  2174. this.expressionsToBeDeoptimized = [];
  2175. for (const expression of expressionsToBeDeoptimized) {
  2176. expression.deoptimizeCache();
  2177. }
  2178. if (this.init) {
  2179. this.init.deoptimizePath(UNKNOWN_PATH);
  2180. }
  2181. }
  2182. }
  2183. else if (this.init) {
  2184. this.init.deoptimizePath(path);
  2185. }
  2186. }
  2187. getLiteralValueAtPath(path, recursionTracker, origin) {
  2188. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2189. return UnknownValue;
  2190. }
  2191. const trackedEntities = recursionTracker.getEntities(path);
  2192. if (trackedEntities.has(this.init)) {
  2193. return UnknownValue;
  2194. }
  2195. this.expressionsToBeDeoptimized.push(origin);
  2196. trackedEntities.add(this.init);
  2197. const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  2198. trackedEntities.delete(this.init);
  2199. return value;
  2200. }
  2201. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  2202. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2203. return UNKNOWN_EXPRESSION;
  2204. }
  2205. const trackedEntities = recursionTracker.getEntities(path);
  2206. if (trackedEntities.has(this.init)) {
  2207. return UNKNOWN_EXPRESSION;
  2208. }
  2209. this.expressionsToBeDeoptimized.push(origin);
  2210. trackedEntities.add(this.init);
  2211. const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  2212. trackedEntities.delete(this.init);
  2213. return value;
  2214. }
  2215. hasEffectsWhenAccessedAtPath(path, context) {
  2216. if (path.length === 0)
  2217. return false;
  2218. if (this.isReassigned || path.length > MAX_PATH_DEPTH)
  2219. return true;
  2220. const trackedExpressions = context.accessed.getEntities(path);
  2221. if (trackedExpressions.has(this))
  2222. return false;
  2223. trackedExpressions.add(this);
  2224. return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
  2225. }
  2226. hasEffectsWhenAssignedAtPath(path, context) {
  2227. if (this.included || path.length > MAX_PATH_DEPTH)
  2228. return true;
  2229. if (path.length === 0)
  2230. return false;
  2231. if (this.isReassigned)
  2232. return true;
  2233. const trackedExpressions = context.assigned.getEntities(path);
  2234. if (trackedExpressions.has(this))
  2235. return false;
  2236. trackedExpressions.add(this);
  2237. return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
  2238. }
  2239. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2240. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2241. return true;
  2242. const trackedExpressions = (callOptions.withNew
  2243. ? context.instantiated
  2244. : context.called).getEntities(path, callOptions);
  2245. if (trackedExpressions.has(this))
  2246. return false;
  2247. trackedExpressions.add(this);
  2248. return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2249. }
  2250. include() {
  2251. if (!this.included) {
  2252. this.included = true;
  2253. if (!this.module.isExecuted) {
  2254. markModuleAndImpureDependenciesAsExecuted(this.module);
  2255. }
  2256. for (const declaration of this.declarations) {
  2257. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  2258. if (!declaration.included)
  2259. declaration.include(createInclusionContext(), false);
  2260. let node = declaration.parent;
  2261. while (!node.included) {
  2262. // We do not want to properly include parents in case they are part of a dead branch
  2263. // in which case .include() might pull in more dead code
  2264. node.included = true;
  2265. if (node.type === Program)
  2266. break;
  2267. node = node.parent;
  2268. }
  2269. }
  2270. }
  2271. }
  2272. includeCallArguments(context, args) {
  2273. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  2274. for (const arg of args) {
  2275. arg.include(context, false);
  2276. }
  2277. }
  2278. else if (this.init) {
  2279. context.includedCallArguments.add(this.init);
  2280. this.init.includeCallArguments(context, args);
  2281. context.includedCallArguments.delete(this.init);
  2282. }
  2283. }
  2284. markCalledFromTryStatement() {
  2285. this.calledFromTryStatement = true;
  2286. }
  2287. }
  2288. class Scope {
  2289. constructor() {
  2290. this.children = [];
  2291. this.variables = new Map();
  2292. }
  2293. addDeclaration(identifier, context, init, _isHoisted) {
  2294. const name = identifier.name;
  2295. let variable = this.variables.get(name);
  2296. if (variable) {
  2297. variable.addDeclaration(identifier, init);
  2298. }
  2299. else {
  2300. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  2301. this.variables.set(name, variable);
  2302. }
  2303. return variable;
  2304. }
  2305. contains(name) {
  2306. return this.variables.has(name);
  2307. }
  2308. findVariable(_name) {
  2309. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  2310. }
  2311. }
  2312. class ChildScope extends Scope {
  2313. constructor(parent) {
  2314. super();
  2315. this.accessedOutsideVariables = new Map();
  2316. this.parent = parent;
  2317. parent.children.push(this);
  2318. }
  2319. addAccessedDynamicImport(importExpression) {
  2320. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  2321. if (this.parent instanceof ChildScope) {
  2322. this.parent.addAccessedDynamicImport(importExpression);
  2323. }
  2324. }
  2325. addAccessedGlobals(globals, accessedGlobalsByScope) {
  2326. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  2327. for (const name of globals) {
  2328. accessedGlobals.add(name);
  2329. }
  2330. accessedGlobalsByScope.set(this, accessedGlobals);
  2331. if (this.parent instanceof ChildScope) {
  2332. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  2333. }
  2334. }
  2335. addNamespaceMemberAccess(name, variable) {
  2336. this.accessedOutsideVariables.set(name, variable);
  2337. this.parent.addNamespaceMemberAccess(name, variable);
  2338. }
  2339. addReturnExpression(expression) {
  2340. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  2341. }
  2342. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  2343. for (const variable of this.accessedOutsideVariables.values()) {
  2344. if (variable.included) {
  2345. usedNames.add(variable.getBaseVariableName());
  2346. if (format === 'system' && exportNamesByVariable.has(variable)) {
  2347. usedNames.add('exports');
  2348. }
  2349. }
  2350. }
  2351. const accessedGlobals = accessedGlobalsByScope.get(this);
  2352. if (accessedGlobals) {
  2353. for (const name of accessedGlobals) {
  2354. usedNames.add(name);
  2355. }
  2356. }
  2357. }
  2358. contains(name) {
  2359. return this.variables.has(name) || this.parent.contains(name);
  2360. }
  2361. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  2362. const usedNames = new Set();
  2363. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  2364. if (this.accessedDynamicImports) {
  2365. for (const importExpression of this.accessedDynamicImports) {
  2366. if (importExpression.inlineNamespace) {
  2367. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  2368. }
  2369. }
  2370. }
  2371. for (const [name, variable] of this.variables) {
  2372. if (variable.included || variable.alwaysRendered) {
  2373. variable.setRenderNames(null, getSafeName(name, usedNames));
  2374. }
  2375. }
  2376. for (const scope of this.children) {
  2377. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  2378. }
  2379. }
  2380. findLexicalBoundary() {
  2381. return this.parent.findLexicalBoundary();
  2382. }
  2383. findVariable(name) {
  2384. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  2385. if (knownVariable) {
  2386. return knownVariable;
  2387. }
  2388. const variable = this.parent.findVariable(name);
  2389. this.accessedOutsideVariables.set(name, variable);
  2390. return variable;
  2391. }
  2392. }
  2393. function getLocator$1(source, options) {
  2394. if (options === void 0) { options = {}; }
  2395. var offsetLine = options.offsetLine || 0;
  2396. var offsetColumn = options.offsetColumn || 0;
  2397. var originalLines = source.split('\n');
  2398. var start = 0;
  2399. var lineRanges = originalLines.map(function (line, i) {
  2400. var end = start + line.length + 1;
  2401. var range = { start: start, end: end, line: i };
  2402. start = end;
  2403. return range;
  2404. });
  2405. var i = 0;
  2406. function rangeContains(range, index) {
  2407. return range.start <= index && index < range.end;
  2408. }
  2409. function getLocation(range, index) {
  2410. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  2411. }
  2412. function locate(search, startIndex) {
  2413. if (typeof search === 'string') {
  2414. search = source.indexOf(search, startIndex || 0);
  2415. }
  2416. var range = lineRanges[i];
  2417. var d = search >= range.end ? 1 : -1;
  2418. while (range) {
  2419. if (rangeContains(range, search))
  2420. return getLocation(range, search);
  2421. i += d;
  2422. range = lineRanges[i];
  2423. }
  2424. }
  2425. return locate;
  2426. }
  2427. function locate(source, search, options) {
  2428. if (typeof options === 'number') {
  2429. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  2430. }
  2431. return getLocator$1(source, options)(search, options && options.startIndex);
  2432. }
  2433. const keys = {
  2434. Literal: [],
  2435. Program: ['body']
  2436. };
  2437. function getAndCreateKeys(esTreeNode) {
  2438. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
  2439. return keys[esTreeNode.type];
  2440. }
  2441. const INCLUDE_PARAMETERS = 'variables';
  2442. class NodeBase {
  2443. constructor(esTreeNode, parent, parentScope) {
  2444. this.included = false;
  2445. this.esTreeNode = esTreeNode;
  2446. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  2447. this.parent = parent;
  2448. this.context = parent.context;
  2449. this.createScope(parentScope);
  2450. this.parseNode(esTreeNode);
  2451. this.initialise();
  2452. this.context.magicString.addSourcemapLocation(this.start);
  2453. this.context.magicString.addSourcemapLocation(this.end);
  2454. }
  2455. /**
  2456. * Override this to bind assignments to variables and do any initialisations that
  2457. * require the scopes to be populated with variables.
  2458. */
  2459. bind() {
  2460. for (const key of this.keys) {
  2461. const value = this[key];
  2462. if (value === null || key === 'annotations')
  2463. continue;
  2464. if (Array.isArray(value)) {
  2465. for (const child of value) {
  2466. if (child !== null)
  2467. child.bind();
  2468. }
  2469. }
  2470. else {
  2471. value.bind();
  2472. }
  2473. }
  2474. }
  2475. /**
  2476. * Override if this node should receive a different scope than the parent scope.
  2477. */
  2478. createScope(parentScope) {
  2479. this.scope = parentScope;
  2480. }
  2481. declare(_kind, _init) {
  2482. return [];
  2483. }
  2484. deoptimizePath(_path) { }
  2485. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2486. return UnknownValue;
  2487. }
  2488. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  2489. return UNKNOWN_EXPRESSION;
  2490. }
  2491. hasEffects(context) {
  2492. for (const key of this.keys) {
  2493. const value = this[key];
  2494. if (value === null || key === 'annotations')
  2495. continue;
  2496. if (Array.isArray(value)) {
  2497. for (const child of value) {
  2498. if (child !== null && child.hasEffects(context))
  2499. return true;
  2500. }
  2501. }
  2502. else if (value.hasEffects(context))
  2503. return true;
  2504. }
  2505. return false;
  2506. }
  2507. hasEffectsWhenAccessedAtPath(path, _context) {
  2508. return path.length > 0;
  2509. }
  2510. hasEffectsWhenAssignedAtPath(_path, _context) {
  2511. return true;
  2512. }
  2513. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  2514. return true;
  2515. }
  2516. include(context, includeChildrenRecursively) {
  2517. this.included = true;
  2518. for (const key of this.keys) {
  2519. const value = this[key];
  2520. if (value === null || key === 'annotations')
  2521. continue;
  2522. if (Array.isArray(value)) {
  2523. for (const child of value) {
  2524. if (child !== null)
  2525. child.include(context, includeChildrenRecursively);
  2526. }
  2527. }
  2528. else {
  2529. value.include(context, includeChildrenRecursively);
  2530. }
  2531. }
  2532. }
  2533. includeCallArguments(context, args) {
  2534. for (const arg of args) {
  2535. arg.include(context, false);
  2536. }
  2537. }
  2538. includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
  2539. this.include(context, includeChildrenRecursively);
  2540. }
  2541. /**
  2542. * Override to perform special initialisation steps after the scope is initialised
  2543. */
  2544. initialise() { }
  2545. insertSemicolon(code) {
  2546. if (code.original[this.end - 1] !== ';') {
  2547. code.appendLeft(this.end, ';');
  2548. }
  2549. }
  2550. parseNode(esTreeNode) {
  2551. for (const key of Object.keys(esTreeNode)) {
  2552. // That way, we can override this function to add custom initialisation and then call super.parseNode
  2553. if (this.hasOwnProperty(key))
  2554. continue;
  2555. const value = esTreeNode[key];
  2556. if (typeof value !== 'object' || value === null || key === 'annotations') {
  2557. this[key] = value;
  2558. }
  2559. else if (Array.isArray(value)) {
  2560. this[key] = [];
  2561. for (const child of value) {
  2562. this[key].push(child === null
  2563. ? null
  2564. : new (this.context.nodeConstructors[child.type] ||
  2565. this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
  2566. }
  2567. }
  2568. else {
  2569. this[key] = new (this.context.nodeConstructors[value.type] ||
  2570. this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
  2571. }
  2572. }
  2573. }
  2574. render(code, options) {
  2575. for (const key of this.keys) {
  2576. const value = this[key];
  2577. if (value === null || key === 'annotations')
  2578. continue;
  2579. if (Array.isArray(value)) {
  2580. for (const child of value) {
  2581. if (child !== null)
  2582. child.render(code, options);
  2583. }
  2584. }
  2585. else {
  2586. value.render(code, options);
  2587. }
  2588. }
  2589. }
  2590. shouldBeIncluded(context) {
  2591. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2592. }
  2593. toString() {
  2594. return this.context.code.slice(this.start, this.end);
  2595. }
  2596. }
  2597. class ClassNode extends NodeBase {
  2598. createScope(parentScope) {
  2599. this.scope = new ChildScope(parentScope);
  2600. }
  2601. hasEffectsWhenAccessedAtPath(path) {
  2602. if (path.length <= 1)
  2603. return false;
  2604. return path.length > 2 || path[0] !== 'prototype';
  2605. }
  2606. hasEffectsWhenAssignedAtPath(path) {
  2607. if (path.length <= 1)
  2608. return false;
  2609. return path.length > 2 || path[0] !== 'prototype';
  2610. }
  2611. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2612. if (!callOptions.withNew)
  2613. return true;
  2614. return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  2615. (this.superClass !== null &&
  2616. this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
  2617. }
  2618. initialise() {
  2619. if (this.id !== null) {
  2620. this.id.declare('class', this);
  2621. }
  2622. }
  2623. }
  2624. class ClassDeclaration extends ClassNode {
  2625. initialise() {
  2626. super.initialise();
  2627. if (this.id !== null) {
  2628. this.id.variable.isId = true;
  2629. }
  2630. }
  2631. parseNode(esTreeNode) {
  2632. if (esTreeNode.id !== null) {
  2633. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  2634. }
  2635. super.parseNode(esTreeNode);
  2636. }
  2637. render(code, options) {
  2638. if (options.format === 'system' &&
  2639. this.id &&
  2640. options.exportNamesByVariable.has(this.id.variable)) {
  2641. code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
  2642. }
  2643. super.render(code, options);
  2644. }
  2645. }
  2646. class ArgumentsVariable extends LocalVariable {
  2647. constructor(context) {
  2648. super('arguments', null, UNKNOWN_EXPRESSION, context);
  2649. }
  2650. hasEffectsWhenAccessedAtPath(path) {
  2651. return path.length > 1;
  2652. }
  2653. hasEffectsWhenAssignedAtPath() {
  2654. return true;
  2655. }
  2656. hasEffectsWhenCalledAtPath() {
  2657. return true;
  2658. }
  2659. }
  2660. class ThisVariable extends LocalVariable {
  2661. constructor(context) {
  2662. super('this', null, null, context);
  2663. }
  2664. getLiteralValueAtPath() {
  2665. return UnknownValue;
  2666. }
  2667. hasEffectsWhenAccessedAtPath(path, context) {
  2668. return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
  2669. super.hasEffectsWhenAccessedAtPath(path, context));
  2670. }
  2671. hasEffectsWhenAssignedAtPath(path, context) {
  2672. return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
  2673. super.hasEffectsWhenAssignedAtPath(path, context));
  2674. }
  2675. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2676. return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  2677. super.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2678. }
  2679. getInit(context) {
  2680. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  2681. }
  2682. }
  2683. class SpreadElement extends NodeBase {
  2684. bind() {
  2685. super.bind();
  2686. // Only properties of properties of the argument could become subject to reassignment
  2687. // This will also reassign the return values of iterators
  2688. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  2689. }
  2690. }
  2691. class ParameterScope extends ChildScope {
  2692. constructor(parent, context) {
  2693. super(parent);
  2694. this.parameters = [];
  2695. this.hasRest = false;
  2696. this.context = context;
  2697. this.hoistedBodyVarScope = new ChildScope(this);
  2698. }
  2699. /**
  2700. * Adds a parameter to this scope. Parameters must be added in the correct
  2701. * order, e.g. from left to right.
  2702. */
  2703. addParameterDeclaration(identifier) {
  2704. const name = identifier.name;
  2705. let variable = this.hoistedBodyVarScope.variables.get(name);
  2706. if (variable) {
  2707. variable.addDeclaration(identifier, null);
  2708. }
  2709. else {
  2710. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  2711. }
  2712. this.variables.set(name, variable);
  2713. return variable;
  2714. }
  2715. addParameterVariables(parameters, hasRest) {
  2716. this.parameters = parameters;
  2717. for (const parameterList of parameters) {
  2718. for (const parameter of parameterList) {
  2719. parameter.alwaysRendered = true;
  2720. }
  2721. }
  2722. this.hasRest = hasRest;
  2723. }
  2724. includeCallArguments(context, args) {
  2725. let calledFromTryStatement = false;
  2726. let argIncluded = false;
  2727. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  2728. for (const checkedArg of args) {
  2729. if (checkedArg instanceof SpreadElement) {
  2730. for (const arg of args) {
  2731. arg.include(context, false);
  2732. }
  2733. break;
  2734. }
  2735. }
  2736. for (let index = args.length - 1; index >= 0; index--) {
  2737. const paramVars = this.parameters[index] || restParam;
  2738. const arg = args[index];
  2739. if (paramVars) {
  2740. calledFromTryStatement = false;
  2741. for (const variable of paramVars) {
  2742. if (variable.included) {
  2743. argIncluded = true;
  2744. }
  2745. if (variable.calledFromTryStatement) {
  2746. calledFromTryStatement = true;
  2747. }
  2748. }
  2749. }
  2750. if (!argIncluded && arg.shouldBeIncluded(context)) {
  2751. argIncluded = true;
  2752. }
  2753. if (argIncluded) {
  2754. arg.include(context, calledFromTryStatement);
  2755. }
  2756. }
  2757. }
  2758. }
  2759. class ReturnValueScope extends ParameterScope {
  2760. constructor() {
  2761. super(...arguments);
  2762. this.returnExpression = null;
  2763. this.returnExpressions = [];
  2764. }
  2765. addReturnExpression(expression) {
  2766. this.returnExpressions.push(expression);
  2767. }
  2768. getReturnExpression() {
  2769. if (this.returnExpression === null)
  2770. this.updateReturnExpression();
  2771. return this.returnExpression;
  2772. }
  2773. updateReturnExpression() {
  2774. if (this.returnExpressions.length === 1) {
  2775. this.returnExpression = this.returnExpressions[0];
  2776. }
  2777. else {
  2778. this.returnExpression = UNKNOWN_EXPRESSION;
  2779. for (const expression of this.returnExpressions) {
  2780. expression.deoptimizePath(UNKNOWN_PATH);
  2781. }
  2782. }
  2783. }
  2784. }
  2785. class FunctionScope extends ReturnValueScope {
  2786. constructor(parent, context) {
  2787. super(parent, context);
  2788. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  2789. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  2790. }
  2791. findLexicalBoundary() {
  2792. return this;
  2793. }
  2794. includeCallArguments(context, args) {
  2795. super.includeCallArguments(context, args);
  2796. if (this.argumentsVariable.included) {
  2797. for (const arg of args) {
  2798. if (!arg.included) {
  2799. arg.include(context, false);
  2800. }
  2801. }
  2802. }
  2803. }
  2804. }
  2805. function isReference(node, parent) {
  2806. if (node.type === 'MemberExpression') {
  2807. return !node.computed && isReference(node.object, node);
  2808. }
  2809. if (node.type === 'Identifier') {
  2810. if (!parent)
  2811. return true;
  2812. switch (parent.type) {
  2813. // disregard `bar` in `foo.bar`
  2814. case 'MemberExpression': return parent.computed || node === parent.object;
  2815. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  2816. case 'MethodDefinition': return parent.computed;
  2817. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  2818. case 'FieldDefinition': return parent.computed || node === parent.value;
  2819. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  2820. case 'Property': return parent.computed || node === parent.value;
  2821. // disregard the `bar` in `export { foo as bar }` or
  2822. // the foo in `import { foo as bar }`
  2823. case 'ExportSpecifier':
  2824. case 'ImportSpecifier': return node === parent.local;
  2825. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  2826. case 'LabeledStatement':
  2827. case 'BreakStatement':
  2828. case 'ContinueStatement': return false;
  2829. default: return true;
  2830. }
  2831. }
  2832. return false;
  2833. }
  2834. const ValueProperties = Symbol('Value Properties');
  2835. const PURE = { pure: true };
  2836. const IMPURE = { pure: false };
  2837. // We use shortened variables to reduce file size here
  2838. /* OBJECT */
  2839. const O = {
  2840. // @ts-ignore
  2841. __proto__: null,
  2842. [ValueProperties]: IMPURE
  2843. };
  2844. /* PURE FUNCTION */
  2845. const PF = {
  2846. // @ts-ignore
  2847. __proto__: null,
  2848. [ValueProperties]: PURE
  2849. };
  2850. /* CONSTRUCTOR */
  2851. const C = {
  2852. // @ts-ignore
  2853. __proto__: null,
  2854. [ValueProperties]: IMPURE,
  2855. prototype: O
  2856. };
  2857. /* PURE CONSTRUCTOR */
  2858. const PC = {
  2859. // @ts-ignore
  2860. __proto__: null,
  2861. [ValueProperties]: PURE,
  2862. prototype: O
  2863. };
  2864. const ARRAY_TYPE = {
  2865. // @ts-ignore
  2866. __proto__: null,
  2867. [ValueProperties]: PURE,
  2868. from: PF,
  2869. of: PF,
  2870. prototype: O
  2871. };
  2872. const INTL_MEMBER = {
  2873. // @ts-ignore
  2874. __proto__: null,
  2875. [ValueProperties]: PURE,
  2876. supportedLocalesOf: PC
  2877. };
  2878. const knownGlobals = {
  2879. // Placeholders for global objects to avoid shape mutations
  2880. global: O,
  2881. globalThis: O,
  2882. self: O,
  2883. window: O,
  2884. // Common globals
  2885. // @ts-ignore
  2886. __proto__: null,
  2887. [ValueProperties]: IMPURE,
  2888. Array: {
  2889. // @ts-ignore
  2890. __proto__: null,
  2891. [ValueProperties]: IMPURE,
  2892. from: O,
  2893. isArray: PF,
  2894. of: PF,
  2895. prototype: O
  2896. },
  2897. ArrayBuffer: {
  2898. // @ts-ignore
  2899. __proto__: null,
  2900. [ValueProperties]: PURE,
  2901. isView: PF,
  2902. prototype: O
  2903. },
  2904. Atomics: O,
  2905. BigInt: C,
  2906. BigInt64Array: C,
  2907. BigUint64Array: C,
  2908. Boolean: PC,
  2909. // @ts-ignore
  2910. constructor: C,
  2911. DataView: PC,
  2912. Date: {
  2913. // @ts-ignore
  2914. __proto__: null,
  2915. [ValueProperties]: PURE,
  2916. now: PF,
  2917. parse: PF,
  2918. prototype: O,
  2919. UTC: PF
  2920. },
  2921. decodeURI: PF,
  2922. decodeURIComponent: PF,
  2923. encodeURI: PF,
  2924. encodeURIComponent: PF,
  2925. Error: PC,
  2926. escape: PF,
  2927. eval: O,
  2928. EvalError: PC,
  2929. Float32Array: ARRAY_TYPE,
  2930. Float64Array: ARRAY_TYPE,
  2931. Function: C,
  2932. // @ts-ignore
  2933. hasOwnProperty: O,
  2934. Infinity: O,
  2935. Int16Array: ARRAY_TYPE,
  2936. Int32Array: ARRAY_TYPE,
  2937. Int8Array: ARRAY_TYPE,
  2938. isFinite: PF,
  2939. isNaN: PF,
  2940. // @ts-ignore
  2941. isPrototypeOf: O,
  2942. JSON: O,
  2943. Map: PC,
  2944. Math: {
  2945. // @ts-ignore
  2946. __proto__: null,
  2947. [ValueProperties]: IMPURE,
  2948. abs: PF,
  2949. acos: PF,
  2950. acosh: PF,
  2951. asin: PF,
  2952. asinh: PF,
  2953. atan: PF,
  2954. atan2: PF,
  2955. atanh: PF,
  2956. cbrt: PF,
  2957. ceil: PF,
  2958. clz32: PF,
  2959. cos: PF,
  2960. cosh: PF,
  2961. exp: PF,
  2962. expm1: PF,
  2963. floor: PF,
  2964. fround: PF,
  2965. hypot: PF,
  2966. imul: PF,
  2967. log: PF,
  2968. log10: PF,
  2969. log1p: PF,
  2970. log2: PF,
  2971. max: PF,
  2972. min: PF,
  2973. pow: PF,
  2974. random: PF,
  2975. round: PF,
  2976. sign: PF,
  2977. sin: PF,
  2978. sinh: PF,
  2979. sqrt: PF,
  2980. tan: PF,
  2981. tanh: PF,
  2982. trunc: PF
  2983. },
  2984. NaN: O,
  2985. Number: {
  2986. // @ts-ignore
  2987. __proto__: null,
  2988. [ValueProperties]: PURE,
  2989. isFinite: PF,
  2990. isInteger: PF,
  2991. isNaN: PF,
  2992. isSafeInteger: PF,
  2993. parseFloat: PF,
  2994. parseInt: PF,
  2995. prototype: O
  2996. },
  2997. Object: {
  2998. // @ts-ignore
  2999. __proto__: null,
  3000. [ValueProperties]: PURE,
  3001. create: PF,
  3002. getNotifier: PF,
  3003. getOwn: PF,
  3004. getOwnPropertyDescriptor: PF,
  3005. getOwnPropertyNames: PF,
  3006. getOwnPropertySymbols: PF,
  3007. getPrototypeOf: PF,
  3008. is: PF,
  3009. isExtensible: PF,
  3010. isFrozen: PF,
  3011. isSealed: PF,
  3012. keys: PF,
  3013. prototype: O
  3014. },
  3015. parseFloat: PF,
  3016. parseInt: PF,
  3017. Promise: {
  3018. // @ts-ignore
  3019. __proto__: null,
  3020. [ValueProperties]: IMPURE,
  3021. all: PF,
  3022. prototype: O,
  3023. race: PF,
  3024. resolve: PF
  3025. },
  3026. // @ts-ignore
  3027. propertyIsEnumerable: O,
  3028. Proxy: O,
  3029. RangeError: PC,
  3030. ReferenceError: PC,
  3031. Reflect: O,
  3032. RegExp: PC,
  3033. Set: PC,
  3034. SharedArrayBuffer: C,
  3035. String: {
  3036. // @ts-ignore
  3037. __proto__: null,
  3038. [ValueProperties]: PURE,
  3039. fromCharCode: PF,
  3040. fromCodePoint: PF,
  3041. prototype: O,
  3042. raw: PF
  3043. },
  3044. Symbol: {
  3045. // @ts-ignore
  3046. __proto__: null,
  3047. [ValueProperties]: PURE,
  3048. for: PF,
  3049. keyFor: PF,
  3050. prototype: O
  3051. },
  3052. SyntaxError: PC,
  3053. // @ts-ignore
  3054. toLocaleString: O,
  3055. // @ts-ignore
  3056. toString: O,
  3057. TypeError: PC,
  3058. Uint16Array: ARRAY_TYPE,
  3059. Uint32Array: ARRAY_TYPE,
  3060. Uint8Array: ARRAY_TYPE,
  3061. Uint8ClampedArray: ARRAY_TYPE,
  3062. // Technically, this is a global, but it needs special handling
  3063. // undefined: ?,
  3064. unescape: PF,
  3065. URIError: PC,
  3066. // @ts-ignore
  3067. valueOf: O,
  3068. WeakMap: PC,
  3069. WeakSet: PC,
  3070. // Additional globals shared by Node and Browser that are not strictly part of the language
  3071. clearInterval: C,
  3072. clearTimeout: C,
  3073. console: O,
  3074. Intl: {
  3075. // @ts-ignore
  3076. __proto__: null,
  3077. [ValueProperties]: IMPURE,
  3078. Collator: INTL_MEMBER,
  3079. DateTimeFormat: INTL_MEMBER,
  3080. ListFormat: INTL_MEMBER,
  3081. NumberFormat: INTL_MEMBER,
  3082. PluralRules: INTL_MEMBER,
  3083. RelativeTimeFormat: INTL_MEMBER
  3084. },
  3085. setInterval: C,
  3086. setTimeout: C,
  3087. TextDecoder: C,
  3088. TextEncoder: C,
  3089. URL: C,
  3090. URLSearchParams: C,
  3091. // Browser specific globals
  3092. AbortController: C,
  3093. AbortSignal: C,
  3094. addEventListener: O,
  3095. alert: O,
  3096. AnalyserNode: C,
  3097. Animation: C,
  3098. AnimationEvent: C,
  3099. applicationCache: O,
  3100. ApplicationCache: C,
  3101. ApplicationCacheErrorEvent: C,
  3102. atob: O,
  3103. Attr: C,
  3104. Audio: C,
  3105. AudioBuffer: C,
  3106. AudioBufferSourceNode: C,
  3107. AudioContext: C,
  3108. AudioDestinationNode: C,
  3109. AudioListener: C,
  3110. AudioNode: C,
  3111. AudioParam: C,
  3112. AudioProcessingEvent: C,
  3113. AudioScheduledSourceNode: C,
  3114. AudioWorkletNode: C,
  3115. BarProp: C,
  3116. BaseAudioContext: C,
  3117. BatteryManager: C,
  3118. BeforeUnloadEvent: C,
  3119. BiquadFilterNode: C,
  3120. Blob: C,
  3121. BlobEvent: C,
  3122. blur: O,
  3123. BroadcastChannel: C,
  3124. btoa: O,
  3125. ByteLengthQueuingStrategy: C,
  3126. Cache: C,
  3127. caches: O,
  3128. CacheStorage: C,
  3129. cancelAnimationFrame: O,
  3130. cancelIdleCallback: O,
  3131. CanvasCaptureMediaStreamTrack: C,
  3132. CanvasGradient: C,
  3133. CanvasPattern: C,
  3134. CanvasRenderingContext2D: C,
  3135. ChannelMergerNode: C,
  3136. ChannelSplitterNode: C,
  3137. CharacterData: C,
  3138. clientInformation: O,
  3139. ClipboardEvent: C,
  3140. close: O,
  3141. closed: O,
  3142. CloseEvent: C,
  3143. Comment: C,
  3144. CompositionEvent: C,
  3145. confirm: O,
  3146. ConstantSourceNode: C,
  3147. ConvolverNode: C,
  3148. CountQueuingStrategy: C,
  3149. createImageBitmap: O,
  3150. Credential: C,
  3151. CredentialsContainer: C,
  3152. crypto: O,
  3153. Crypto: C,
  3154. CryptoKey: C,
  3155. CSS: C,
  3156. CSSConditionRule: C,
  3157. CSSFontFaceRule: C,
  3158. CSSGroupingRule: C,
  3159. CSSImportRule: C,
  3160. CSSKeyframeRule: C,
  3161. CSSKeyframesRule: C,
  3162. CSSMediaRule: C,
  3163. CSSNamespaceRule: C,
  3164. CSSPageRule: C,
  3165. CSSRule: C,
  3166. CSSRuleList: C,
  3167. CSSStyleDeclaration: C,
  3168. CSSStyleRule: C,
  3169. CSSStyleSheet: C,
  3170. CSSSupportsRule: C,
  3171. CustomElementRegistry: C,
  3172. customElements: O,
  3173. CustomEvent: C,
  3174. DataTransfer: C,
  3175. DataTransferItem: C,
  3176. DataTransferItemList: C,
  3177. defaultstatus: O,
  3178. defaultStatus: O,
  3179. DelayNode: C,
  3180. DeviceMotionEvent: C,
  3181. DeviceOrientationEvent: C,
  3182. devicePixelRatio: O,
  3183. dispatchEvent: O,
  3184. document: O,
  3185. Document: C,
  3186. DocumentFragment: C,
  3187. DocumentType: C,
  3188. DOMError: C,
  3189. DOMException: C,
  3190. DOMImplementation: C,
  3191. DOMMatrix: C,
  3192. DOMMatrixReadOnly: C,
  3193. DOMParser: C,
  3194. DOMPoint: C,
  3195. DOMPointReadOnly: C,
  3196. DOMQuad: C,
  3197. DOMRect: C,
  3198. DOMRectReadOnly: C,
  3199. DOMStringList: C,
  3200. DOMStringMap: C,
  3201. DOMTokenList: C,
  3202. DragEvent: C,
  3203. DynamicsCompressorNode: C,
  3204. Element: C,
  3205. ErrorEvent: C,
  3206. Event: C,
  3207. EventSource: C,
  3208. EventTarget: C,
  3209. external: O,
  3210. fetch: O,
  3211. File: C,
  3212. FileList: C,
  3213. FileReader: C,
  3214. find: O,
  3215. focus: O,
  3216. FocusEvent: C,
  3217. FontFace: C,
  3218. FontFaceSetLoadEvent: C,
  3219. FormData: C,
  3220. frames: O,
  3221. GainNode: C,
  3222. Gamepad: C,
  3223. GamepadButton: C,
  3224. GamepadEvent: C,
  3225. getComputedStyle: O,
  3226. getSelection: O,
  3227. HashChangeEvent: C,
  3228. Headers: C,
  3229. history: O,
  3230. History: C,
  3231. HTMLAllCollection: C,
  3232. HTMLAnchorElement: C,
  3233. HTMLAreaElement: C,
  3234. HTMLAudioElement: C,
  3235. HTMLBaseElement: C,
  3236. HTMLBodyElement: C,
  3237. HTMLBRElement: C,
  3238. HTMLButtonElement: C,
  3239. HTMLCanvasElement: C,
  3240. HTMLCollection: C,
  3241. HTMLContentElement: C,
  3242. HTMLDataElement: C,
  3243. HTMLDataListElement: C,
  3244. HTMLDetailsElement: C,
  3245. HTMLDialogElement: C,
  3246. HTMLDirectoryElement: C,
  3247. HTMLDivElement: C,
  3248. HTMLDListElement: C,
  3249. HTMLDocument: C,
  3250. HTMLElement: C,
  3251. HTMLEmbedElement: C,
  3252. HTMLFieldSetElement: C,
  3253. HTMLFontElement: C,
  3254. HTMLFormControlsCollection: C,
  3255. HTMLFormElement: C,
  3256. HTMLFrameElement: C,
  3257. HTMLFrameSetElement: C,
  3258. HTMLHeadElement: C,
  3259. HTMLHeadingElement: C,
  3260. HTMLHRElement: C,
  3261. HTMLHtmlElement: C,
  3262. HTMLIFrameElement: C,
  3263. HTMLImageElement: C,
  3264. HTMLInputElement: C,
  3265. HTMLLabelElement: C,
  3266. HTMLLegendElement: C,
  3267. HTMLLIElement: C,
  3268. HTMLLinkElement: C,
  3269. HTMLMapElement: C,
  3270. HTMLMarqueeElement: C,
  3271. HTMLMediaElement: C,
  3272. HTMLMenuElement: C,
  3273. HTMLMetaElement: C,
  3274. HTMLMeterElement: C,
  3275. HTMLModElement: C,
  3276. HTMLObjectElement: C,
  3277. HTMLOListElement: C,
  3278. HTMLOptGroupElement: C,
  3279. HTMLOptionElement: C,
  3280. HTMLOptionsCollection: C,
  3281. HTMLOutputElement: C,
  3282. HTMLParagraphElement: C,
  3283. HTMLParamElement: C,
  3284. HTMLPictureElement: C,
  3285. HTMLPreElement: C,
  3286. HTMLProgressElement: C,
  3287. HTMLQuoteElement: C,
  3288. HTMLScriptElement: C,
  3289. HTMLSelectElement: C,
  3290. HTMLShadowElement: C,
  3291. HTMLSlotElement: C,
  3292. HTMLSourceElement: C,
  3293. HTMLSpanElement: C,
  3294. HTMLStyleElement: C,
  3295. HTMLTableCaptionElement: C,
  3296. HTMLTableCellElement: C,
  3297. HTMLTableColElement: C,
  3298. HTMLTableElement: C,
  3299. HTMLTableRowElement: C,
  3300. HTMLTableSectionElement: C,
  3301. HTMLTemplateElement: C,
  3302. HTMLTextAreaElement: C,
  3303. HTMLTimeElement: C,
  3304. HTMLTitleElement: C,
  3305. HTMLTrackElement: C,
  3306. HTMLUListElement: C,
  3307. HTMLUnknownElement: C,
  3308. HTMLVideoElement: C,
  3309. IDBCursor: C,
  3310. IDBCursorWithValue: C,
  3311. IDBDatabase: C,
  3312. IDBFactory: C,
  3313. IDBIndex: C,
  3314. IDBKeyRange: C,
  3315. IDBObjectStore: C,
  3316. IDBOpenDBRequest: C,
  3317. IDBRequest: C,
  3318. IDBTransaction: C,
  3319. IDBVersionChangeEvent: C,
  3320. IdleDeadline: C,
  3321. IIRFilterNode: C,
  3322. Image: C,
  3323. ImageBitmap: C,
  3324. ImageBitmapRenderingContext: C,
  3325. ImageCapture: C,
  3326. ImageData: C,
  3327. indexedDB: O,
  3328. innerHeight: O,
  3329. innerWidth: O,
  3330. InputEvent: C,
  3331. IntersectionObserver: C,
  3332. IntersectionObserverEntry: C,
  3333. isSecureContext: O,
  3334. KeyboardEvent: C,
  3335. KeyframeEffect: C,
  3336. length: O,
  3337. localStorage: O,
  3338. location: O,
  3339. Location: C,
  3340. locationbar: O,
  3341. matchMedia: O,
  3342. MediaDeviceInfo: C,
  3343. MediaDevices: C,
  3344. MediaElementAudioSourceNode: C,
  3345. MediaEncryptedEvent: C,
  3346. MediaError: C,
  3347. MediaKeyMessageEvent: C,
  3348. MediaKeySession: C,
  3349. MediaKeyStatusMap: C,
  3350. MediaKeySystemAccess: C,
  3351. MediaList: C,
  3352. MediaQueryList: C,
  3353. MediaQueryListEvent: C,
  3354. MediaRecorder: C,
  3355. MediaSettingsRange: C,
  3356. MediaSource: C,
  3357. MediaStream: C,
  3358. MediaStreamAudioDestinationNode: C,
  3359. MediaStreamAudioSourceNode: C,
  3360. MediaStreamEvent: C,
  3361. MediaStreamTrack: C,
  3362. MediaStreamTrackEvent: C,
  3363. menubar: O,
  3364. MessageChannel: C,
  3365. MessageEvent: C,
  3366. MessagePort: C,
  3367. MIDIAccess: C,
  3368. MIDIConnectionEvent: C,
  3369. MIDIInput: C,
  3370. MIDIInputMap: C,
  3371. MIDIMessageEvent: C,
  3372. MIDIOutput: C,
  3373. MIDIOutputMap: C,
  3374. MIDIPort: C,
  3375. MimeType: C,
  3376. MimeTypeArray: C,
  3377. MouseEvent: C,
  3378. moveBy: O,
  3379. moveTo: O,
  3380. MutationEvent: C,
  3381. MutationObserver: C,
  3382. MutationRecord: C,
  3383. name: O,
  3384. NamedNodeMap: C,
  3385. NavigationPreloadManager: C,
  3386. navigator: O,
  3387. Navigator: C,
  3388. NetworkInformation: C,
  3389. Node: C,
  3390. NodeFilter: O,
  3391. NodeIterator: C,
  3392. NodeList: C,
  3393. Notification: C,
  3394. OfflineAudioCompletionEvent: C,
  3395. OfflineAudioContext: C,
  3396. offscreenBuffering: O,
  3397. OffscreenCanvas: C,
  3398. open: O,
  3399. openDatabase: O,
  3400. Option: C,
  3401. origin: O,
  3402. OscillatorNode: C,
  3403. outerHeight: O,
  3404. outerWidth: O,
  3405. PageTransitionEvent: C,
  3406. pageXOffset: O,
  3407. pageYOffset: O,
  3408. PannerNode: C,
  3409. parent: O,
  3410. Path2D: C,
  3411. PaymentAddress: C,
  3412. PaymentRequest: C,
  3413. PaymentRequestUpdateEvent: C,
  3414. PaymentResponse: C,
  3415. performance: O,
  3416. Performance: C,
  3417. PerformanceEntry: C,
  3418. PerformanceLongTaskTiming: C,
  3419. PerformanceMark: C,
  3420. PerformanceMeasure: C,
  3421. PerformanceNavigation: C,
  3422. PerformanceNavigationTiming: C,
  3423. PerformanceObserver: C,
  3424. PerformanceObserverEntryList: C,
  3425. PerformancePaintTiming: C,
  3426. PerformanceResourceTiming: C,
  3427. PerformanceTiming: C,
  3428. PeriodicWave: C,
  3429. Permissions: C,
  3430. PermissionStatus: C,
  3431. personalbar: O,
  3432. PhotoCapabilities: C,
  3433. Plugin: C,
  3434. PluginArray: C,
  3435. PointerEvent: C,
  3436. PopStateEvent: C,
  3437. postMessage: O,
  3438. Presentation: C,
  3439. PresentationAvailability: C,
  3440. PresentationConnection: C,
  3441. PresentationConnectionAvailableEvent: C,
  3442. PresentationConnectionCloseEvent: C,
  3443. PresentationConnectionList: C,
  3444. PresentationReceiver: C,
  3445. PresentationRequest: C,
  3446. print: O,
  3447. ProcessingInstruction: C,
  3448. ProgressEvent: C,
  3449. PromiseRejectionEvent: C,
  3450. prompt: O,
  3451. PushManager: C,
  3452. PushSubscription: C,
  3453. PushSubscriptionOptions: C,
  3454. queueMicrotask: O,
  3455. RadioNodeList: C,
  3456. Range: C,
  3457. ReadableStream: C,
  3458. RemotePlayback: C,
  3459. removeEventListener: O,
  3460. Request: C,
  3461. requestAnimationFrame: O,
  3462. requestIdleCallback: O,
  3463. resizeBy: O,
  3464. ResizeObserver: C,
  3465. ResizeObserverEntry: C,
  3466. resizeTo: O,
  3467. Response: C,
  3468. RTCCertificate: C,
  3469. RTCDataChannel: C,
  3470. RTCDataChannelEvent: C,
  3471. RTCDtlsTransport: C,
  3472. RTCIceCandidate: C,
  3473. RTCIceTransport: C,
  3474. RTCPeerConnection: C,
  3475. RTCPeerConnectionIceEvent: C,
  3476. RTCRtpReceiver: C,
  3477. RTCRtpSender: C,
  3478. RTCSctpTransport: C,
  3479. RTCSessionDescription: C,
  3480. RTCStatsReport: C,
  3481. RTCTrackEvent: C,
  3482. screen: O,
  3483. Screen: C,
  3484. screenLeft: O,
  3485. ScreenOrientation: C,
  3486. screenTop: O,
  3487. screenX: O,
  3488. screenY: O,
  3489. ScriptProcessorNode: C,
  3490. scroll: O,
  3491. scrollbars: O,
  3492. scrollBy: O,
  3493. scrollTo: O,
  3494. scrollX: O,
  3495. scrollY: O,
  3496. SecurityPolicyViolationEvent: C,
  3497. Selection: C,
  3498. ServiceWorker: C,
  3499. ServiceWorkerContainer: C,
  3500. ServiceWorkerRegistration: C,
  3501. sessionStorage: O,
  3502. ShadowRoot: C,
  3503. SharedWorker: C,
  3504. SourceBuffer: C,
  3505. SourceBufferList: C,
  3506. speechSynthesis: O,
  3507. SpeechSynthesisEvent: C,
  3508. SpeechSynthesisUtterance: C,
  3509. StaticRange: C,
  3510. status: O,
  3511. statusbar: O,
  3512. StereoPannerNode: C,
  3513. stop: O,
  3514. Storage: C,
  3515. StorageEvent: C,
  3516. StorageManager: C,
  3517. styleMedia: O,
  3518. StyleSheet: C,
  3519. StyleSheetList: C,
  3520. SubtleCrypto: C,
  3521. SVGAElement: C,
  3522. SVGAngle: C,
  3523. SVGAnimatedAngle: C,
  3524. SVGAnimatedBoolean: C,
  3525. SVGAnimatedEnumeration: C,
  3526. SVGAnimatedInteger: C,
  3527. SVGAnimatedLength: C,
  3528. SVGAnimatedLengthList: C,
  3529. SVGAnimatedNumber: C,
  3530. SVGAnimatedNumberList: C,
  3531. SVGAnimatedPreserveAspectRatio: C,
  3532. SVGAnimatedRect: C,
  3533. SVGAnimatedString: C,
  3534. SVGAnimatedTransformList: C,
  3535. SVGAnimateElement: C,
  3536. SVGAnimateMotionElement: C,
  3537. SVGAnimateTransformElement: C,
  3538. SVGAnimationElement: C,
  3539. SVGCircleElement: C,
  3540. SVGClipPathElement: C,
  3541. SVGComponentTransferFunctionElement: C,
  3542. SVGDefsElement: C,
  3543. SVGDescElement: C,
  3544. SVGDiscardElement: C,
  3545. SVGElement: C,
  3546. SVGEllipseElement: C,
  3547. SVGFEBlendElement: C,
  3548. SVGFEColorMatrixElement: C,
  3549. SVGFEComponentTransferElement: C,
  3550. SVGFECompositeElement: C,
  3551. SVGFEConvolveMatrixElement: C,
  3552. SVGFEDiffuseLightingElement: C,
  3553. SVGFEDisplacementMapElement: C,
  3554. SVGFEDistantLightElement: C,
  3555. SVGFEDropShadowElement: C,
  3556. SVGFEFloodElement: C,
  3557. SVGFEFuncAElement: C,
  3558. SVGFEFuncBElement: C,
  3559. SVGFEFuncGElement: C,
  3560. SVGFEFuncRElement: C,
  3561. SVGFEGaussianBlurElement: C,
  3562. SVGFEImageElement: C,
  3563. SVGFEMergeElement: C,
  3564. SVGFEMergeNodeElement: C,
  3565. SVGFEMorphologyElement: C,
  3566. SVGFEOffsetElement: C,
  3567. SVGFEPointLightElement: C,
  3568. SVGFESpecularLightingElement: C,
  3569. SVGFESpotLightElement: C,
  3570. SVGFETileElement: C,
  3571. SVGFETurbulenceElement: C,
  3572. SVGFilterElement: C,
  3573. SVGForeignObjectElement: C,
  3574. SVGGElement: C,
  3575. SVGGeometryElement: C,
  3576. SVGGradientElement: C,
  3577. SVGGraphicsElement: C,
  3578. SVGImageElement: C,
  3579. SVGLength: C,
  3580. SVGLengthList: C,
  3581. SVGLinearGradientElement: C,
  3582. SVGLineElement: C,
  3583. SVGMarkerElement: C,
  3584. SVGMaskElement: C,
  3585. SVGMatrix: C,
  3586. SVGMetadataElement: C,
  3587. SVGMPathElement: C,
  3588. SVGNumber: C,
  3589. SVGNumberList: C,
  3590. SVGPathElement: C,
  3591. SVGPatternElement: C,
  3592. SVGPoint: C,
  3593. SVGPointList: C,
  3594. SVGPolygonElement: C,
  3595. SVGPolylineElement: C,
  3596. SVGPreserveAspectRatio: C,
  3597. SVGRadialGradientElement: C,
  3598. SVGRect: C,
  3599. SVGRectElement: C,
  3600. SVGScriptElement: C,
  3601. SVGSetElement: C,
  3602. SVGStopElement: C,
  3603. SVGStringList: C,
  3604. SVGStyleElement: C,
  3605. SVGSVGElement: C,
  3606. SVGSwitchElement: C,
  3607. SVGSymbolElement: C,
  3608. SVGTextContentElement: C,
  3609. SVGTextElement: C,
  3610. SVGTextPathElement: C,
  3611. SVGTextPositioningElement: C,
  3612. SVGTitleElement: C,
  3613. SVGTransform: C,
  3614. SVGTransformList: C,
  3615. SVGTSpanElement: C,
  3616. SVGUnitTypes: C,
  3617. SVGUseElement: C,
  3618. SVGViewElement: C,
  3619. TaskAttributionTiming: C,
  3620. Text: C,
  3621. TextEvent: C,
  3622. TextMetrics: C,
  3623. TextTrack: C,
  3624. TextTrackCue: C,
  3625. TextTrackCueList: C,
  3626. TextTrackList: C,
  3627. TimeRanges: C,
  3628. toolbar: O,
  3629. top: O,
  3630. Touch: C,
  3631. TouchEvent: C,
  3632. TouchList: C,
  3633. TrackEvent: C,
  3634. TransitionEvent: C,
  3635. TreeWalker: C,
  3636. UIEvent: C,
  3637. ValidityState: C,
  3638. visualViewport: O,
  3639. VisualViewport: C,
  3640. VTTCue: C,
  3641. WaveShaperNode: C,
  3642. WebAssembly: O,
  3643. WebGL2RenderingContext: C,
  3644. WebGLActiveInfo: C,
  3645. WebGLBuffer: C,
  3646. WebGLContextEvent: C,
  3647. WebGLFramebuffer: C,
  3648. WebGLProgram: C,
  3649. WebGLQuery: C,
  3650. WebGLRenderbuffer: C,
  3651. WebGLRenderingContext: C,
  3652. WebGLSampler: C,
  3653. WebGLShader: C,
  3654. WebGLShaderPrecisionFormat: C,
  3655. WebGLSync: C,
  3656. WebGLTexture: C,
  3657. WebGLTransformFeedback: C,
  3658. WebGLUniformLocation: C,
  3659. WebGLVertexArrayObject: C,
  3660. WebSocket: C,
  3661. WheelEvent: C,
  3662. Window: C,
  3663. Worker: C,
  3664. WritableStream: C,
  3665. XMLDocument: C,
  3666. XMLHttpRequest: C,
  3667. XMLHttpRequestEventTarget: C,
  3668. XMLHttpRequestUpload: C,
  3669. XMLSerializer: C,
  3670. XPathEvaluator: C,
  3671. XPathExpression: C,
  3672. XPathResult: C,
  3673. XSLTProcessor: C
  3674. };
  3675. for (const global of ['window', 'global', 'self', 'globalThis']) {
  3676. knownGlobals[global] = knownGlobals;
  3677. }
  3678. function getGlobalAtPath(path) {
  3679. let currentGlobal = knownGlobals;
  3680. for (const pathSegment of path) {
  3681. if (typeof pathSegment !== 'string') {
  3682. return null;
  3683. }
  3684. currentGlobal = currentGlobal[pathSegment];
  3685. if (!currentGlobal) {
  3686. return null;
  3687. }
  3688. }
  3689. return currentGlobal[ValueProperties];
  3690. }
  3691. function isPureGlobal(path) {
  3692. const globalAtPath = getGlobalAtPath(path);
  3693. return globalAtPath !== null && globalAtPath.pure;
  3694. }
  3695. function isGlobalMember(path) {
  3696. if (path.length === 1) {
  3697. return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
  3698. }
  3699. return getGlobalAtPath(path.slice(0, -1)) !== null;
  3700. }
  3701. class GlobalVariable extends Variable {
  3702. constructor() {
  3703. super(...arguments);
  3704. this.isReassigned = true;
  3705. }
  3706. hasEffectsWhenAccessedAtPath(path) {
  3707. return !isGlobalMember([this.name, ...path]);
  3708. }
  3709. hasEffectsWhenCalledAtPath(path) {
  3710. return !isPureGlobal([this.name, ...path]);
  3711. }
  3712. }
  3713. class Identifier$1 extends NodeBase {
  3714. constructor() {
  3715. super(...arguments);
  3716. this.variable = null;
  3717. this.bound = false;
  3718. }
  3719. addExportedVariables(variables, exportNamesByVariable) {
  3720. if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
  3721. variables.push(this.variable);
  3722. }
  3723. }
  3724. bind() {
  3725. if (this.bound)
  3726. return;
  3727. this.bound = true;
  3728. if (this.variable === null && isReference(this, this.parent)) {
  3729. this.variable = this.scope.findVariable(this.name);
  3730. this.variable.addReference(this);
  3731. }
  3732. if (this.variable !== null &&
  3733. this.variable instanceof LocalVariable &&
  3734. this.variable.additionalInitializers !== null) {
  3735. this.variable.consolidateInitializers();
  3736. }
  3737. }
  3738. declare(kind, init) {
  3739. let variable;
  3740. switch (kind) {
  3741. case 'var':
  3742. variable = this.scope.addDeclaration(this, this.context, init, true);
  3743. break;
  3744. case 'function':
  3745. // in strict mode, functions are only hoisted within a scope but not across block scopes
  3746. variable = this.scope.addDeclaration(this, this.context, init, false);
  3747. break;
  3748. case 'let':
  3749. case 'const':
  3750. case 'class':
  3751. variable = this.scope.addDeclaration(this, this.context, init, false);
  3752. break;
  3753. case 'parameter':
  3754. variable = this.scope.addParameterDeclaration(this);
  3755. break;
  3756. /* istanbul ignore next */
  3757. default:
  3758. /* istanbul ignore next */
  3759. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  3760. }
  3761. return [(this.variable = variable)];
  3762. }
  3763. deoptimizePath(path) {
  3764. if (!this.bound)
  3765. this.bind();
  3766. if (path.length === 0 && !this.scope.contains(this.name)) {
  3767. this.disallowImportReassignment();
  3768. }
  3769. this.variable.deoptimizePath(path);
  3770. }
  3771. getLiteralValueAtPath(path, recursionTracker, origin) {
  3772. if (!this.bound)
  3773. this.bind();
  3774. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  3775. }
  3776. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  3777. if (!this.bound)
  3778. this.bind();
  3779. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  3780. }
  3781. hasEffects() {
  3782. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  3783. this.variable instanceof GlobalVariable &&
  3784. this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
  3785. }
  3786. hasEffectsWhenAccessedAtPath(path, context) {
  3787. return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  3788. }
  3789. hasEffectsWhenAssignedAtPath(path, context) {
  3790. return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
  3791. }
  3792. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3793. return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  3794. }
  3795. include() {
  3796. if (!this.included) {
  3797. this.included = true;
  3798. if (this.variable !== null) {
  3799. this.context.includeVariable(this.variable);
  3800. }
  3801. }
  3802. }
  3803. includeCallArguments(context, args) {
  3804. this.variable.includeCallArguments(context, args);
  3805. }
  3806. render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  3807. if (this.variable) {
  3808. const name = this.variable.getName();
  3809. if (name !== this.name) {
  3810. code.overwrite(this.start, this.end, name, {
  3811. contentOnly: true,
  3812. storeName: true
  3813. });
  3814. if (isShorthandProperty) {
  3815. code.prependRight(this.start, `${this.name}: `);
  3816. }
  3817. }
  3818. // In strict mode, any variable named "eval" must be the actual "eval" function
  3819. if (name === 'eval' &&
  3820. renderedParentType === CallExpression &&
  3821. isCalleeOfRenderedParent) {
  3822. code.appendRight(this.start, '0, ');
  3823. }
  3824. }
  3825. }
  3826. disallowImportReassignment() {
  3827. return this.context.error({
  3828. code: 'ILLEGAL_REASSIGNMENT',
  3829. message: `Illegal reassignment to import '${this.name}'`
  3830. }, this.start);
  3831. }
  3832. }
  3833. class RestElement extends NodeBase {
  3834. constructor() {
  3835. super(...arguments);
  3836. this.declarationInit = null;
  3837. }
  3838. addExportedVariables(variables, exportNamesByVariable) {
  3839. this.argument.addExportedVariables(variables, exportNamesByVariable);
  3840. }
  3841. bind() {
  3842. super.bind();
  3843. if (this.declarationInit !== null) {
  3844. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  3845. }
  3846. }
  3847. declare(kind, init) {
  3848. this.declarationInit = init;
  3849. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  3850. }
  3851. deoptimizePath(path) {
  3852. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  3853. }
  3854. hasEffectsWhenAssignedAtPath(path, context) {
  3855. return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  3856. }
  3857. }
  3858. class FunctionNode extends NodeBase {
  3859. constructor() {
  3860. super(...arguments);
  3861. this.isPrototypeDeoptimized = false;
  3862. }
  3863. createScope(parentScope) {
  3864. this.scope = new FunctionScope(parentScope, this.context);
  3865. }
  3866. deoptimizePath(path) {
  3867. if (path.length === 1) {
  3868. if (path[0] === 'prototype') {
  3869. this.isPrototypeDeoptimized = true;
  3870. }
  3871. else if (path[0] === UnknownKey) {
  3872. this.isPrototypeDeoptimized = true;
  3873. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  3874. // which means the return expression needs to be reassigned as well
  3875. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  3876. }
  3877. }
  3878. }
  3879. getReturnExpressionWhenCalledAtPath(path) {
  3880. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  3881. }
  3882. hasEffects() {
  3883. return this.id !== null && this.id.hasEffects();
  3884. }
  3885. hasEffectsWhenAccessedAtPath(path) {
  3886. if (path.length <= 1)
  3887. return false;
  3888. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  3889. }
  3890. hasEffectsWhenAssignedAtPath(path) {
  3891. if (path.length <= 1) {
  3892. return false;
  3893. }
  3894. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  3895. }
  3896. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3897. if (path.length > 0)
  3898. return true;
  3899. for (const param of this.params) {
  3900. if (param.hasEffects(context))
  3901. return true;
  3902. }
  3903. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  3904. context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
  3905. const { brokenFlow, ignore } = context;
  3906. context.ignore = {
  3907. breaks: false,
  3908. continues: false,
  3909. labels: new Set(),
  3910. returnAwaitYield: true
  3911. };
  3912. if (this.body.hasEffects(context))
  3913. return true;
  3914. context.brokenFlow = brokenFlow;
  3915. if (thisInit) {
  3916. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  3917. }
  3918. else {
  3919. context.replacedVariableInits.delete(this.scope.thisVariable);
  3920. }
  3921. context.ignore = ignore;
  3922. return false;
  3923. }
  3924. include(context, includeChildrenRecursively) {
  3925. this.included = true;
  3926. if (this.id)
  3927. this.id.include();
  3928. const hasArguments = this.scope.argumentsVariable.included;
  3929. for (const param of this.params) {
  3930. if (!(param instanceof Identifier$1) || hasArguments) {
  3931. param.include(context, includeChildrenRecursively);
  3932. }
  3933. }
  3934. const { brokenFlow } = context;
  3935. context.brokenFlow = BROKEN_FLOW_NONE;
  3936. this.body.include(context, includeChildrenRecursively);
  3937. context.brokenFlow = brokenFlow;
  3938. }
  3939. includeCallArguments(context, args) {
  3940. this.scope.includeCallArguments(context, args);
  3941. }
  3942. initialise() {
  3943. if (this.id !== null) {
  3944. this.id.declare('function', this);
  3945. }
  3946. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  3947. this.body.addImplicitReturnExpressionToScope();
  3948. }
  3949. parseNode(esTreeNode) {
  3950. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  3951. super.parseNode(esTreeNode);
  3952. }
  3953. }
  3954. FunctionNode.prototype.preventChildBlockScope = true;
  3955. class FunctionDeclaration extends FunctionNode {
  3956. initialise() {
  3957. super.initialise();
  3958. if (this.id !== null) {
  3959. this.id.variable.isId = true;
  3960. }
  3961. }
  3962. parseNode(esTreeNode) {
  3963. if (esTreeNode.id !== null) {
  3964. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
  3965. .parent);
  3966. }
  3967. super.parseNode(esTreeNode);
  3968. }
  3969. }
  3970. // The header ends at the first non-white-space after "default"
  3971. function getDeclarationStart(code, start) {
  3972. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  3973. }
  3974. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  3975. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  3976. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  3977. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  3978. if (generatorStarPos === -1) {
  3979. return declarationEnd;
  3980. }
  3981. return declarationEnd + generatorStarPos + 1;
  3982. }
  3983. class ExportDefaultDeclaration extends NodeBase {
  3984. include(context, includeChildrenRecursively) {
  3985. super.include(context, includeChildrenRecursively);
  3986. if (includeChildrenRecursively) {
  3987. this.context.includeVariable(this.variable);
  3988. }
  3989. }
  3990. initialise() {
  3991. const declaration = this.declaration;
  3992. this.declarationName =
  3993. (declaration.id && declaration.id.name) || this.declaration.name;
  3994. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  3995. this.context.addExport(this);
  3996. }
  3997. render(code, options, nodeRenderOptions) {
  3998. const { start, end } = nodeRenderOptions;
  3999. const declarationStart = getDeclarationStart(code.original, this.start);
  4000. if (this.declaration instanceof FunctionDeclaration) {
  4001. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  4002. }
  4003. else if (this.declaration instanceof ClassDeclaration) {
  4004. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  4005. }
  4006. else if (this.variable.getOriginalVariable() !== this.variable) {
  4007. // Remove altogether to prevent re-declaring the same variable
  4008. treeshakeNode(this, code, start, end);
  4009. return;
  4010. }
  4011. else if (this.variable.included) {
  4012. this.renderVariableDeclaration(code, declarationStart, options);
  4013. }
  4014. else {
  4015. code.remove(this.start, declarationStart);
  4016. this.declaration.render(code, options, {
  4017. isCalleeOfRenderedParent: false,
  4018. renderedParentType: ExpressionStatement
  4019. });
  4020. if (code.original[this.end - 1] !== ';') {
  4021. code.appendLeft(this.end, ';');
  4022. }
  4023. return;
  4024. }
  4025. this.declaration.render(code, options);
  4026. }
  4027. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  4028. const name = this.variable.getName();
  4029. // Remove `export default`
  4030. code.remove(this.start, declarationStart);
  4031. if (needsId) {
  4032. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  4033. }
  4034. if (options.format === 'system' &&
  4035. this.declaration instanceof ClassDeclaration &&
  4036. options.exportNamesByVariable.has(this.variable)) {
  4037. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  4038. }
  4039. }
  4040. renderVariableDeclaration(code, declarationStart, options) {
  4041. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  4042. const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
  4043. if (systemExportNames) {
  4044. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
  4045. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  4046. }
  4047. else {
  4048. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
  4049. if (!hasTrailingSemicolon) {
  4050. code.appendLeft(this.end, ';');
  4051. }
  4052. }
  4053. }
  4054. }
  4055. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  4056. class UndefinedVariable extends Variable {
  4057. constructor() {
  4058. super('undefined');
  4059. }
  4060. getLiteralValueAtPath() {
  4061. return undefined;
  4062. }
  4063. }
  4064. class ExportDefaultVariable extends LocalVariable {
  4065. constructor(name, exportDefaultDeclaration, context) {
  4066. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  4067. this.hasId = false;
  4068. // Not initialised during construction
  4069. this.originalId = null;
  4070. this.originalVariableAndDeclarationModules = null;
  4071. const declaration = exportDefaultDeclaration.declaration;
  4072. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  4073. declaration.id) {
  4074. this.hasId = true;
  4075. this.originalId = declaration.id;
  4076. }
  4077. else if (declaration instanceof Identifier$1) {
  4078. this.originalId = declaration;
  4079. }
  4080. }
  4081. addReference(identifier) {
  4082. if (!this.hasId) {
  4083. this.name = identifier.name;
  4084. }
  4085. }
  4086. getAssignedVariableName() {
  4087. return (this.originalId && this.originalId.name) || null;
  4088. }
  4089. getBaseVariableName() {
  4090. const original = this.getOriginalVariable();
  4091. if (original === this) {
  4092. return super.getBaseVariableName();
  4093. }
  4094. else {
  4095. return original.getBaseVariableName();
  4096. }
  4097. }
  4098. getName() {
  4099. const original = this.getOriginalVariable();
  4100. if (original === this) {
  4101. return super.getName();
  4102. }
  4103. else {
  4104. return original.getName();
  4105. }
  4106. }
  4107. getOriginalVariable() {
  4108. return this.getOriginalVariableAndDeclarationModules().original;
  4109. }
  4110. getOriginalVariableAndDeclarationModules() {
  4111. if (this.originalVariableAndDeclarationModules === null) {
  4112. if (!this.originalId ||
  4113. (!this.hasId &&
  4114. (this.originalId.variable.isReassigned ||
  4115. this.originalId.variable instanceof UndefinedVariable))) {
  4116. this.originalVariableAndDeclarationModules = { modules: [], original: this };
  4117. }
  4118. else {
  4119. const assignedOriginal = this.originalId.variable;
  4120. if (assignedOriginal instanceof ExportDefaultVariable) {
  4121. const { modules, original } = assignedOriginal.getOriginalVariableAndDeclarationModules();
  4122. this.originalVariableAndDeclarationModules = {
  4123. modules: modules.concat(this.module),
  4124. original
  4125. };
  4126. }
  4127. else {
  4128. this.originalVariableAndDeclarationModules = {
  4129. modules: [this.module],
  4130. original: assignedOriginal
  4131. };
  4132. }
  4133. }
  4134. }
  4135. return this.originalVariableAndDeclarationModules;
  4136. }
  4137. }
  4138. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  4139. class ExportShimVariable extends Variable {
  4140. constructor(module) {
  4141. super(MISSING_EXPORT_SHIM_VARIABLE);
  4142. this.module = module;
  4143. }
  4144. }
  4145. class NamespaceVariable extends Variable {
  4146. constructor(context, syntheticNamedExports) {
  4147. super(context.getModuleName());
  4148. this.memberVariables = null;
  4149. this.mergedNamespaces = [];
  4150. this.referencedEarly = false;
  4151. this.references = [];
  4152. this.context = context;
  4153. this.module = context.module;
  4154. this.syntheticNamedExports = syntheticNamedExports;
  4155. }
  4156. addReference(identifier) {
  4157. this.references.push(identifier);
  4158. this.name = identifier.name;
  4159. }
  4160. // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
  4161. // build fails due to an illegal namespace reassignment or MemberExpression already forwards
  4162. // the reassignment to the right variable. This means we lost track of this variable and thus
  4163. // need to reassign all exports.
  4164. deoptimizePath() {
  4165. const memberVariables = this.getMemberVariables();
  4166. for (const key of Object.keys(memberVariables)) {
  4167. memberVariables[key].deoptimizePath(UNKNOWN_PATH);
  4168. }
  4169. }
  4170. getMemberVariables() {
  4171. if (this.memberVariables) {
  4172. return this.memberVariables;
  4173. }
  4174. const memberVariables = Object.create(null);
  4175. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  4176. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  4177. memberVariables[name] = this.context.traceExport(name);
  4178. }
  4179. }
  4180. return (this.memberVariables = memberVariables);
  4181. }
  4182. include() {
  4183. this.included = true;
  4184. this.context.includeAllExports();
  4185. }
  4186. prepareNamespace(mergedNamespaces) {
  4187. this.mergedNamespaces = mergedNamespaces;
  4188. const moduleExecIndex = this.context.getModuleExecIndex();
  4189. for (const identifier of this.references) {
  4190. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  4191. this.referencedEarly = true;
  4192. break;
  4193. }
  4194. }
  4195. }
  4196. renderBlock(options) {
  4197. const _ = options.compact ? '' : ' ';
  4198. const n = options.compact ? '' : '\n';
  4199. const t = options.indent;
  4200. const memberVariables = this.getMemberVariables();
  4201. const members = Object.keys(memberVariables).map(name => {
  4202. const original = memberVariables[name];
  4203. if (this.referencedEarly || original.isReassigned) {
  4204. return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
  4205. }
  4206. const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
  4207. return `${t}${safeName}: ${original.getName()}`;
  4208. });
  4209. if (options.namespaceToStringTag) {
  4210. members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
  4211. }
  4212. const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
  4213. if (!needsObjectAssign)
  4214. members.unshift(`${t}__proto__:${_}null`);
  4215. let output = `{${n}${members.join(`,${n}`)}${n}}`;
  4216. if (needsObjectAssign) {
  4217. const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
  4218. if (this.mergedNamespaces.length > 0) {
  4219. assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
  4220. }
  4221. if (this.syntheticNamedExports) {
  4222. assignmentArgs.push(this.module.getSyntheticNamespace().getName());
  4223. }
  4224. if (members.length > 0) {
  4225. assignmentArgs.push(output);
  4226. }
  4227. output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
  4228. }
  4229. if (options.freeze) {
  4230. output = `/*#__PURE__*/Object.freeze(${output})`;
  4231. }
  4232. const name = this.getName();
  4233. output = `${options.varOrConst} ${name}${_}=${_}${output};`;
  4234. if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
  4235. output += `${n}${getSystemExportStatement([this], options)};`;
  4236. }
  4237. return output;
  4238. }
  4239. renderFirst() {
  4240. return this.referencedEarly;
  4241. }
  4242. }
  4243. NamespaceVariable.prototype.isNamespace = true;
  4244. class SyntheticNamedExportVariable extends Variable {
  4245. constructor(context, name, syntheticNamespace) {
  4246. super(name);
  4247. this.context = context;
  4248. this.module = context.module;
  4249. this.syntheticNamespace = syntheticNamespace;
  4250. }
  4251. getBaseVariable() {
  4252. let baseVariable = this.syntheticNamespace;
  4253. if (baseVariable instanceof ExportDefaultVariable) {
  4254. baseVariable = baseVariable.getOriginalVariable();
  4255. }
  4256. if (baseVariable instanceof SyntheticNamedExportVariable) {
  4257. baseVariable = baseVariable.getBaseVariable();
  4258. }
  4259. return baseVariable;
  4260. }
  4261. getBaseVariableName() {
  4262. return this.syntheticNamespace.getBaseVariableName();
  4263. }
  4264. getName() {
  4265. const name = this.name;
  4266. return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
  4267. }
  4268. include() {
  4269. if (!this.included) {
  4270. this.included = true;
  4271. this.context.includeVariable(this.syntheticNamespace);
  4272. }
  4273. }
  4274. setRenderNames(baseName, name) {
  4275. super.setRenderNames(baseName, name);
  4276. }
  4277. }
  4278. const getPropertyAccess = (name) => {
  4279. return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
  4280. ? `.${name}`
  4281. : `[${JSON.stringify(name)}]`;
  4282. };
  4283. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  4284. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  4285. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  4286. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  4287. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  4288. const defaultInteropHelpersByInteropType = {
  4289. auto: INTEROP_DEFAULT_VARIABLE,
  4290. default: null,
  4291. defaultOnly: null,
  4292. esModule: null,
  4293. false: null,
  4294. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  4295. };
  4296. function isDefaultAProperty(interopType, externalLiveBindings) {
  4297. return (interopType === 'esModule' ||
  4298. (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
  4299. }
  4300. const namespaceInteropHelpersByInteropType = {
  4301. auto: INTEROP_NAMESPACE_VARIABLE,
  4302. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  4303. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  4304. esModule: null,
  4305. false: null,
  4306. true: INTEROP_NAMESPACE_VARIABLE
  4307. };
  4308. function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
  4309. return (isDefaultAProperty(interopType, externalLiveBindings) &&
  4310. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
  4311. }
  4312. function getDefaultOnlyHelper() {
  4313. return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
  4314. }
  4315. function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
  4316. return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
  4317. ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  4318. : '').join('');
  4319. }
  4320. const HELPER_GENERATORS = {
  4321. [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
  4322. `e${_}&&${_}e.__esModule${_}?${_}` +
  4323. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  4324. [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
  4325. `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  4326. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  4327. [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  4328. (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
  4329. ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
  4330. : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  4331. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
  4332. `}${n}${n}`,
  4333. [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  4334. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
  4335. `}${n}${n}`,
  4336. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
  4337. `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
  4338. `}${n}${n}`
  4339. };
  4340. function getDefaultLiveBinding(_) {
  4341. return `e${_}:${_}{${_}'default':${_}e${_}}`;
  4342. }
  4343. function getDefaultStatic(_) {
  4344. return `e['default']${_}:${_}e`;
  4345. }
  4346. function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
  4347. return (`${i}var n${_}=${_}${namespaceToStringTag
  4348. ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
  4349. : 'Object.create(null)'};${n}` +
  4350. `${i}if${_}(e)${_}{${n}` +
  4351. `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
  4352. (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
  4353. `${i}${t}});${n}` +
  4354. `${i}}${n}` +
  4355. `${i}n['default']${_}=${_}e;${n}` +
  4356. `${i}return ${getFrozen('n', freeze)};${n}`);
  4357. }
  4358. function copyPropertyLiveBinding(_, n, t, i) {
  4359. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  4360. `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  4361. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  4362. `${i}${t}${t}enumerable:${_}true,${n}` +
  4363. `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
  4364. `${i}${t}${t}${t}return e[k];${n}` +
  4365. `${i}${t}${t}}${n}` +
  4366. `${i}${t}});${n}` +
  4367. `${i}}${n}`);
  4368. }
  4369. function copyPropertyStatic(_, n, _t, i) {
  4370. return `${i}n[k]${_}=${_}e[k];${n}`;
  4371. }
  4372. function getFrozen(fragment, freeze) {
  4373. return freeze ? `Object.freeze(${fragment})` : fragment;
  4374. }
  4375. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  4376. function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
  4377. const _ = compact ? '' : ' ';
  4378. const n = compact ? '' : '\n';
  4379. if (!namedExportsMode) {
  4380. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
  4381. }
  4382. let exportBlock = '';
  4383. // star exports must always output first for precedence
  4384. for (const { name, reexports } of dependencies) {
  4385. if (reexports && namedExportsMode) {
  4386. for (const specifier of reexports) {
  4387. if (specifier.reexported === '*') {
  4388. if (exportBlock)
  4389. exportBlock += n;
  4390. if (specifier.needsLiveBinding) {
  4391. exportBlock +=
  4392. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4393. `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
  4394. `${t}${t}enumerable:${_}true,${n}` +
  4395. `${t}${t}get:${_}function${_}()${_}{${n}` +
  4396. `${t}${t}${t}return ${name}[k];${n}` +
  4397. `${t}${t}}${n}${t}});${n}});`;
  4398. }
  4399. else {
  4400. exportBlock +=
  4401. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4402. `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
  4403. }
  4404. }
  4405. }
  4406. }
  4407. }
  4408. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4409. if (reexports && namedExportsMode) {
  4410. for (const specifier of reexports) {
  4411. if (specifier.reexported !== '*') {
  4412. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  4413. if (exportBlock)
  4414. exportBlock += n;
  4415. exportBlock +=
  4416. specifier.imported !== '*' && specifier.needsLiveBinding
  4417. ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  4418. `${t}enumerable:${_}true,${n}` +
  4419. `${t}get:${_}function${_}()${_}{${n}` +
  4420. `${t}${t}return ${importName};${n}${t}}${n}});`
  4421. : `exports.${specifier.reexported}${_}=${_}${importName};`;
  4422. }
  4423. }
  4424. }
  4425. }
  4426. for (const chunkExport of exports) {
  4427. const lhs = `exports.${chunkExport.exported}`;
  4428. const rhs = chunkExport.local;
  4429. if (lhs !== rhs) {
  4430. if (exportBlock)
  4431. exportBlock += n;
  4432. exportBlock += `${lhs}${_}=${_}${rhs};`;
  4433. }
  4434. }
  4435. if (exportBlock) {
  4436. return `${n}${n}${exportBlock}`;
  4437. }
  4438. return '';
  4439. }
  4440. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
  4441. if (exports.length > 0) {
  4442. return exports[0].local;
  4443. }
  4444. else {
  4445. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4446. if (reexports) {
  4447. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  4448. }
  4449. }
  4450. }
  4451. }
  4452. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
  4453. if (imported === 'default') {
  4454. if (!isChunk) {
  4455. const moduleInterop = String(interop(moduleId));
  4456. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  4457. ? defaultVariableName
  4458. : moduleVariableName;
  4459. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  4460. ? `${variableName}['default']`
  4461. : variableName;
  4462. }
  4463. return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
  4464. }
  4465. if (imported === '*') {
  4466. return (isChunk
  4467. ? !depNamedExportsMode
  4468. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  4469. ? namespaceVariableName
  4470. : moduleVariableName;
  4471. }
  4472. return `${moduleVariableName}.${imported}`;
  4473. }
  4474. function getEsModuleExport(_) {
  4475. return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
  4476. }
  4477. function getNamespaceToStringExport(_) {
  4478. return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
  4479. }
  4480. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
  4481. let namespaceMarkers = '';
  4482. if (hasNamedExports) {
  4483. if (addEsModule) {
  4484. namespaceMarkers += getEsModuleExport(_);
  4485. }
  4486. if (addNamespaceToStringTag) {
  4487. if (namespaceMarkers) {
  4488. namespaceMarkers += n;
  4489. }
  4490. namespaceMarkers += getNamespaceToStringExport(_);
  4491. }
  4492. }
  4493. return namespaceMarkers;
  4494. }
  4495. function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
  4496. const neededInteropHelpers = new Set();
  4497. const interopStatements = [];
  4498. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  4499. neededInteropHelpers.add(helper);
  4500. interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  4501. };
  4502. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4503. if (isChunk) {
  4504. for (const { imported, reexported } of [
  4505. ...(imports || []),
  4506. ...(reexports || [])
  4507. ]) {
  4508. if (imported === '*' && reexported !== '*') {
  4509. if (!namedExportsMode) {
  4510. addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
  4511. }
  4512. break;
  4513. }
  4514. }
  4515. }
  4516. else {
  4517. const moduleInterop = String(interop(id));
  4518. let hasDefault = false;
  4519. let hasNamespace = false;
  4520. for (const { imported, reexported } of [
  4521. ...(imports || []),
  4522. ...(reexports || [])
  4523. ]) {
  4524. let helper;
  4525. let variableName;
  4526. if (imported === 'default') {
  4527. if (!hasDefault) {
  4528. hasDefault = true;
  4529. if (defaultVariableName !== namespaceVariableName) {
  4530. variableName = defaultVariableName;
  4531. helper = defaultInteropHelpersByInteropType[moduleInterop];
  4532. }
  4533. }
  4534. }
  4535. else if (imported === '*' && reexported !== '*') {
  4536. if (!hasNamespace) {
  4537. hasNamespace = true;
  4538. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  4539. variableName = namespaceVariableName;
  4540. }
  4541. }
  4542. if (helper) {
  4543. addInteropStatement(variableName, helper, name);
  4544. }
  4545. }
  4546. }
  4547. }
  4548. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  4549. }
  4550. const builtins$1 = {
  4551. assert: true,
  4552. buffer: true,
  4553. console: true,
  4554. constants: true,
  4555. domain: true,
  4556. events: true,
  4557. http: true,
  4558. https: true,
  4559. os: true,
  4560. path: true,
  4561. process: true,
  4562. punycode: true,
  4563. querystring: true,
  4564. stream: true,
  4565. string_decoder: true,
  4566. timers: true,
  4567. tty: true,
  4568. url: true,
  4569. util: true,
  4570. vm: true,
  4571. zlib: true
  4572. };
  4573. function warnOnBuiltins(warn, dependencies) {
  4574. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
  4575. if (!externalBuiltins.length)
  4576. return;
  4577. const detail = externalBuiltins.length === 1
  4578. ? `module ('${externalBuiltins[0]}')`
  4579. : `modules (${externalBuiltins
  4580. .slice(0, -1)
  4581. .map(name => `'${name}'`)
  4582. .join(', ')} and '${externalBuiltins.slice(-1)}')`;
  4583. warn({
  4584. code: 'MISSING_NODE_BUILTINS',
  4585. message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills`,
  4586. modules: externalBuiltins
  4587. });
  4588. }
  4589. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  4590. // The assumption is that this makes sense for all relative ids:
  4591. // https://requirejs.org/docs/api.html#jsfiles
  4592. function removeExtensionFromRelativeAmdId(id) {
  4593. if (id[0] === '.' && id.endsWith('.js')) {
  4594. return id.slice(0, -3);
  4595. }
  4596. return id;
  4597. }
  4598. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  4599. warnOnBuiltins(warn, dependencies);
  4600. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  4601. const args = dependencies.map(m => m.name);
  4602. const n = compact ? '' : '\n';
  4603. const s = compact ? '' : ';';
  4604. const _ = compact ? '' : ' ';
  4605. if (namedExportsMode && hasExports) {
  4606. args.unshift(`exports`);
  4607. deps.unshift(`'exports'`);
  4608. }
  4609. if (accessedGlobals.has('require')) {
  4610. args.unshift('require');
  4611. deps.unshift(`'require'`);
  4612. }
  4613. if (accessedGlobals.has('module')) {
  4614. args.unshift('module');
  4615. deps.unshift(`'module'`);
  4616. }
  4617. const params = (amdId ? `'${amdId}',${_}` : ``) + (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  4618. const useStrict = strict ? `${_}'use strict';` : '';
  4619. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  4620. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  4621. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  4622. if (namespaceMarkers) {
  4623. namespaceMarkers = n + n + namespaceMarkers;
  4624. }
  4625. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  4626. return magicString
  4627. .indent(t)
  4628. .prepend(`${amdDefine}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
  4629. .append(`${n}${n}});`);
  4630. }
  4631. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  4632. const n = compact ? '' : '\n';
  4633. const s = compact ? '' : ';';
  4634. const _ = compact ? '' : ' ';
  4635. const useStrict = strict ? `'use strict';${n}${n}` : '';
  4636. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  4637. if (namespaceMarkers) {
  4638. namespaceMarkers += n + n;
  4639. }
  4640. const importBlock = getImportBlock(dependencies, compact, varOrConst, n, _);
  4641. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  4642. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  4643. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
  4644. return magicString.append(`${exportBlock}${outro}`);
  4645. }
  4646. function getImportBlock(dependencies, compact, varOrConst, n, _) {
  4647. let importBlock = '';
  4648. let definingVariable = false;
  4649. for (const { id, name, reexports, imports } of dependencies) {
  4650. if (!reexports && !imports) {
  4651. if (importBlock) {
  4652. importBlock += !compact || definingVariable ? `;${n}` : ',';
  4653. }
  4654. definingVariable = false;
  4655. importBlock += `require('${id}')`;
  4656. }
  4657. else {
  4658. importBlock +=
  4659. compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
  4660. definingVariable = true;
  4661. importBlock += `${name}${_}=${_}require('${id}')`;
  4662. }
  4663. }
  4664. if (importBlock) {
  4665. return `${importBlock};${n}${n}`;
  4666. }
  4667. return '';
  4668. }
  4669. function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
  4670. const _ = compact ? '' : ' ';
  4671. const n = compact ? '' : '\n';
  4672. const importBlock = getImportBlock$1(dependencies, _);
  4673. if (importBlock.length > 0)
  4674. intro += importBlock.join(n) + n + n;
  4675. if (intro)
  4676. magicString.prepend(intro);
  4677. const exportBlock = getExportBlock$1(exports, _, varOrConst);
  4678. if (exportBlock.length)
  4679. magicString.append(n + n + exportBlock.join(n).trim());
  4680. if (outro)
  4681. magicString.append(outro);
  4682. return magicString.trim();
  4683. }
  4684. function getImportBlock$1(dependencies, _) {
  4685. const importBlock = [];
  4686. for (const { id, reexports, imports, name } of dependencies) {
  4687. if (!reexports && !imports) {
  4688. importBlock.push(`import${_}'${id}';`);
  4689. continue;
  4690. }
  4691. if (imports) {
  4692. let defaultImport = null;
  4693. let starImport = null;
  4694. const importedNames = [];
  4695. for (const specifier of imports) {
  4696. if (specifier.imported === 'default') {
  4697. defaultImport = specifier;
  4698. }
  4699. else if (specifier.imported === '*') {
  4700. starImport = specifier;
  4701. }
  4702. else {
  4703. importedNames.push(specifier);
  4704. }
  4705. }
  4706. if (starImport) {
  4707. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  4708. }
  4709. if (defaultImport && importedNames.length === 0) {
  4710. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  4711. }
  4712. else if (importedNames.length > 0) {
  4713. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  4714. .map(specifier => {
  4715. if (specifier.imported === specifier.local) {
  4716. return specifier.imported;
  4717. }
  4718. else {
  4719. return `${specifier.imported} as ${specifier.local}`;
  4720. }
  4721. })
  4722. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  4723. }
  4724. }
  4725. if (reexports) {
  4726. let starExport = null;
  4727. const namespaceReexports = [];
  4728. const namedReexports = [];
  4729. for (const specifier of reexports) {
  4730. if (specifier.reexported === '*') {
  4731. starExport = specifier;
  4732. }
  4733. else if (specifier.imported === '*') {
  4734. namespaceReexports.push(specifier);
  4735. }
  4736. else {
  4737. namedReexports.push(specifier);
  4738. }
  4739. }
  4740. if (starExport) {
  4741. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  4742. }
  4743. if (namespaceReexports.length > 0) {
  4744. if (!imports ||
  4745. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  4746. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  4747. }
  4748. for (const specifier of namespaceReexports) {
  4749. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  4750. }
  4751. }
  4752. if (namedReexports.length > 0) {
  4753. importBlock.push(`export${_}{${_}${namedReexports
  4754. .map(specifier => {
  4755. if (specifier.imported === specifier.reexported) {
  4756. return specifier.imported;
  4757. }
  4758. else {
  4759. return `${specifier.imported} as ${specifier.reexported}`;
  4760. }
  4761. })
  4762. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  4763. }
  4764. }
  4765. }
  4766. return importBlock;
  4767. }
  4768. function getExportBlock$1(exports, _, varOrConst) {
  4769. const exportBlock = [];
  4770. const exportDeclaration = [];
  4771. for (const specifier of exports) {
  4772. if (specifier.exported === 'default') {
  4773. exportBlock.push(`export default ${specifier.local};`);
  4774. }
  4775. else {
  4776. if (specifier.expression) {
  4777. exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
  4778. }
  4779. exportDeclaration.push(specifier.exported === specifier.local
  4780. ? specifier.local
  4781. : `${specifier.local} as ${specifier.exported}`);
  4782. }
  4783. }
  4784. if (exportDeclaration.length) {
  4785. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  4786. }
  4787. return exportBlock;
  4788. }
  4789. function spaces(i) {
  4790. let result = '';
  4791. while (i--)
  4792. result += ' ';
  4793. return result;
  4794. }
  4795. function tabsToSpaces(str) {
  4796. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  4797. }
  4798. function getCodeFrame(source, line, column) {
  4799. let lines = source.split('\n');
  4800. const frameStart = Math.max(0, line - 3);
  4801. let frameEnd = Math.min(line + 2, lines.length);
  4802. lines = lines.slice(frameStart, frameEnd);
  4803. while (!/\S/.test(lines[lines.length - 1])) {
  4804. lines.pop();
  4805. frameEnd -= 1;
  4806. }
  4807. const digits = String(frameEnd).length;
  4808. return lines
  4809. .map((str, i) => {
  4810. const isErrorLine = frameStart + i + 1 === line;
  4811. let lineNum = String(i + frameStart + 1);
  4812. while (lineNum.length < digits)
  4813. lineNum = ` ${lineNum}`;
  4814. if (isErrorLine) {
  4815. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  4816. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  4817. }
  4818. return `${lineNum}: ${tabsToSpaces(str)}`;
  4819. })
  4820. .join('\n');
  4821. }
  4822. function sanitizeFileName(name) {
  4823. return name.replace(/[\0?*]/g, '_');
  4824. }
  4825. function getAliasName(id) {
  4826. const base = basename(id);
  4827. return base.substr(0, base.length - extname(id).length);
  4828. }
  4829. function relativeId(id) {
  4830. if (typeof process === 'undefined' || !isAbsolute(id))
  4831. return id;
  4832. return relative$1(process.cwd(), id);
  4833. }
  4834. function isPlainPathFragment(name) {
  4835. // not starting with "/", "./", "../"
  4836. return (name[0] !== '/' &&
  4837. !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
  4838. sanitizeFileName(name) === name &&
  4839. !isAbsolute(name));
  4840. }
  4841. function error(base) {
  4842. if (!(base instanceof Error))
  4843. base = Object.assign(new Error(base.message), base);
  4844. throw base;
  4845. }
  4846. function augmentCodeLocation(props, pos, source, id) {
  4847. if (typeof pos === 'object') {
  4848. const { line, column } = pos;
  4849. props.loc = { file: id, line, column };
  4850. }
  4851. else {
  4852. props.pos = pos;
  4853. const { line, column } = locate(source, pos, { offsetLine: 1 });
  4854. props.loc = { file: id, line, column };
  4855. }
  4856. if (props.frame === undefined) {
  4857. const { line, column } = props.loc;
  4858. props.frame = getCodeFrame(source, line, column);
  4859. }
  4860. }
  4861. var Errors;
  4862. (function (Errors) {
  4863. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  4864. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  4865. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  4866. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  4867. Errors["BAD_LOADER"] = "BAD_LOADER";
  4868. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  4869. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  4870. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  4871. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  4872. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  4873. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  4874. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  4875. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  4876. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  4877. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  4878. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  4879. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  4880. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  4881. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  4882. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  4883. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  4884. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  4885. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  4886. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  4887. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  4888. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  4889. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  4890. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  4891. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  4892. })(Errors || (Errors = {}));
  4893. function errAssetNotFinalisedForFileName(name) {
  4894. return {
  4895. code: Errors.ASSET_NOT_FINALISED,
  4896. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  4897. };
  4898. }
  4899. function errCannotEmitFromOptionsHook() {
  4900. return {
  4901. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  4902. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  4903. };
  4904. }
  4905. function errChunkNotGeneratedForFileName(name) {
  4906. return {
  4907. code: Errors.CHUNK_NOT_GENERATED,
  4908. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  4909. };
  4910. }
  4911. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  4912. return {
  4913. code: Errors.ASSET_NOT_FOUND,
  4914. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  4915. };
  4916. }
  4917. function errAssetSourceAlreadySet(name) {
  4918. return {
  4919. code: Errors.ASSET_SOURCE_ALREADY_SET,
  4920. message: `Unable to set the source for asset "${name}", source already set.`
  4921. };
  4922. }
  4923. function errNoAssetSourceSet(assetName) {
  4924. return {
  4925. code: Errors.ASSET_SOURCE_MISSING,
  4926. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  4927. };
  4928. }
  4929. function errBadLoader(id) {
  4930. return {
  4931. code: Errors.BAD_LOADER,
  4932. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  4933. };
  4934. }
  4935. function errDeprecation(deprecation) {
  4936. return {
  4937. code: Errors.DEPRECATED_FEATURE,
  4938. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  4939. };
  4940. }
  4941. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  4942. return {
  4943. code: Errors.FILE_NOT_FOUND,
  4944. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  4945. };
  4946. }
  4947. function errFileNameConflict(fileName) {
  4948. return {
  4949. code: Errors.FILE_NAME_CONFLICT,
  4950. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  4951. };
  4952. }
  4953. function errInputHookInOutputPlugin(pluginName, hookName) {
  4954. return {
  4955. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  4956. 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.`
  4957. };
  4958. }
  4959. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  4960. return {
  4961. code: Errors.INVALID_CHUNK,
  4962. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  4963. };
  4964. }
  4965. function errInvalidExportOptionValue(optionValue) {
  4966. return {
  4967. code: Errors.INVALID_EXPORT_OPTION,
  4968. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  4969. url: `https://rollupjs.org/guide/en/#outputexports`
  4970. };
  4971. }
  4972. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  4973. return {
  4974. code: 'INVALID_EXPORT_OPTION',
  4975. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  4976. };
  4977. }
  4978. function errInternalIdCannotBeExternal(source, importer) {
  4979. return {
  4980. code: Errors.INVALID_EXTERNAL_ID,
  4981. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  4982. };
  4983. }
  4984. function errInvalidOption(option, explanation) {
  4985. return {
  4986. code: Errors.INVALID_OPTION,
  4987. message: `Invalid value for option "${option}" - ${explanation}.`
  4988. };
  4989. }
  4990. function errInvalidRollupPhaseForAddWatchFile() {
  4991. return {
  4992. code: Errors.INVALID_ROLLUP_PHASE,
  4993. message: `Cannot call addWatchFile after the build has finished.`
  4994. };
  4995. }
  4996. function errInvalidRollupPhaseForChunkEmission() {
  4997. return {
  4998. code: Errors.INVALID_ROLLUP_PHASE,
  4999. message: `Cannot emit chunks after module loading has finished.`
  5000. };
  5001. }
  5002. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  5003. return {
  5004. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5005. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  5006. };
  5007. }
  5008. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  5009. return {
  5010. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5011. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  5012. };
  5013. }
  5014. function errImplicitDependantIsNotIncluded(module) {
  5015. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  5016. return {
  5017. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5018. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before "${implicitDependencies.length === 1
  5019. ? implicitDependencies[0]
  5020. : `${implicitDependencies.slice(0, -1).join('", "')}" and "${implicitDependencies.slice(-1)[0]}`}" 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.`
  5021. };
  5022. }
  5023. function errMixedExport(facadeModuleId, name) {
  5024. return {
  5025. code: Errors.MIXED_EXPORTS,
  5026. id: facadeModuleId,
  5027. 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`,
  5028. url: `https://rollupjs.org/guide/en/#outputexports`
  5029. };
  5030. }
  5031. function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
  5032. return {
  5033. code: Errors.NAMESPACE_CONFLICT,
  5034. message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
  5035. name,
  5036. reexporter: reexportingModule.id,
  5037. sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
  5038. };
  5039. }
  5040. function errNoTransformMapOrAstWithoutCode(pluginName) {
  5041. return {
  5042. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  5043. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  5044. 'a "code". This will be ignored.'
  5045. };
  5046. }
  5047. function errPreferNamedExports(facadeModuleId) {
  5048. const file = relativeId(facadeModuleId);
  5049. return {
  5050. code: Errors.PREFER_NAMED_EXPORTS,
  5051. id: facadeModuleId,
  5052. 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.`,
  5053. url: `https://rollupjs.org/guide/en/#outputexports`
  5054. };
  5055. }
  5056. function errUnexpectedNamedImport(id, imported, isReexport) {
  5057. const importType = isReexport ? 'reexport' : 'import';
  5058. return {
  5059. code: Errors.UNEXPECTED_NAMED_IMPORT,
  5060. id,
  5061. 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.`,
  5062. url: 'https://rollupjs.org/guide/en/#outputinterop'
  5063. };
  5064. }
  5065. function errUnexpectedNamespaceReexport(id) {
  5066. return {
  5067. code: Errors.UNEXPECTED_NAMED_IMPORT,
  5068. id,
  5069. 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.`,
  5070. url: 'https://rollupjs.org/guide/en/#outputinterop'
  5071. };
  5072. }
  5073. function errEntryCannotBeExternal(unresolvedId) {
  5074. return {
  5075. code: Errors.UNRESOLVED_ENTRY,
  5076. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  5077. };
  5078. }
  5079. function errUnresolvedEntry(unresolvedId) {
  5080. return {
  5081. code: Errors.UNRESOLVED_ENTRY,
  5082. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  5083. };
  5084. }
  5085. function errUnresolvedImport(source, importer) {
  5086. return {
  5087. code: Errors.UNRESOLVED_IMPORT,
  5088. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  5089. };
  5090. }
  5091. function errUnresolvedImportTreatedAsExternal(source, importer) {
  5092. return {
  5093. code: Errors.UNRESOLVED_IMPORT,
  5094. importer: relativeId(importer),
  5095. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  5096. source,
  5097. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  5098. };
  5099. }
  5100. function errExternalSyntheticExports(source, importer) {
  5101. return {
  5102. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  5103. importer: relativeId(importer),
  5104. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  5105. source
  5106. };
  5107. }
  5108. function errFailedValidation(message) {
  5109. return {
  5110. code: Errors.VALIDATION_ERROR,
  5111. message
  5112. };
  5113. }
  5114. function warnDeprecation(deprecation, activeDeprecation, options) {
  5115. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  5116. }
  5117. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  5118. if (activeDeprecation || strictDeprecations) {
  5119. const warning = errDeprecation(deprecation);
  5120. if (strictDeprecations) {
  5121. return error(warning);
  5122. }
  5123. warn(warning);
  5124. }
  5125. }
  5126. // Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
  5127. // if the property name isn't trivial
  5128. const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
  5129. function property(prop) {
  5130. return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
  5131. }
  5132. function keypath(keypath) {
  5133. return keypath
  5134. .split('.')
  5135. .map(property)
  5136. .join('');
  5137. }
  5138. function setupNamespace(name, root, globals, compact) {
  5139. const _ = compact ? '' : ' ';
  5140. const parts = name.split('.');
  5141. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5142. parts.pop();
  5143. let acc = root;
  5144. return (parts
  5145. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
  5146. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  5147. }
  5148. function assignToDeepVariable(deepName, root, globals, compact, assignment) {
  5149. const _ = compact ? '' : ' ';
  5150. const parts = deepName.split('.');
  5151. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5152. const last = parts.pop();
  5153. let acc = root;
  5154. let deepAssignment = parts
  5155. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
  5156. .concat(`${acc}${property(last)}`)
  5157. .join(`,${_}`)
  5158. .concat(`${_}=${_}${assignment}`);
  5159. if (parts.length > 0) {
  5160. deepAssignment = `(${deepAssignment})`;
  5161. }
  5162. return deepAssignment;
  5163. }
  5164. function trimEmptyImports(dependencies) {
  5165. let i = dependencies.length;
  5166. while (i--) {
  5167. const { imports, reexports } = dependencies[i];
  5168. if (imports || reexports) {
  5169. return dependencies.slice(0, i + 1);
  5170. }
  5171. }
  5172. return [];
  5173. }
  5174. const thisProp = (name) => `this${keypath(name)}`;
  5175. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  5176. const _ = compact ? '' : ' ';
  5177. const s = compact ? '' : ';';
  5178. const n = compact ? '' : '\n';
  5179. const isNamespaced = name && name.indexOf('.') !== -1;
  5180. const useVariableAssignment = !extend && !isNamespaced;
  5181. if (name && useVariableAssignment && !isLegal(name)) {
  5182. return error({
  5183. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  5184. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  5185. });
  5186. }
  5187. warnOnBuiltins(warn, dependencies);
  5188. const external = trimEmptyImports(dependencies);
  5189. const deps = external.map(dep => dep.globalName || 'null');
  5190. const args = external.map(m => m.name);
  5191. if (hasExports && !name) {
  5192. warn({
  5193. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5194. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  5195. });
  5196. }
  5197. if (namedExportsMode && hasExports) {
  5198. if (extend) {
  5199. deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
  5200. args.unshift('exports');
  5201. }
  5202. else {
  5203. deps.unshift('{}');
  5204. args.unshift('exports');
  5205. }
  5206. }
  5207. const useStrict = strict ? `${t}'use strict';${n}` : '';
  5208. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  5209. magicString.prepend(`${intro}${interopBlock}`);
  5210. let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
  5211. if (hasExports) {
  5212. if (name && !(extend && namedExportsMode)) {
  5213. wrapperIntro =
  5214. (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
  5215. `${_}=${_}${wrapperIntro}`;
  5216. }
  5217. if (isNamespaced) {
  5218. wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
  5219. }
  5220. }
  5221. let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
  5222. if (hasExports && !extend && namedExportsMode) {
  5223. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  5224. }
  5225. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  5226. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  5227. if (namespaceMarkers) {
  5228. namespaceMarkers = n + n + namespaceMarkers;
  5229. }
  5230. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  5231. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  5232. }
  5233. function getStarExcludes({ dependencies, exports }) {
  5234. const starExcludes = new Set(exports.map(expt => expt.exported));
  5235. if (!starExcludes.has('default'))
  5236. starExcludes.add('default');
  5237. // also include reexport names
  5238. for (const { reexports } of dependencies) {
  5239. if (reexports) {
  5240. for (const reexport of reexports) {
  5241. if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
  5242. starExcludes.add(reexport.reexported);
  5243. }
  5244. }
  5245. }
  5246. return starExcludes;
  5247. }
  5248. const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
  5249. ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
  5250. .map(prop => `${prop}:${_}1`)
  5251. .join(`,${_}`)}${_}};`
  5252. : '';
  5253. const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  5254. function getExportsBlock(exports, _, t, n) {
  5255. if (exports.length === 0) {
  5256. return '';
  5257. }
  5258. if (exports.length === 1) {
  5259. return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  5260. }
  5261. return (`${t}${t}${t}exports({${n}` +
  5262. exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
  5263. `${n}${t}${t}${t}});${n}${n}`);
  5264. }
  5265. const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5266. .filter(expt => expt.hoisted || expt.uninitialized)
  5267. .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
  5268. const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5269. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  5270. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
  5271. const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5272. .filter(expt => expt.expression)
  5273. .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  5274. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
  5275. const n = options.compact ? '' : '\n';
  5276. const _ = options.compact ? '' : ' ';
  5277. const dependencyIds = dependencies.map(m => `'${m.id}'`);
  5278. const importBindings = [];
  5279. let starExcludes;
  5280. const setters = [];
  5281. for (const { imports, reexports } of dependencies) {
  5282. const setter = [];
  5283. if (imports) {
  5284. for (const specifier of imports) {
  5285. importBindings.push(specifier.local);
  5286. if (specifier.imported === '*') {
  5287. setter.push(`${specifier.local}${_}=${_}module;`);
  5288. }
  5289. else {
  5290. setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
  5291. }
  5292. }
  5293. }
  5294. if (reexports) {
  5295. let createdSetter = false;
  5296. // bulk-reexport form
  5297. if (reexports.length > 1 ||
  5298. (reexports.length === 1 &&
  5299. (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
  5300. // star reexports
  5301. for (const specifier of reexports) {
  5302. if (specifier.reexported !== '*')
  5303. continue;
  5304. // need own exports list for deduping in star export case
  5305. if (!starExcludes) {
  5306. starExcludes = getStarExcludes({ dependencies, exports });
  5307. }
  5308. if (!createdSetter) {
  5309. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5310. createdSetter = true;
  5311. }
  5312. setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
  5313. setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
  5314. setter.push('}');
  5315. }
  5316. // star import reexport
  5317. for (const specifier of reexports) {
  5318. if (specifier.imported !== '*' || specifier.reexported === '*')
  5319. continue;
  5320. setter.push(`exports('${specifier.reexported}',${_}module);`);
  5321. }
  5322. // reexports
  5323. for (const specifier of reexports) {
  5324. if (specifier.reexported === '*' || specifier.imported === '*')
  5325. continue;
  5326. if (!createdSetter) {
  5327. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5328. createdSetter = true;
  5329. }
  5330. setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
  5331. }
  5332. if (createdSetter) {
  5333. setter.push('exports(_setter);');
  5334. }
  5335. }
  5336. else {
  5337. // single reexport
  5338. for (const specifier of reexports) {
  5339. setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
  5340. }
  5341. }
  5342. }
  5343. setters.push(setter.join(`${n}${t}${t}${t}`));
  5344. }
  5345. const registeredName = options.name ? `'${options.name}',${_}` : '';
  5346. const wrapperParams = accessedGlobals.has('module')
  5347. ? `exports,${_}module`
  5348. : hasExports
  5349. ? 'exports'
  5350. : '';
  5351. let wrapperStart = `System.register(${registeredName}[` +
  5352. dependencyIds.join(`,${_}`) +
  5353. `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
  5354. getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
  5355. getImportBindingsBlock(importBindings, _, t, n) +
  5356. `${n}${t}return${_}{${setters.length
  5357. ? `${n}${t}${t}setters:${_}[${setters
  5358. .map(s => s
  5359. ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
  5360. : options.systemNullSetters
  5361. ? `null`
  5362. : `function${_}()${_}{}`)
  5363. .join(`,${_}`)}],`
  5364. : ''}${n}`;
  5365. wrapperStart +=
  5366. `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
  5367. getHoistedExportsBlock(exports, _, t, n);
  5368. const wrapperEnd = `${n}${n}` +
  5369. getSyntheticExportsBlock(exports, _, t, n) +
  5370. getMissingExportsBlock(exports, _, t, n) +
  5371. `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
  5372. if (intro)
  5373. magicString.prepend(intro);
  5374. if (outro)
  5375. magicString.append(outro);
  5376. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  5377. }
  5378. function globalProp(name, globalVar) {
  5379. if (!name)
  5380. return 'null';
  5381. return `${globalVar}${keypath(name)}`;
  5382. }
  5383. function safeAccess(name, globalVar, _) {
  5384. const parts = name.split('.');
  5385. let acc = globalVar;
  5386. return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
  5387. }
  5388. function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  5389. const _ = compact ? '' : ' ';
  5390. const n = compact ? '' : '\n';
  5391. const s = compact ? '' : ';';
  5392. const factoryVar = compact ? 'f' : 'factory';
  5393. const globalVar = compact ? 'g' : 'global';
  5394. if (hasExports && !name) {
  5395. return error({
  5396. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5397. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  5398. });
  5399. }
  5400. warnOnBuiltins(warn, dependencies);
  5401. const amdDeps = dependencies.map(m => `'${m.id}'`);
  5402. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  5403. const trimmedImports = trimEmptyImports(dependencies);
  5404. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
  5405. const factoryArgs = trimmedImports.map(m => m.name);
  5406. if (namedExportsMode && (hasExports || noConflict)) {
  5407. amdDeps.unshift(`'exports'`);
  5408. cjsDeps.unshift(`exports`);
  5409. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
  5410. factoryArgs.unshift('exports');
  5411. }
  5412. const amdParams = (amdId ? `'${amdId}',${_}` : ``) + (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  5413. const define = amdDefine;
  5414. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  5415. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  5416. let iifeExport;
  5417. if (noConflict) {
  5418. const noConflictExportsVar = compact ? 'e' : 'exports';
  5419. let factory;
  5420. if (!namedExportsMode && hasExports) {
  5421. factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
  5422. }
  5423. else {
  5424. const module = globalDeps.shift();
  5425. factory =
  5426. `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
  5427. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  5428. }
  5429. iifeExport =
  5430. `(function${_}()${_}{${n}` +
  5431. `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
  5432. `${t}${t}${factory}${n}` +
  5433. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
  5434. `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
  5435. `${t}}())`;
  5436. }
  5437. else {
  5438. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  5439. if (!namedExportsMode && hasExports) {
  5440. iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
  5441. }
  5442. }
  5443. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  5444. const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
  5445. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  5446. const iifeStart = iifeNeedsGlobal
  5447. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  5448. : '';
  5449. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  5450. const cjsIntro = iifeNeedsGlobal
  5451. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  5452. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  5453. : '';
  5454. // factory function should be wrapped by parentheses to avoid lazy parsing
  5455. const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
  5456. cjsIntro +
  5457. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  5458. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  5459. `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
  5460. const wrapperOutro = n + n + '})));';
  5461. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  5462. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  5463. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  5464. if (namespaceMarkers) {
  5465. namespaceMarkers = n + n + namespaceMarkers;
  5466. }
  5467. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  5468. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  5469. }
  5470. var finalisers = { system, amd, cjs, es, iife, umd };
  5471. const extractors = {
  5472. ArrayPattern(names, param) {
  5473. for (const element of param.elements) {
  5474. if (element)
  5475. extractors[element.type](names, element);
  5476. }
  5477. },
  5478. AssignmentPattern(names, param) {
  5479. extractors[param.left.type](names, param.left);
  5480. },
  5481. Identifier(names, param) {
  5482. names.push(param.name);
  5483. },
  5484. MemberExpression() { },
  5485. ObjectPattern(names, param) {
  5486. for (const prop of param.properties) {
  5487. if (prop.type === 'RestElement') {
  5488. extractors.RestElement(names, prop);
  5489. }
  5490. else {
  5491. extractors[prop.value.type](names, prop.value);
  5492. }
  5493. }
  5494. },
  5495. RestElement(names, param) {
  5496. extractors[param.argument.type](names, param.argument);
  5497. }
  5498. };
  5499. const extractAssignedNames = function extractAssignedNames(param) {
  5500. const names = [];
  5501. extractors[param.type](names, param);
  5502. return names;
  5503. };
  5504. class ExportAllDeclaration extends NodeBase {
  5505. hasEffects() {
  5506. return false;
  5507. }
  5508. initialise() {
  5509. this.context.addExport(this);
  5510. }
  5511. render(code, _options, nodeRenderOptions) {
  5512. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  5513. }
  5514. }
  5515. ExportAllDeclaration.prototype.needsBoundaries = true;
  5516. class ArrayExpression extends NodeBase {
  5517. bind() {
  5518. super.bind();
  5519. for (const element of this.elements) {
  5520. if (element !== null)
  5521. element.deoptimizePath(UNKNOWN_PATH);
  5522. }
  5523. }
  5524. getReturnExpressionWhenCalledAtPath(path) {
  5525. if (path.length !== 1)
  5526. return UNKNOWN_EXPRESSION;
  5527. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  5528. }
  5529. hasEffectsWhenAccessedAtPath(path) {
  5530. return path.length > 1;
  5531. }
  5532. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5533. if (path.length === 1) {
  5534. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  5535. }
  5536. return true;
  5537. }
  5538. }
  5539. class ArrayPattern extends NodeBase {
  5540. addExportedVariables(variables, exportNamesByVariable) {
  5541. for (const element of this.elements) {
  5542. if (element !== null) {
  5543. element.addExportedVariables(variables, exportNamesByVariable);
  5544. }
  5545. }
  5546. }
  5547. declare(kind) {
  5548. const variables = [];
  5549. for (const element of this.elements) {
  5550. if (element !== null) {
  5551. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5552. }
  5553. }
  5554. return variables;
  5555. }
  5556. deoptimizePath(path) {
  5557. if (path.length === 0) {
  5558. for (const element of this.elements) {
  5559. if (element !== null) {
  5560. element.deoptimizePath(path);
  5561. }
  5562. }
  5563. }
  5564. }
  5565. hasEffectsWhenAssignedAtPath(path, context) {
  5566. if (path.length > 0)
  5567. return true;
  5568. for (const element of this.elements) {
  5569. if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  5570. return true;
  5571. }
  5572. return false;
  5573. }
  5574. }
  5575. class BlockScope extends ChildScope {
  5576. addDeclaration(identifier, context, init, isHoisted) {
  5577. if (isHoisted) {
  5578. return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, isHoisted);
  5579. }
  5580. else {
  5581. return super.addDeclaration(identifier, context, init, false);
  5582. }
  5583. }
  5584. }
  5585. class ExpressionStatement$1 extends NodeBase {
  5586. initialise() {
  5587. if (this.directive &&
  5588. this.directive !== 'use strict' &&
  5589. this.parent.type === Program) {
  5590. this.context.warn(
  5591. // This is necessary, because either way (deleting or not) can lead to errors.
  5592. {
  5593. code: 'MODULE_LEVEL_DIRECTIVE',
  5594. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  5595. }, this.start);
  5596. }
  5597. }
  5598. render(code, options) {
  5599. super.render(code, options);
  5600. if (this.included)
  5601. this.insertSemicolon(code);
  5602. }
  5603. shouldBeIncluded(context) {
  5604. if (this.directive && this.directive !== 'use strict')
  5605. return this.parent.type !== Program;
  5606. return super.shouldBeIncluded(context);
  5607. }
  5608. }
  5609. class BlockStatement$1 extends NodeBase {
  5610. constructor() {
  5611. super(...arguments);
  5612. this.directlyIncluded = false;
  5613. }
  5614. addImplicitReturnExpressionToScope() {
  5615. const lastStatement = this.body[this.body.length - 1];
  5616. if (!lastStatement || lastStatement.type !== ReturnStatement) {
  5617. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  5618. }
  5619. }
  5620. createScope(parentScope) {
  5621. this.scope = this.parent.preventChildBlockScope
  5622. ? parentScope
  5623. : new BlockScope(parentScope);
  5624. }
  5625. hasEffects(context) {
  5626. if (this.deoptimizeBody)
  5627. return true;
  5628. for (const node of this.body) {
  5629. if (node.hasEffects(context))
  5630. return true;
  5631. if (context.brokenFlow)
  5632. break;
  5633. }
  5634. return false;
  5635. }
  5636. include(context, includeChildrenRecursively) {
  5637. if (!this.deoptimizeBody || !this.directlyIncluded) {
  5638. this.included = true;
  5639. this.directlyIncluded = true;
  5640. if (this.deoptimizeBody)
  5641. includeChildrenRecursively = true;
  5642. for (const node of this.body) {
  5643. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5644. node.include(context, includeChildrenRecursively);
  5645. }
  5646. }
  5647. }
  5648. initialise() {
  5649. const firstBodyStatement = this.body[0];
  5650. this.deoptimizeBody =
  5651. firstBodyStatement instanceof ExpressionStatement$1 &&
  5652. firstBodyStatement.directive === 'use asm';
  5653. }
  5654. render(code, options) {
  5655. if (this.body.length) {
  5656. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  5657. }
  5658. else {
  5659. super.render(code, options);
  5660. }
  5661. }
  5662. }
  5663. class ArrowFunctionExpression$1 extends NodeBase {
  5664. createScope(parentScope) {
  5665. this.scope = new ReturnValueScope(parentScope, this.context);
  5666. }
  5667. deoptimizePath(path) {
  5668. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  5669. // which means the return expression needs to be reassigned
  5670. if (path.length === 1 && path[0] === UnknownKey) {
  5671. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5672. }
  5673. }
  5674. getReturnExpressionWhenCalledAtPath(path) {
  5675. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  5676. }
  5677. hasEffects() {
  5678. return false;
  5679. }
  5680. hasEffectsWhenAccessedAtPath(path) {
  5681. return path.length > 1;
  5682. }
  5683. hasEffectsWhenAssignedAtPath(path) {
  5684. return path.length > 1;
  5685. }
  5686. hasEffectsWhenCalledAtPath(path, _callOptions, context) {
  5687. if (path.length > 0)
  5688. return true;
  5689. for (const param of this.params) {
  5690. if (param.hasEffects(context))
  5691. return true;
  5692. }
  5693. const { ignore, brokenFlow } = context;
  5694. context.ignore = {
  5695. breaks: false,
  5696. continues: false,
  5697. labels: new Set(),
  5698. returnAwaitYield: true
  5699. };
  5700. if (this.body.hasEffects(context))
  5701. return true;
  5702. context.ignore = ignore;
  5703. context.brokenFlow = brokenFlow;
  5704. return false;
  5705. }
  5706. include(context, includeChildrenRecursively) {
  5707. this.included = true;
  5708. for (const param of this.params) {
  5709. if (!(param instanceof Identifier$1)) {
  5710. param.include(context, includeChildrenRecursively);
  5711. }
  5712. }
  5713. const { brokenFlow } = context;
  5714. context.brokenFlow = BROKEN_FLOW_NONE;
  5715. this.body.include(context, includeChildrenRecursively);
  5716. context.brokenFlow = brokenFlow;
  5717. }
  5718. includeCallArguments(context, args) {
  5719. this.scope.includeCallArguments(context, args);
  5720. }
  5721. initialise() {
  5722. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  5723. if (this.body instanceof BlockStatement$1) {
  5724. this.body.addImplicitReturnExpressionToScope();
  5725. }
  5726. else {
  5727. this.scope.addReturnExpression(this.body);
  5728. }
  5729. }
  5730. parseNode(esTreeNode) {
  5731. if (esTreeNode.body.type === BlockStatement) {
  5732. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  5733. }
  5734. super.parseNode(esTreeNode);
  5735. }
  5736. }
  5737. ArrowFunctionExpression$1.prototype.preventChildBlockScope = true;
  5738. class AssignmentExpression extends NodeBase {
  5739. constructor() {
  5740. super(...arguments);
  5741. this.deoptimized = false;
  5742. }
  5743. hasEffects(context) {
  5744. if (!this.deoptimized)
  5745. this.applyDeoptimizations();
  5746. return (this.right.hasEffects(context) ||
  5747. this.left.hasEffects(context) ||
  5748. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  5749. }
  5750. hasEffectsWhenAccessedAtPath(path, context) {
  5751. return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
  5752. }
  5753. include(context, includeChildrenRecursively) {
  5754. if (!this.deoptimized)
  5755. this.applyDeoptimizations();
  5756. this.included = true;
  5757. this.left.include(context, includeChildrenRecursively);
  5758. this.right.include(context, includeChildrenRecursively);
  5759. }
  5760. render(code, options) {
  5761. this.left.render(code, options);
  5762. this.right.render(code, options);
  5763. if (options.format === 'system') {
  5764. const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
  5765. if (this.left.type === 'Identifier' && exportNames) {
  5766. const _ = options.compact ? '' : ' ';
  5767. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  5768. const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
  5769. code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
  5770. ? `exports('${exportNames[0]}',${_}`
  5771. : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
  5772. code.appendLeft(this.right.end, ')');
  5773. }
  5774. else {
  5775. const systemPatternExports = [];
  5776. this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  5777. if (systemPatternExports.length > 0) {
  5778. code.prependRight(this.start, getSystemExportFunctionLeft(systemPatternExports, true, options));
  5779. code.appendLeft(this.end, ')');
  5780. }
  5781. }
  5782. }
  5783. }
  5784. applyDeoptimizations() {
  5785. this.deoptimized = true;
  5786. this.left.deoptimizePath(EMPTY_PATH);
  5787. this.right.deoptimizePath(UNKNOWN_PATH);
  5788. }
  5789. }
  5790. class AssignmentPattern extends NodeBase {
  5791. addExportedVariables(variables, exportNamesByVariable) {
  5792. this.left.addExportedVariables(variables, exportNamesByVariable);
  5793. }
  5794. bind() {
  5795. super.bind();
  5796. this.left.deoptimizePath(EMPTY_PATH);
  5797. this.right.deoptimizePath(UNKNOWN_PATH);
  5798. }
  5799. declare(kind, init) {
  5800. return this.left.declare(kind, init);
  5801. }
  5802. deoptimizePath(path) {
  5803. path.length === 0 && this.left.deoptimizePath(path);
  5804. }
  5805. hasEffectsWhenAssignedAtPath(path, context) {
  5806. return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  5807. }
  5808. render(code, options, { isShorthandProperty } = BLANK) {
  5809. this.left.render(code, options, { isShorthandProperty });
  5810. this.right.render(code, options);
  5811. }
  5812. }
  5813. class AwaitExpression extends NodeBase {
  5814. hasEffects(context) {
  5815. return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
  5816. }
  5817. include(context, includeChildrenRecursively) {
  5818. if (!this.included) {
  5819. this.included = true;
  5820. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  5821. let parent = this.parent;
  5822. do {
  5823. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression$1)
  5824. break checkTopLevelAwait;
  5825. } while ((parent = parent.parent));
  5826. this.context.usesTopLevelAwait = true;
  5827. }
  5828. }
  5829. this.argument.include(context, includeChildrenRecursively);
  5830. }
  5831. }
  5832. const binaryOperators = {
  5833. '!=': (left, right) => left != right,
  5834. '!==': (left, right) => left !== right,
  5835. '%': (left, right) => left % right,
  5836. '&': (left, right) => left & right,
  5837. '*': (left, right) => left * right,
  5838. // At the moment, "**" will be transpiled to Math.pow
  5839. '**': (left, right) => left ** right,
  5840. '+': (left, right) => left + right,
  5841. '-': (left, right) => left - right,
  5842. '/': (left, right) => left / right,
  5843. '<': (left, right) => left < right,
  5844. '<<': (left, right) => left << right,
  5845. '<=': (left, right) => left <= right,
  5846. '==': (left, right) => left == right,
  5847. '===': (left, right) => left === right,
  5848. '>': (left, right) => left > right,
  5849. '>=': (left, right) => left >= right,
  5850. '>>': (left, right) => left >> right,
  5851. '>>>': (left, right) => left >>> right,
  5852. '^': (left, right) => left ^ right,
  5853. in: () => UnknownValue,
  5854. instanceof: () => UnknownValue,
  5855. '|': (left, right) => left | right
  5856. };
  5857. class BinaryExpression extends NodeBase {
  5858. deoptimizeCache() { }
  5859. getLiteralValueAtPath(path, recursionTracker, origin) {
  5860. if (path.length > 0)
  5861. return UnknownValue;
  5862. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  5863. if (leftValue === UnknownValue)
  5864. return UnknownValue;
  5865. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  5866. if (rightValue === UnknownValue)
  5867. return UnknownValue;
  5868. const operatorFn = binaryOperators[this.operator];
  5869. if (!operatorFn)
  5870. return UnknownValue;
  5871. return operatorFn(leftValue, rightValue);
  5872. }
  5873. hasEffects(context) {
  5874. // support some implicit type coercion runtime errors
  5875. if (this.operator === '+' &&
  5876. this.parent instanceof ExpressionStatement$1 &&
  5877. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
  5878. return true;
  5879. return super.hasEffects(context);
  5880. }
  5881. hasEffectsWhenAccessedAtPath(path) {
  5882. return path.length > 1;
  5883. }
  5884. }
  5885. class BreakStatement extends NodeBase {
  5886. hasEffects(context) {
  5887. if (this.label) {
  5888. if (!context.ignore.labels.has(this.label.name))
  5889. return true;
  5890. context.includedLabels.add(this.label.name);
  5891. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  5892. }
  5893. else {
  5894. if (!context.ignore.breaks)
  5895. return true;
  5896. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  5897. }
  5898. return false;
  5899. }
  5900. include(context) {
  5901. this.included = true;
  5902. if (this.label) {
  5903. this.label.include();
  5904. context.includedLabels.add(this.label.name);
  5905. }
  5906. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  5907. }
  5908. }
  5909. class Literal extends NodeBase {
  5910. getLiteralValueAtPath(path) {
  5911. if (path.length > 0 ||
  5912. // unknown literals can also be null but do not start with an "n"
  5913. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  5914. typeof this.value === 'bigint' ||
  5915. // to support shims for regular expressions
  5916. this.context.code.charCodeAt(this.start) === 47) {
  5917. return UnknownValue;
  5918. }
  5919. return this.value;
  5920. }
  5921. getReturnExpressionWhenCalledAtPath(path) {
  5922. if (path.length !== 1)
  5923. return UNKNOWN_EXPRESSION;
  5924. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  5925. }
  5926. hasEffectsWhenAccessedAtPath(path) {
  5927. if (this.value === null) {
  5928. return path.length > 0;
  5929. }
  5930. return path.length > 1;
  5931. }
  5932. hasEffectsWhenAssignedAtPath(path) {
  5933. return path.length > 0;
  5934. }
  5935. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5936. if (path.length === 1) {
  5937. return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
  5938. }
  5939. return true;
  5940. }
  5941. initialise() {
  5942. this.members = getLiteralMembersForValue(this.value);
  5943. }
  5944. parseNode(esTreeNode) {
  5945. this.value = esTreeNode.value;
  5946. this.regex = esTreeNode.regex;
  5947. super.parseNode(esTreeNode);
  5948. }
  5949. render(code) {
  5950. if (typeof this.value === 'string') {
  5951. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  5952. }
  5953. }
  5954. }
  5955. function getResolvablePropertyKey(memberExpression) {
  5956. return memberExpression.computed
  5957. ? getResolvableComputedPropertyKey(memberExpression.property)
  5958. : memberExpression.property.name;
  5959. }
  5960. function getResolvableComputedPropertyKey(propertyKey) {
  5961. if (propertyKey instanceof Literal) {
  5962. return String(propertyKey.value);
  5963. }
  5964. return null;
  5965. }
  5966. function getPathIfNotComputed(memberExpression) {
  5967. const nextPathKey = memberExpression.propertyKey;
  5968. const object = memberExpression.object;
  5969. if (typeof nextPathKey === 'string') {
  5970. if (object instanceof Identifier$1) {
  5971. return [
  5972. { key: object.name, pos: object.start },
  5973. { key: nextPathKey, pos: memberExpression.property.start }
  5974. ];
  5975. }
  5976. if (object instanceof MemberExpression) {
  5977. const parentPath = getPathIfNotComputed(object);
  5978. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  5979. }
  5980. }
  5981. return null;
  5982. }
  5983. function getStringFromPath(path) {
  5984. let pathString = path[0].key;
  5985. for (let index = 1; index < path.length; index++) {
  5986. pathString += '.' + path[index].key;
  5987. }
  5988. return pathString;
  5989. }
  5990. class MemberExpression extends NodeBase {
  5991. constructor() {
  5992. super(...arguments);
  5993. this.variable = null;
  5994. this.bound = false;
  5995. this.expressionsToBeDeoptimized = [];
  5996. this.replacement = null;
  5997. this.wasPathDeoptimizedWhileOptimized = false;
  5998. }
  5999. addExportedVariables() { }
  6000. bind() {
  6001. if (this.bound)
  6002. return;
  6003. this.bound = true;
  6004. const path = getPathIfNotComputed(this);
  6005. const baseVariable = path && this.scope.findVariable(path[0].key);
  6006. if (baseVariable && baseVariable.isNamespace) {
  6007. const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
  6008. if (!resolvedVariable) {
  6009. super.bind();
  6010. }
  6011. else if (typeof resolvedVariable === 'string') {
  6012. this.replacement = resolvedVariable;
  6013. }
  6014. else {
  6015. if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
  6016. resolvedVariable.module.suggestName(path[0].key);
  6017. }
  6018. this.variable = resolvedVariable;
  6019. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6020. }
  6021. }
  6022. else {
  6023. super.bind();
  6024. // ensure the propertyKey is set for the tree-shaking passes
  6025. this.getPropertyKey();
  6026. }
  6027. }
  6028. deoptimizeCache() {
  6029. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6030. this.expressionsToBeDeoptimized = [];
  6031. this.propertyKey = UnknownKey;
  6032. if (this.wasPathDeoptimizedWhileOptimized) {
  6033. this.object.deoptimizePath(UNKNOWN_PATH);
  6034. }
  6035. for (const expression of expressionsToBeDeoptimized) {
  6036. expression.deoptimizeCache();
  6037. }
  6038. }
  6039. deoptimizePath(path) {
  6040. if (!this.bound)
  6041. this.bind();
  6042. if (path.length === 0)
  6043. this.disallowNamespaceReassignment();
  6044. if (this.variable) {
  6045. this.variable.deoptimizePath(path);
  6046. }
  6047. else {
  6048. const propertyKey = this.getPropertyKey();
  6049. if (propertyKey === UnknownKey) {
  6050. this.object.deoptimizePath(UNKNOWN_PATH);
  6051. }
  6052. else {
  6053. this.wasPathDeoptimizedWhileOptimized = true;
  6054. this.object.deoptimizePath([propertyKey, ...path]);
  6055. }
  6056. }
  6057. }
  6058. getLiteralValueAtPath(path, recursionTracker, origin) {
  6059. if (!this.bound)
  6060. this.bind();
  6061. if (this.variable !== null) {
  6062. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6063. }
  6064. this.expressionsToBeDeoptimized.push(origin);
  6065. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6066. }
  6067. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6068. if (!this.bound)
  6069. this.bind();
  6070. if (this.variable !== null) {
  6071. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6072. }
  6073. this.expressionsToBeDeoptimized.push(origin);
  6074. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6075. }
  6076. hasEffects(context) {
  6077. return (this.property.hasEffects(context) ||
  6078. this.object.hasEffects(context) ||
  6079. (this.context.options.treeshake.propertyReadSideEffects &&
  6080. this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
  6081. }
  6082. hasEffectsWhenAccessedAtPath(path, context) {
  6083. if (path.length === 0)
  6084. return false;
  6085. if (this.variable !== null) {
  6086. return this.variable.hasEffectsWhenAccessedAtPath(path, context);
  6087. }
  6088. return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
  6089. }
  6090. hasEffectsWhenAssignedAtPath(path, context) {
  6091. if (this.variable !== null) {
  6092. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  6093. }
  6094. return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
  6095. }
  6096. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6097. if (this.variable !== null) {
  6098. return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6099. }
  6100. return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
  6101. }
  6102. include(context, includeChildrenRecursively) {
  6103. if (!this.included) {
  6104. this.included = true;
  6105. if (this.variable !== null) {
  6106. this.context.includeVariable(this.variable);
  6107. }
  6108. }
  6109. this.object.include(context, includeChildrenRecursively);
  6110. this.property.include(context, includeChildrenRecursively);
  6111. }
  6112. includeCallArguments(context, args) {
  6113. if (this.variable) {
  6114. this.variable.includeCallArguments(context, args);
  6115. }
  6116. else {
  6117. super.includeCallArguments(context, args);
  6118. }
  6119. }
  6120. initialise() {
  6121. this.propertyKey = getResolvablePropertyKey(this);
  6122. }
  6123. render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
  6124. const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
  6125. if (this.variable || this.replacement) {
  6126. let replacement = this.variable ? this.variable.getName() : this.replacement;
  6127. if (isCalleeOfDifferentParent)
  6128. replacement = '0, ' + replacement;
  6129. code.overwrite(this.start, this.end, replacement, {
  6130. contentOnly: true,
  6131. storeName: true
  6132. });
  6133. }
  6134. else {
  6135. if (isCalleeOfDifferentParent) {
  6136. code.appendRight(this.start, '0, ');
  6137. }
  6138. super.render(code, options);
  6139. }
  6140. }
  6141. disallowNamespaceReassignment() {
  6142. if (this.object instanceof Identifier$1) {
  6143. const variable = this.scope.findVariable(this.object.name);
  6144. if (variable.isNamespace) {
  6145. if (this.variable) {
  6146. this.context.includeVariable(this.variable);
  6147. }
  6148. this.context.warn({
  6149. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  6150. message: `Illegal reassignment to import '${this.object.name}'`
  6151. }, this.start);
  6152. }
  6153. }
  6154. }
  6155. getPropertyKey() {
  6156. if (this.propertyKey === null) {
  6157. this.propertyKey = UnknownKey;
  6158. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6159. return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
  6160. }
  6161. return this.propertyKey;
  6162. }
  6163. resolveNamespaceVariables(baseVariable, path) {
  6164. if (path.length === 0)
  6165. return baseVariable;
  6166. if (!baseVariable.isNamespace)
  6167. return null;
  6168. const exportName = path[0].key;
  6169. const variable = baseVariable instanceof ExternalVariable
  6170. ? baseVariable.module.getVariableForExportName(exportName)
  6171. : baseVariable.context.traceExport(exportName);
  6172. if (!variable) {
  6173. const fileName = baseVariable instanceof ExternalVariable
  6174. ? baseVariable.module.id
  6175. : baseVariable.context.fileName;
  6176. this.context.warn({
  6177. code: 'MISSING_EXPORT',
  6178. exporter: relativeId(fileName),
  6179. importer: relativeId(this.context.fileName),
  6180. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  6181. missing: exportName,
  6182. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  6183. }, path[0].pos);
  6184. return 'undefined';
  6185. }
  6186. return this.resolveNamespaceVariables(variable, path.slice(1));
  6187. }
  6188. }
  6189. class CallExpression$1 extends NodeBase {
  6190. constructor() {
  6191. super(...arguments);
  6192. this.expressionsToBeDeoptimized = [];
  6193. this.returnExpression = null;
  6194. this.wasPathDeoptmizedWhileOptimized = false;
  6195. }
  6196. bind() {
  6197. super.bind();
  6198. if (this.callee instanceof Identifier$1) {
  6199. const variable = this.scope.findVariable(this.callee.name);
  6200. if (variable.isNamespace) {
  6201. this.context.warn({
  6202. code: 'CANNOT_CALL_NAMESPACE',
  6203. message: `Cannot call a namespace ('${this.callee.name}')`
  6204. }, this.start);
  6205. }
  6206. if (this.callee.name === 'eval') {
  6207. this.context.warn({
  6208. code: 'EVAL',
  6209. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  6210. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  6211. }, this.start);
  6212. }
  6213. }
  6214. // ensure the returnExpression is set for the tree-shaking passes
  6215. this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6216. // This deoptimizes "this" for non-namespace calls until we have a better solution
  6217. if (this.callee instanceof MemberExpression && !this.callee.variable) {
  6218. this.callee.object.deoptimizePath(UNKNOWN_PATH);
  6219. }
  6220. for (const argument of this.arguments) {
  6221. // This will make sure all properties of parameters behave as "unknown"
  6222. argument.deoptimizePath(UNKNOWN_PATH);
  6223. }
  6224. }
  6225. deoptimizeCache() {
  6226. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  6227. this.returnExpression = null;
  6228. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6229. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6230. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6231. // We need to replace here because is possible new expressions are added
  6232. // while we are deoptimizing the old ones
  6233. this.expressionsToBeDeoptimized = [];
  6234. if (this.wasPathDeoptmizedWhileOptimized) {
  6235. returnExpression.deoptimizePath(UNKNOWN_PATH);
  6236. this.wasPathDeoptmizedWhileOptimized = false;
  6237. }
  6238. }
  6239. for (const expression of expressionsToBeDeoptimized) {
  6240. expression.deoptimizeCache();
  6241. }
  6242. }
  6243. }
  6244. deoptimizePath(path) {
  6245. if (path.length === 0)
  6246. return;
  6247. const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
  6248. if (trackedEntities.has(this))
  6249. return;
  6250. trackedEntities.add(this);
  6251. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6252. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6253. this.wasPathDeoptmizedWhileOptimized = true;
  6254. returnExpression.deoptimizePath(path);
  6255. }
  6256. }
  6257. getLiteralValueAtPath(path, recursionTracker, origin) {
  6258. const returnExpression = this.getReturnExpression(recursionTracker);
  6259. if (returnExpression === UNKNOWN_EXPRESSION) {
  6260. return UnknownValue;
  6261. }
  6262. const trackedEntities = recursionTracker.getEntities(path);
  6263. if (trackedEntities.has(returnExpression)) {
  6264. return UnknownValue;
  6265. }
  6266. this.expressionsToBeDeoptimized.push(origin);
  6267. trackedEntities.add(returnExpression);
  6268. const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6269. trackedEntities.delete(returnExpression);
  6270. return value;
  6271. }
  6272. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6273. const returnExpression = this.getReturnExpression(recursionTracker);
  6274. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  6275. return UNKNOWN_EXPRESSION;
  6276. }
  6277. const trackedEntities = recursionTracker.getEntities(path);
  6278. if (trackedEntities.has(returnExpression)) {
  6279. return UNKNOWN_EXPRESSION;
  6280. }
  6281. this.expressionsToBeDeoptimized.push(origin);
  6282. trackedEntities.add(returnExpression);
  6283. const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6284. trackedEntities.delete(returnExpression);
  6285. return value;
  6286. }
  6287. hasEffects(context) {
  6288. for (const argument of this.arguments) {
  6289. if (argument.hasEffects(context))
  6290. return true;
  6291. }
  6292. if (this.context.options.treeshake.annotations &&
  6293. this.annotatedPure)
  6294. return false;
  6295. return (this.callee.hasEffects(context) ||
  6296. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  6297. }
  6298. hasEffectsWhenAccessedAtPath(path, context) {
  6299. if (path.length === 0)
  6300. return false;
  6301. const trackedExpressions = context.accessed.getEntities(path);
  6302. if (trackedExpressions.has(this))
  6303. return false;
  6304. trackedExpressions.add(this);
  6305. return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
  6306. }
  6307. hasEffectsWhenAssignedAtPath(path, context) {
  6308. if (path.length === 0)
  6309. return true;
  6310. const trackedExpressions = context.assigned.getEntities(path);
  6311. if (trackedExpressions.has(this))
  6312. return false;
  6313. trackedExpressions.add(this);
  6314. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  6315. }
  6316. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6317. const trackedExpressions = (callOptions.withNew
  6318. ? context.instantiated
  6319. : context.called).getEntities(path, callOptions);
  6320. if (trackedExpressions.has(this))
  6321. return false;
  6322. trackedExpressions.add(this);
  6323. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6324. }
  6325. include(context, includeChildrenRecursively) {
  6326. if (includeChildrenRecursively) {
  6327. super.include(context, includeChildrenRecursively);
  6328. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  6329. this.callee instanceof Identifier$1 &&
  6330. this.callee.variable) {
  6331. this.callee.variable.markCalledFromTryStatement();
  6332. }
  6333. }
  6334. else {
  6335. this.included = true;
  6336. this.callee.include(context, false);
  6337. }
  6338. this.callee.includeCallArguments(context, this.arguments);
  6339. if (!this.returnExpression.included) {
  6340. this.returnExpression.include(context, false);
  6341. }
  6342. }
  6343. initialise() {
  6344. this.callOptions = {
  6345. args: this.arguments,
  6346. withNew: false
  6347. };
  6348. }
  6349. render(code, options, { renderedParentType } = BLANK) {
  6350. this.callee.render(code, options);
  6351. if (this.arguments.length > 0) {
  6352. if (this.arguments[this.arguments.length - 1].included) {
  6353. for (const arg of this.arguments) {
  6354. arg.render(code, options);
  6355. }
  6356. }
  6357. else {
  6358. let lastIncludedIndex = this.arguments.length - 2;
  6359. while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
  6360. lastIncludedIndex--;
  6361. }
  6362. if (lastIncludedIndex >= 0) {
  6363. for (let index = 0; index <= lastIncludedIndex; index++) {
  6364. this.arguments[index].render(code, options);
  6365. }
  6366. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
  6367. }
  6368. else {
  6369. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
  6370. }
  6371. }
  6372. }
  6373. if (renderedParentType === ExpressionStatement &&
  6374. this.callee.type === FunctionExpression) {
  6375. code.appendRight(this.start, '(');
  6376. code.prependLeft(this.end, ')');
  6377. }
  6378. }
  6379. getReturnExpression(recursionTracker) {
  6380. if (this.returnExpression === null) {
  6381. this.returnExpression = UNKNOWN_EXPRESSION;
  6382. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
  6383. }
  6384. return this.returnExpression;
  6385. }
  6386. }
  6387. class CatchScope extends ParameterScope {
  6388. addDeclaration(identifier, context, init, isHoisted) {
  6389. if (isHoisted) {
  6390. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6391. }
  6392. else {
  6393. return super.addDeclaration(identifier, context, init, false);
  6394. }
  6395. }
  6396. }
  6397. class CatchClause extends NodeBase {
  6398. createScope(parentScope) {
  6399. this.scope = new CatchScope(parentScope, this.context);
  6400. }
  6401. initialise() {
  6402. if (this.param) {
  6403. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  6404. }
  6405. }
  6406. parseNode(esTreeNode) {
  6407. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
  6408. super.parseNode(esTreeNode);
  6409. }
  6410. }
  6411. CatchClause.prototype.preventChildBlockScope = true;
  6412. class ChainExpression extends NodeBase {
  6413. }
  6414. class ClassBodyScope extends ChildScope {
  6415. findLexicalBoundary() {
  6416. return this;
  6417. }
  6418. }
  6419. class MethodDefinition extends NodeBase {
  6420. hasEffects(context) {
  6421. return this.key.hasEffects(context);
  6422. }
  6423. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6424. return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6425. }
  6426. }
  6427. class ClassBody extends NodeBase {
  6428. createScope(parentScope) {
  6429. this.scope = new ClassBodyScope(parentScope);
  6430. }
  6431. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6432. if (path.length > 0)
  6433. return true;
  6434. return (this.classConstructor !== null &&
  6435. this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6436. }
  6437. initialise() {
  6438. for (const method of this.body) {
  6439. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  6440. this.classConstructor = method;
  6441. return;
  6442. }
  6443. }
  6444. this.classConstructor = null;
  6445. }
  6446. }
  6447. class ClassExpression extends ClassNode {
  6448. }
  6449. class MultiExpression {
  6450. constructor(expressions) {
  6451. this.included = false;
  6452. this.expressions = expressions;
  6453. }
  6454. deoptimizePath(path) {
  6455. for (const expression of this.expressions) {
  6456. expression.deoptimizePath(path);
  6457. }
  6458. }
  6459. getLiteralValueAtPath() {
  6460. return UnknownValue;
  6461. }
  6462. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6463. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
  6464. }
  6465. hasEffectsWhenAccessedAtPath(path, context) {
  6466. for (const expression of this.expressions) {
  6467. if (expression.hasEffectsWhenAccessedAtPath(path, context))
  6468. return true;
  6469. }
  6470. return false;
  6471. }
  6472. hasEffectsWhenAssignedAtPath(path, context) {
  6473. for (const expression of this.expressions) {
  6474. if (expression.hasEffectsWhenAssignedAtPath(path, context))
  6475. return true;
  6476. }
  6477. return false;
  6478. }
  6479. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6480. for (const expression of this.expressions) {
  6481. if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
  6482. return true;
  6483. }
  6484. return false;
  6485. }
  6486. include(context, includeChildrenRecursively) {
  6487. // This is only relevant to include values that do not have an AST representation,
  6488. // such as UnknownArrayExpression. Thus we only need to include them once.
  6489. for (const expression of this.expressions) {
  6490. if (!expression.included) {
  6491. expression.include(context, includeChildrenRecursively);
  6492. }
  6493. }
  6494. }
  6495. includeCallArguments() { }
  6496. }
  6497. class ConditionalExpression extends NodeBase {
  6498. constructor() {
  6499. super(...arguments);
  6500. this.expressionsToBeDeoptimized = [];
  6501. this.isBranchResolutionAnalysed = false;
  6502. this.usedBranch = null;
  6503. this.wasPathDeoptimizedWhileOptimized = false;
  6504. }
  6505. bind() {
  6506. super.bind();
  6507. // ensure the usedBranch is set for the tree-shaking passes
  6508. this.getUsedBranch();
  6509. }
  6510. deoptimizeCache() {
  6511. if (this.usedBranch !== null) {
  6512. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  6513. this.usedBranch = null;
  6514. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6515. this.expressionsToBeDeoptimized = [];
  6516. if (this.wasPathDeoptimizedWhileOptimized) {
  6517. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  6518. }
  6519. for (const expression of expressionsToBeDeoptimized) {
  6520. expression.deoptimizeCache();
  6521. }
  6522. }
  6523. }
  6524. deoptimizePath(path) {
  6525. if (path.length > 0) {
  6526. const usedBranch = this.getUsedBranch();
  6527. if (usedBranch === null) {
  6528. this.consequent.deoptimizePath(path);
  6529. this.alternate.deoptimizePath(path);
  6530. }
  6531. else {
  6532. this.wasPathDeoptimizedWhileOptimized = true;
  6533. usedBranch.deoptimizePath(path);
  6534. }
  6535. }
  6536. }
  6537. getLiteralValueAtPath(path, recursionTracker, origin) {
  6538. const usedBranch = this.getUsedBranch();
  6539. if (usedBranch === null)
  6540. return UnknownValue;
  6541. this.expressionsToBeDeoptimized.push(origin);
  6542. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  6543. }
  6544. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6545. const usedBranch = this.getUsedBranch();
  6546. if (usedBranch === null)
  6547. return new MultiExpression([
  6548. this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  6549. this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  6550. ]);
  6551. this.expressionsToBeDeoptimized.push(origin);
  6552. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6553. }
  6554. hasEffects(context) {
  6555. if (this.test.hasEffects(context))
  6556. return true;
  6557. if (this.usedBranch === null) {
  6558. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  6559. }
  6560. return this.usedBranch.hasEffects(context);
  6561. }
  6562. hasEffectsWhenAccessedAtPath(path, context) {
  6563. if (path.length === 0)
  6564. return false;
  6565. if (this.usedBranch === null) {
  6566. return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
  6567. this.alternate.hasEffectsWhenAccessedAtPath(path, context));
  6568. }
  6569. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  6570. }
  6571. hasEffectsWhenAssignedAtPath(path, context) {
  6572. if (path.length === 0)
  6573. return true;
  6574. if (this.usedBranch === null) {
  6575. return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
  6576. this.alternate.hasEffectsWhenAssignedAtPath(path, context));
  6577. }
  6578. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  6579. }
  6580. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6581. if (this.usedBranch === null) {
  6582. return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  6583. this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
  6584. }
  6585. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6586. }
  6587. include(context, includeChildrenRecursively) {
  6588. this.included = true;
  6589. if (includeChildrenRecursively ||
  6590. this.test.shouldBeIncluded(context) ||
  6591. this.usedBranch === null) {
  6592. this.test.include(context, includeChildrenRecursively);
  6593. this.consequent.include(context, includeChildrenRecursively);
  6594. this.alternate.include(context, includeChildrenRecursively);
  6595. }
  6596. else {
  6597. this.usedBranch.include(context, includeChildrenRecursively);
  6598. }
  6599. }
  6600. includeCallArguments(context, args) {
  6601. if (this.usedBranch === null) {
  6602. this.consequent.includeCallArguments(context, args);
  6603. this.alternate.includeCallArguments(context, args);
  6604. }
  6605. else {
  6606. this.usedBranch.includeCallArguments(context, args);
  6607. }
  6608. }
  6609. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  6610. if (!this.test.included) {
  6611. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  6612. const inclusionStart = (this.consequent.included
  6613. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  6614. : colonPos) + 1;
  6615. if (preventASI) {
  6616. removeLineBreaks(code, inclusionStart, this.usedBranch.start);
  6617. }
  6618. code.remove(this.start, inclusionStart);
  6619. if (this.consequent.included) {
  6620. code.remove(colonPos, this.end);
  6621. }
  6622. removeAnnotations(this, code);
  6623. this.usedBranch.render(code, options, {
  6624. isCalleeOfRenderedParent: renderedParentType
  6625. ? isCalleeOfRenderedParent
  6626. : this.parent.callee === this,
  6627. preventASI: true,
  6628. renderedParentType: renderedParentType || this.parent.type
  6629. });
  6630. }
  6631. else {
  6632. super.render(code, options);
  6633. }
  6634. }
  6635. getUsedBranch() {
  6636. if (this.isBranchResolutionAnalysed) {
  6637. return this.usedBranch;
  6638. }
  6639. this.isBranchResolutionAnalysed = true;
  6640. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6641. return testValue === UnknownValue
  6642. ? null
  6643. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  6644. }
  6645. }
  6646. class ContinueStatement extends NodeBase {
  6647. hasEffects(context) {
  6648. if (this.label) {
  6649. if (!context.ignore.labels.has(this.label.name))
  6650. return true;
  6651. context.includedLabels.add(this.label.name);
  6652. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6653. }
  6654. else {
  6655. if (!context.ignore.continues)
  6656. return true;
  6657. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6658. }
  6659. return false;
  6660. }
  6661. include(context) {
  6662. this.included = true;
  6663. if (this.label) {
  6664. this.label.include();
  6665. context.includedLabels.add(this.label.name);
  6666. }
  6667. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6668. }
  6669. }
  6670. class DoWhileStatement extends NodeBase {
  6671. hasEffects(context) {
  6672. if (this.test.hasEffects(context))
  6673. return true;
  6674. const { brokenFlow, ignore: { breaks, continues } } = context;
  6675. context.ignore.breaks = true;
  6676. context.ignore.continues = true;
  6677. if (this.body.hasEffects(context))
  6678. return true;
  6679. context.ignore.breaks = breaks;
  6680. context.ignore.continues = continues;
  6681. context.brokenFlow = brokenFlow;
  6682. return false;
  6683. }
  6684. include(context, includeChildrenRecursively) {
  6685. this.included = true;
  6686. this.test.include(context, includeChildrenRecursively);
  6687. const { brokenFlow } = context;
  6688. this.body.include(context, includeChildrenRecursively);
  6689. context.brokenFlow = brokenFlow;
  6690. }
  6691. }
  6692. class EmptyStatement extends NodeBase {
  6693. hasEffects() {
  6694. return false;
  6695. }
  6696. }
  6697. class ExportNamedDeclaration extends NodeBase {
  6698. bind() {
  6699. // Do not bind specifiers
  6700. if (this.declaration !== null)
  6701. this.declaration.bind();
  6702. }
  6703. hasEffects(context) {
  6704. return this.declaration !== null && this.declaration.hasEffects(context);
  6705. }
  6706. initialise() {
  6707. this.context.addExport(this);
  6708. }
  6709. render(code, options, nodeRenderOptions) {
  6710. const { start, end } = nodeRenderOptions;
  6711. if (this.declaration === null) {
  6712. code.remove(start, end);
  6713. }
  6714. else {
  6715. code.remove(this.start, this.declaration.start);
  6716. this.declaration.render(code, options, { start, end });
  6717. }
  6718. }
  6719. }
  6720. ExportNamedDeclaration.prototype.needsBoundaries = true;
  6721. class ExportSpecifier extends NodeBase {
  6722. }
  6723. class FieldDefinition extends NodeBase {
  6724. hasEffects(context) {
  6725. return (this.key.hasEffects(context) ||
  6726. (this.static && this.value !== null && this.value.hasEffects(context)));
  6727. }
  6728. }
  6729. class ForInStatement extends NodeBase {
  6730. bind() {
  6731. this.left.bind();
  6732. this.left.deoptimizePath(EMPTY_PATH);
  6733. this.right.bind();
  6734. this.body.bind();
  6735. }
  6736. createScope(parentScope) {
  6737. this.scope = new BlockScope(parentScope);
  6738. }
  6739. hasEffects(context) {
  6740. if ((this.left &&
  6741. (this.left.hasEffects(context) ||
  6742. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
  6743. (this.right && this.right.hasEffects(context)))
  6744. return true;
  6745. const { brokenFlow, ignore: { breaks, continues } } = context;
  6746. context.ignore.breaks = true;
  6747. context.ignore.continues = true;
  6748. if (this.body.hasEffects(context))
  6749. return true;
  6750. context.ignore.breaks = breaks;
  6751. context.ignore.continues = continues;
  6752. context.brokenFlow = brokenFlow;
  6753. return false;
  6754. }
  6755. include(context, includeChildrenRecursively) {
  6756. this.included = true;
  6757. this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
  6758. this.left.deoptimizePath(EMPTY_PATH);
  6759. this.right.include(context, includeChildrenRecursively);
  6760. const { brokenFlow } = context;
  6761. this.body.include(context, includeChildrenRecursively);
  6762. context.brokenFlow = brokenFlow;
  6763. }
  6764. render(code, options) {
  6765. this.left.render(code, options, NO_SEMICOLON);
  6766. this.right.render(code, options, NO_SEMICOLON);
  6767. // handle no space between "in" and the right side
  6768. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  6769. code.prependLeft(this.right.start, ' ');
  6770. }
  6771. this.body.render(code, options);
  6772. }
  6773. }
  6774. class ForOfStatement extends NodeBase {
  6775. bind() {
  6776. this.left.bind();
  6777. this.left.deoptimizePath(EMPTY_PATH);
  6778. this.right.bind();
  6779. this.body.bind();
  6780. }
  6781. createScope(parentScope) {
  6782. this.scope = new BlockScope(parentScope);
  6783. }
  6784. hasEffects() {
  6785. // Placeholder until proper Symbol.Iterator support
  6786. return true;
  6787. }
  6788. include(context, includeChildrenRecursively) {
  6789. this.included = true;
  6790. this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
  6791. this.left.deoptimizePath(EMPTY_PATH);
  6792. this.right.include(context, includeChildrenRecursively);
  6793. const { brokenFlow } = context;
  6794. this.body.include(context, includeChildrenRecursively);
  6795. context.brokenFlow = brokenFlow;
  6796. }
  6797. render(code, options) {
  6798. this.left.render(code, options, NO_SEMICOLON);
  6799. this.right.render(code, options, NO_SEMICOLON);
  6800. // handle no space between "of" and the right side
  6801. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  6802. code.prependLeft(this.right.start, ' ');
  6803. }
  6804. this.body.render(code, options);
  6805. }
  6806. }
  6807. class ForStatement extends NodeBase {
  6808. createScope(parentScope) {
  6809. this.scope = new BlockScope(parentScope);
  6810. }
  6811. hasEffects(context) {
  6812. if ((this.init && this.init.hasEffects(context)) ||
  6813. (this.test && this.test.hasEffects(context)) ||
  6814. (this.update && this.update.hasEffects(context)))
  6815. return true;
  6816. const { brokenFlow, ignore: { breaks, continues } } = context;
  6817. context.ignore.breaks = true;
  6818. context.ignore.continues = true;
  6819. if (this.body.hasEffects(context))
  6820. return true;
  6821. context.ignore.breaks = breaks;
  6822. context.ignore.continues = continues;
  6823. context.brokenFlow = brokenFlow;
  6824. return false;
  6825. }
  6826. include(context, includeChildrenRecursively) {
  6827. this.included = true;
  6828. if (this.init)
  6829. this.init.include(context, includeChildrenRecursively);
  6830. if (this.test)
  6831. this.test.include(context, includeChildrenRecursively);
  6832. const { brokenFlow } = context;
  6833. if (this.update)
  6834. this.update.include(context, includeChildrenRecursively);
  6835. this.body.include(context, includeChildrenRecursively);
  6836. context.brokenFlow = brokenFlow;
  6837. }
  6838. render(code, options) {
  6839. if (this.init)
  6840. this.init.render(code, options, NO_SEMICOLON);
  6841. if (this.test)
  6842. this.test.render(code, options, NO_SEMICOLON);
  6843. if (this.update)
  6844. this.update.render(code, options, NO_SEMICOLON);
  6845. this.body.render(code, options);
  6846. }
  6847. }
  6848. class FunctionExpression$1 extends FunctionNode {
  6849. }
  6850. class TrackingScope extends BlockScope {
  6851. constructor() {
  6852. super(...arguments);
  6853. this.hoistedDeclarations = [];
  6854. }
  6855. addDeclaration(identifier, context, init, isHoisted) {
  6856. this.hoistedDeclarations.push(identifier);
  6857. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6858. }
  6859. }
  6860. const unset = Symbol('unset');
  6861. class IfStatement extends NodeBase {
  6862. constructor() {
  6863. super(...arguments);
  6864. this.testValue = unset;
  6865. }
  6866. deoptimizeCache() {
  6867. this.testValue = UnknownValue;
  6868. }
  6869. hasEffects(context) {
  6870. if (this.test.hasEffects(context)) {
  6871. return true;
  6872. }
  6873. const testValue = this.getTestValue();
  6874. if (testValue === UnknownValue) {
  6875. const { brokenFlow } = context;
  6876. if (this.consequent.hasEffects(context))
  6877. return true;
  6878. const consequentBrokenFlow = context.brokenFlow;
  6879. context.brokenFlow = brokenFlow;
  6880. if (this.alternate === null)
  6881. return false;
  6882. if (this.alternate.hasEffects(context))
  6883. return true;
  6884. context.brokenFlow =
  6885. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  6886. return false;
  6887. }
  6888. return testValue
  6889. ? this.consequent.hasEffects(context)
  6890. : this.alternate !== null && this.alternate.hasEffects(context);
  6891. }
  6892. include(context, includeChildrenRecursively) {
  6893. this.included = true;
  6894. if (includeChildrenRecursively) {
  6895. this.includeRecursively(includeChildrenRecursively, context);
  6896. }
  6897. else {
  6898. const testValue = this.getTestValue();
  6899. if (testValue === UnknownValue) {
  6900. this.includeUnknownTest(context);
  6901. }
  6902. else {
  6903. this.includeKnownTest(context, testValue);
  6904. }
  6905. }
  6906. }
  6907. parseNode(esTreeNode) {
  6908. this.consequentScope = new TrackingScope(this.scope);
  6909. this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
  6910. this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
  6911. if (esTreeNode.alternate) {
  6912. this.alternateScope = new TrackingScope(this.scope);
  6913. this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
  6914. this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
  6915. }
  6916. super.parseNode(esTreeNode);
  6917. }
  6918. render(code, options) {
  6919. // Note that unknown test values are always included
  6920. const testValue = this.getTestValue();
  6921. const hoistedDeclarations = [];
  6922. const includesIfElse = this.test.included;
  6923. const noTreeshake = !this.context.options.treeshake;
  6924. if (includesIfElse) {
  6925. this.test.render(code, options);
  6926. }
  6927. else {
  6928. removeAnnotations(this, code);
  6929. code.remove(this.start, this.consequent.start);
  6930. }
  6931. if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
  6932. this.consequent.render(code, options);
  6933. }
  6934. else {
  6935. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  6936. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  6937. }
  6938. if (this.alternate) {
  6939. if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
  6940. if (includesIfElse) {
  6941. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  6942. code.prependLeft(this.alternate.start, ' ');
  6943. }
  6944. }
  6945. else {
  6946. code.remove(this.consequent.end, this.alternate.start);
  6947. }
  6948. this.alternate.render(code, options);
  6949. }
  6950. else {
  6951. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  6952. code.overwrite(this.alternate.start, this.end, ';');
  6953. }
  6954. else {
  6955. code.remove(this.consequent.end, this.end);
  6956. }
  6957. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  6958. }
  6959. }
  6960. this.renderHoistedDeclarations(hoistedDeclarations, code);
  6961. }
  6962. getTestValue() {
  6963. if (this.testValue === unset) {
  6964. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  6965. }
  6966. return this.testValue;
  6967. }
  6968. includeKnownTest(context, testValue) {
  6969. if (this.test.shouldBeIncluded(context)) {
  6970. this.test.include(context, false);
  6971. }
  6972. if (testValue && this.consequent.shouldBeIncluded(context)) {
  6973. this.consequent.include(context, false);
  6974. }
  6975. if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
  6976. this.alternate.include(context, false);
  6977. }
  6978. }
  6979. includeRecursively(includeChildrenRecursively, context) {
  6980. this.test.include(context, includeChildrenRecursively);
  6981. this.consequent.include(context, includeChildrenRecursively);
  6982. if (this.alternate !== null) {
  6983. this.alternate.include(context, includeChildrenRecursively);
  6984. }
  6985. }
  6986. includeUnknownTest(context) {
  6987. this.test.include(context, false);
  6988. const { brokenFlow } = context;
  6989. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  6990. if (this.consequent.shouldBeIncluded(context)) {
  6991. this.consequent.include(context, false);
  6992. consequentBrokenFlow = context.brokenFlow;
  6993. context.brokenFlow = brokenFlow;
  6994. }
  6995. if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
  6996. this.alternate.include(context, false);
  6997. context.brokenFlow =
  6998. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  6999. }
  7000. }
  7001. renderHoistedDeclarations(hoistedDeclarations, code) {
  7002. const hoistedVars = [
  7003. ...new Set(hoistedDeclarations.map(identifier => {
  7004. const variable = identifier.variable;
  7005. return variable.included ? variable.getName() : '';
  7006. }))
  7007. ]
  7008. .filter(Boolean)
  7009. .join(', ');
  7010. if (hoistedVars) {
  7011. const parentType = this.parent.type;
  7012. const needsBraces = parentType !== Program && parentType !== BlockStatement;
  7013. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  7014. if (needsBraces) {
  7015. code.appendLeft(this.end, ` }`);
  7016. }
  7017. }
  7018. }
  7019. shouldKeepAlternateBranch() {
  7020. let currentParent = this.parent;
  7021. do {
  7022. if (currentParent instanceof IfStatement && currentParent.alternate) {
  7023. return true;
  7024. }
  7025. if (currentParent instanceof BlockStatement$1) {
  7026. return false;
  7027. }
  7028. currentParent = currentParent.parent;
  7029. } while (currentParent);
  7030. return false;
  7031. }
  7032. }
  7033. class ImportDeclaration extends NodeBase {
  7034. bind() { }
  7035. hasEffects() {
  7036. return false;
  7037. }
  7038. initialise() {
  7039. this.context.addImport(this);
  7040. }
  7041. render(code, _options, nodeRenderOptions) {
  7042. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  7043. }
  7044. }
  7045. ImportDeclaration.prototype.needsBoundaries = true;
  7046. class ImportDefaultSpecifier$1 extends NodeBase {
  7047. }
  7048. class ImportExpression extends NodeBase {
  7049. constructor() {
  7050. super(...arguments);
  7051. this.inlineNamespace = null;
  7052. this.mechanism = null;
  7053. this.resolution = null;
  7054. }
  7055. hasEffects() {
  7056. return true;
  7057. }
  7058. include(context, includeChildrenRecursively) {
  7059. if (!this.included) {
  7060. this.included = true;
  7061. this.context.includeDynamicImport(this);
  7062. this.scope.addAccessedDynamicImport(this);
  7063. }
  7064. this.source.include(context, includeChildrenRecursively);
  7065. }
  7066. initialise() {
  7067. this.context.addDynamicImport(this);
  7068. }
  7069. render(code, options) {
  7070. if (this.inlineNamespace) {
  7071. const _ = options.compact ? '' : ' ';
  7072. const s = options.compact ? '' : ';';
  7073. code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
  7074. return;
  7075. }
  7076. if (this.mechanism) {
  7077. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  7078. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  7079. }
  7080. this.source.render(code, options);
  7081. }
  7082. renderFinalResolution(code, resolution, namespaceExportName, options) {
  7083. code.overwrite(this.source.start, this.source.end, resolution);
  7084. if (namespaceExportName) {
  7085. const _ = options.compact ? '' : ' ';
  7086. const s = options.compact ? '' : ';';
  7087. code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
  7088. }
  7089. }
  7090. setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
  7091. this.resolution = resolution;
  7092. const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
  7093. let helper;
  7094. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
  7095. if (helper) {
  7096. accessedGlobals.push(helper);
  7097. }
  7098. if (accessedGlobals.length > 0) {
  7099. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7100. }
  7101. }
  7102. setInternalResolution(inlineNamespace) {
  7103. this.inlineNamespace = inlineNamespace;
  7104. }
  7105. getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
  7106. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  7107. {
  7108. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  7109. format: options.format,
  7110. moduleId: this.context.module.id,
  7111. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  7112. }
  7113. ]);
  7114. if (mechanism) {
  7115. return { helper: null, mechanism };
  7116. }
  7117. switch (options.format) {
  7118. case 'cjs': {
  7119. const _ = options.compact ? '' : ' ';
  7120. const s = options.compact ? '' : ';';
  7121. const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
  7122. const helper = this.getInteropHelper(resolution, exportMode, options.interop);
  7123. return {
  7124. helper,
  7125. mechanism: helper
  7126. ? {
  7127. left: `${leftStart} /*#__PURE__*/${helper}(require(`,
  7128. right: `))${s}${_}})`
  7129. }
  7130. : {
  7131. left: `${leftStart} require(`,
  7132. right: `)${s}${_}})`
  7133. }
  7134. };
  7135. }
  7136. case 'amd': {
  7137. const _ = options.compact ? '' : ' ';
  7138. const resolve = options.compact ? 'c' : 'resolve';
  7139. const reject = options.compact ? 'e' : 'reject';
  7140. const helper = this.getInteropHelper(resolution, exportMode, options.interop);
  7141. const resolveNamespace = helper
  7142. ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
  7143. : resolve;
  7144. return {
  7145. helper,
  7146. mechanism: {
  7147. left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
  7148. right: `],${_}${resolveNamespace},${_}${reject})${_}})`
  7149. }
  7150. };
  7151. }
  7152. case 'system':
  7153. return {
  7154. helper: null,
  7155. mechanism: {
  7156. left: 'module.import(',
  7157. right: ')'
  7158. }
  7159. };
  7160. case 'es':
  7161. if (options.dynamicImportFunction) {
  7162. return {
  7163. helper: null,
  7164. mechanism: {
  7165. left: `${options.dynamicImportFunction}(`,
  7166. right: ')'
  7167. }
  7168. };
  7169. }
  7170. }
  7171. return { helper: null, mechanism: null };
  7172. }
  7173. getInteropHelper(resolution, exportMode, interop) {
  7174. return exportMode === 'external'
  7175. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  7176. : exportMode === 'default'
  7177. ? getDefaultOnlyHelper()
  7178. : null;
  7179. }
  7180. }
  7181. const accessedImportGlobals = {
  7182. amd: ['require'],
  7183. cjs: ['require'],
  7184. system: ['module']
  7185. };
  7186. class ImportNamespaceSpecifier$1 extends NodeBase {
  7187. }
  7188. class ImportSpecifier extends NodeBase {
  7189. }
  7190. class LabeledStatement extends NodeBase {
  7191. hasEffects(context) {
  7192. const brokenFlow = context.brokenFlow;
  7193. context.ignore.labels.add(this.label.name);
  7194. if (this.body.hasEffects(context))
  7195. return true;
  7196. context.ignore.labels.delete(this.label.name);
  7197. if (context.includedLabels.has(this.label.name)) {
  7198. context.includedLabels.delete(this.label.name);
  7199. context.brokenFlow = brokenFlow;
  7200. }
  7201. return false;
  7202. }
  7203. include(context, includeChildrenRecursively) {
  7204. this.included = true;
  7205. const brokenFlow = context.brokenFlow;
  7206. this.body.include(context, includeChildrenRecursively);
  7207. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  7208. this.label.include();
  7209. context.includedLabels.delete(this.label.name);
  7210. context.brokenFlow = brokenFlow;
  7211. }
  7212. }
  7213. render(code, options) {
  7214. if (this.label.included) {
  7215. this.label.render(code, options);
  7216. }
  7217. else {
  7218. code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
  7219. }
  7220. this.body.render(code, options);
  7221. }
  7222. }
  7223. class LogicalExpression extends NodeBase {
  7224. constructor() {
  7225. super(...arguments);
  7226. // We collect deoptimization information if usedBranch !== null
  7227. this.expressionsToBeDeoptimized = [];
  7228. this.isBranchResolutionAnalysed = false;
  7229. this.unusedBranch = null;
  7230. this.usedBranch = null;
  7231. this.wasPathDeoptimizedWhileOptimized = false;
  7232. }
  7233. bind() {
  7234. super.bind();
  7235. // ensure the usedBranch is set for the tree-shaking passes
  7236. this.getUsedBranch();
  7237. }
  7238. deoptimizeCache() {
  7239. if (this.usedBranch !== null) {
  7240. this.usedBranch = null;
  7241. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7242. this.expressionsToBeDeoptimized = [];
  7243. if (this.wasPathDeoptimizedWhileOptimized) {
  7244. this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7245. }
  7246. for (const expression of expressionsToBeDeoptimized) {
  7247. expression.deoptimizeCache();
  7248. }
  7249. }
  7250. }
  7251. deoptimizePath(path) {
  7252. const usedBranch = this.getUsedBranch();
  7253. if (usedBranch === null) {
  7254. this.left.deoptimizePath(path);
  7255. this.right.deoptimizePath(path);
  7256. }
  7257. else {
  7258. this.wasPathDeoptimizedWhileOptimized = true;
  7259. usedBranch.deoptimizePath(path);
  7260. }
  7261. }
  7262. getLiteralValueAtPath(path, recursionTracker, origin) {
  7263. const usedBranch = this.getUsedBranch();
  7264. if (usedBranch === null)
  7265. return UnknownValue;
  7266. this.expressionsToBeDeoptimized.push(origin);
  7267. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7268. }
  7269. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7270. const usedBranch = this.getUsedBranch();
  7271. if (usedBranch === null)
  7272. return new MultiExpression([
  7273. this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  7274. this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  7275. ]);
  7276. this.expressionsToBeDeoptimized.push(origin);
  7277. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7278. }
  7279. hasEffects(context) {
  7280. if (this.left.hasEffects(context)) {
  7281. return true;
  7282. }
  7283. if (this.usedBranch !== this.left) {
  7284. return this.right.hasEffects(context);
  7285. }
  7286. return false;
  7287. }
  7288. hasEffectsWhenAccessedAtPath(path, context) {
  7289. if (path.length === 0)
  7290. return false;
  7291. if (this.usedBranch === null) {
  7292. return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
  7293. this.right.hasEffectsWhenAccessedAtPath(path, context));
  7294. }
  7295. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7296. }
  7297. hasEffectsWhenAssignedAtPath(path, context) {
  7298. if (path.length === 0)
  7299. return true;
  7300. if (this.usedBranch === null) {
  7301. return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
  7302. this.right.hasEffectsWhenAssignedAtPath(path, context));
  7303. }
  7304. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7305. }
  7306. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7307. if (this.usedBranch === null) {
  7308. return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7309. this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7310. }
  7311. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7312. }
  7313. include(context, includeChildrenRecursively) {
  7314. this.included = true;
  7315. if (includeChildrenRecursively ||
  7316. (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  7317. this.usedBranch === null) {
  7318. this.left.include(context, includeChildrenRecursively);
  7319. this.right.include(context, includeChildrenRecursively);
  7320. }
  7321. else {
  7322. this.usedBranch.include(context, includeChildrenRecursively);
  7323. }
  7324. }
  7325. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  7326. if (!this.left.included || !this.right.included) {
  7327. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  7328. if (this.right.included) {
  7329. code.remove(this.start, operatorPos + 2);
  7330. if (preventASI) {
  7331. removeLineBreaks(code, operatorPos + 2, this.right.start);
  7332. }
  7333. }
  7334. else {
  7335. code.remove(operatorPos, this.end);
  7336. }
  7337. removeAnnotations(this, code);
  7338. this.usedBranch.render(code, options, {
  7339. isCalleeOfRenderedParent: renderedParentType
  7340. ? isCalleeOfRenderedParent
  7341. : this.parent.callee === this,
  7342. preventASI,
  7343. renderedParentType: renderedParentType || this.parent.type
  7344. });
  7345. }
  7346. else {
  7347. this.left.render(code, options, { preventASI });
  7348. this.right.render(code, options);
  7349. }
  7350. }
  7351. getUsedBranch() {
  7352. if (!this.isBranchResolutionAnalysed) {
  7353. this.isBranchResolutionAnalysed = true;
  7354. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7355. if (leftValue === UnknownValue) {
  7356. return null;
  7357. }
  7358. else {
  7359. if ((this.operator === '||' && leftValue) ||
  7360. (this.operator === '&&' && !leftValue) ||
  7361. (this.operator === '??' && leftValue != null)) {
  7362. this.usedBranch = this.left;
  7363. this.unusedBranch = this.right;
  7364. }
  7365. else {
  7366. this.usedBranch = this.right;
  7367. this.unusedBranch = this.left;
  7368. }
  7369. }
  7370. }
  7371. return this.usedBranch;
  7372. }
  7373. }
  7374. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  7375. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  7376. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7377. class MetaProperty extends NodeBase {
  7378. addAccessedGlobals(format, accessedGlobalsByScope) {
  7379. const metaProperty = this.metaProperty;
  7380. const accessedGlobals = (metaProperty &&
  7381. (metaProperty.startsWith(FILE_PREFIX) ||
  7382. metaProperty.startsWith(ASSET_PREFIX) ||
  7383. metaProperty.startsWith(CHUNK_PREFIX))
  7384. ? accessedFileUrlGlobals
  7385. : accessedMetaUrlGlobals)[format];
  7386. if (accessedGlobals.length > 0) {
  7387. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7388. }
  7389. }
  7390. getReferencedFileName(outputPluginDriver) {
  7391. const metaProperty = this.metaProperty;
  7392. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  7393. return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
  7394. }
  7395. return null;
  7396. }
  7397. hasEffects() {
  7398. return false;
  7399. }
  7400. hasEffectsWhenAccessedAtPath(path) {
  7401. return path.length > 1;
  7402. }
  7403. include() {
  7404. if (!this.included) {
  7405. this.included = true;
  7406. if (this.meta.name === 'import') {
  7407. this.context.addImportMeta(this);
  7408. const parent = this.parent;
  7409. this.metaProperty =
  7410. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7411. ? parent.propertyKey
  7412. : null;
  7413. }
  7414. }
  7415. }
  7416. renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
  7417. var _a;
  7418. const parent = this.parent;
  7419. const metaProperty = this.metaProperty;
  7420. if (metaProperty &&
  7421. (metaProperty.startsWith(FILE_PREFIX) ||
  7422. metaProperty.startsWith(ASSET_PREFIX) ||
  7423. metaProperty.startsWith(CHUNK_PREFIX))) {
  7424. let referenceId = null;
  7425. let assetReferenceId = null;
  7426. let chunkReferenceId = null;
  7427. let fileName;
  7428. if (metaProperty.startsWith(FILE_PREFIX)) {
  7429. referenceId = metaProperty.substr(FILE_PREFIX.length);
  7430. fileName = outputPluginDriver.getFileName(referenceId);
  7431. }
  7432. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  7433. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  7434. assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
  7435. fileName = outputPluginDriver.getFileName(assetReferenceId);
  7436. }
  7437. else {
  7438. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  7439. chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
  7440. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  7441. }
  7442. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  7443. let replacement;
  7444. if (assetReferenceId !== null) {
  7445. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  7446. {
  7447. assetFileName: fileName,
  7448. chunkId,
  7449. format,
  7450. moduleId: this.context.module.id,
  7451. relativeAssetPath: relativePath
  7452. }
  7453. ]);
  7454. }
  7455. if (!replacement) {
  7456. replacement =
  7457. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  7458. {
  7459. assetReferenceId,
  7460. chunkId,
  7461. chunkReferenceId,
  7462. fileName,
  7463. format,
  7464. moduleId: this.context.module.id,
  7465. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  7466. relativePath
  7467. }
  7468. ]) || relativeUrlMechanisms[format](relativePath);
  7469. }
  7470. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7471. return;
  7472. }
  7473. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  7474. metaProperty,
  7475. {
  7476. chunkId,
  7477. format,
  7478. moduleId: this.context.module.id
  7479. }
  7480. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
  7481. if (typeof replacement === 'string') {
  7482. if (parent instanceof MemberExpression) {
  7483. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7484. }
  7485. else {
  7486. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  7487. }
  7488. }
  7489. }
  7490. }
  7491. const accessedMetaUrlGlobals = {
  7492. amd: ['document', 'module', 'URL'],
  7493. cjs: ['document', 'require', 'URL'],
  7494. es: [],
  7495. iife: ['document', 'URL'],
  7496. system: ['module'],
  7497. umd: ['document', 'require', 'URL']
  7498. };
  7499. const accessedFileUrlGlobals = {
  7500. amd: ['document', 'require', 'URL'],
  7501. cjs: ['document', 'require', 'URL'],
  7502. es: [],
  7503. iife: ['document', 'URL'],
  7504. system: ['module', 'URL'],
  7505. umd: ['document', 'require', 'URL']
  7506. };
  7507. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  7508. const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
  7509. const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
  7510. const urlMechanism = getUrl(chunkId);
  7511. return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
  7512. };
  7513. const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  7514. const relativeUrlMechanisms = {
  7515. amd: relativePath => {
  7516. if (relativePath[0] !== '.')
  7517. relativePath = './' + relativePath;
  7518. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  7519. },
  7520. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  7521. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  7522. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  7523. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  7524. umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
  7525. };
  7526. const importMetaMechanisms = {
  7527. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  7528. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  7529. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7530. system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
  7531. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
  7532. };
  7533. class NewExpression extends NodeBase {
  7534. bind() {
  7535. super.bind();
  7536. for (const argument of this.arguments) {
  7537. // This will make sure all properties of parameters behave as "unknown"
  7538. argument.deoptimizePath(UNKNOWN_PATH);
  7539. }
  7540. }
  7541. hasEffects(context) {
  7542. for (const argument of this.arguments) {
  7543. if (argument.hasEffects(context))
  7544. return true;
  7545. }
  7546. if (this.context.options.treeshake.annotations &&
  7547. this.annotatedPure)
  7548. return false;
  7549. return (this.callee.hasEffects(context) ||
  7550. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  7551. }
  7552. hasEffectsWhenAccessedAtPath(path) {
  7553. return path.length > 1;
  7554. }
  7555. initialise() {
  7556. this.callOptions = {
  7557. args: this.arguments,
  7558. withNew: true
  7559. };
  7560. }
  7561. }
  7562. class ObjectExpression extends NodeBase {
  7563. constructor() {
  7564. super(...arguments);
  7565. this.deoptimizedPaths = new Set();
  7566. // We collect deoptimization information if we can resolve a computed property access
  7567. this.expressionsToBeDeoptimized = new Map();
  7568. this.hasUnknownDeoptimizedProperty = false;
  7569. this.propertyMap = null;
  7570. this.unmatchablePropertiesRead = [];
  7571. this.unmatchablePropertiesWrite = [];
  7572. }
  7573. bind() {
  7574. super.bind();
  7575. // ensure the propertyMap is set for the tree-shaking passes
  7576. this.getPropertyMap();
  7577. }
  7578. // We could also track this per-property but this would quickly become much more complex
  7579. deoptimizeCache() {
  7580. if (!this.hasUnknownDeoptimizedProperty)
  7581. this.deoptimizeAllProperties();
  7582. }
  7583. deoptimizePath(path) {
  7584. if (this.hasUnknownDeoptimizedProperty)
  7585. return;
  7586. const propertyMap = this.getPropertyMap();
  7587. const key = path[0];
  7588. if (path.length === 1) {
  7589. if (typeof key !== 'string') {
  7590. this.deoptimizeAllProperties();
  7591. return;
  7592. }
  7593. if (!this.deoptimizedPaths.has(key)) {
  7594. this.deoptimizedPaths.add(key);
  7595. // we only deoptimizeCache exact matches as in all other cases,
  7596. // we do not return a literal value or return expression
  7597. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  7598. if (expressionsToBeDeoptimized) {
  7599. for (const expression of expressionsToBeDeoptimized) {
  7600. expression.deoptimizeCache();
  7601. }
  7602. }
  7603. }
  7604. }
  7605. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  7606. for (const property of typeof key === 'string'
  7607. ? propertyMap[key]
  7608. ? propertyMap[key].propertiesRead
  7609. : []
  7610. : this.properties) {
  7611. property.deoptimizePath(subPath);
  7612. }
  7613. }
  7614. getLiteralValueAtPath(path, recursionTracker, origin) {
  7615. const propertyMap = this.getPropertyMap();
  7616. const key = path[0];
  7617. if (path.length === 0 ||
  7618. this.hasUnknownDeoptimizedProperty ||
  7619. typeof key !== 'string' ||
  7620. this.deoptimizedPaths.has(key)) {
  7621. return UnknownValue;
  7622. }
  7623. if (path.length === 1 &&
  7624. !propertyMap[key] &&
  7625. !objectMembers[key] &&
  7626. this.unmatchablePropertiesRead.length === 0) {
  7627. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7628. return undefined;
  7629. }
  7630. if (!propertyMap[key] ||
  7631. propertyMap[key].exactMatchRead === null ||
  7632. propertyMap[key].propertiesRead.length > 1) {
  7633. return UnknownValue;
  7634. }
  7635. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7636. return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  7637. }
  7638. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7639. const propertyMap = this.getPropertyMap();
  7640. const key = path[0];
  7641. if (path.length === 0 ||
  7642. this.hasUnknownDeoptimizedProperty ||
  7643. typeof key !== 'string' ||
  7644. this.deoptimizedPaths.has(key)) {
  7645. return UNKNOWN_EXPRESSION;
  7646. }
  7647. if (path.length === 1 &&
  7648. objectMembers[key] &&
  7649. this.unmatchablePropertiesRead.length === 0 &&
  7650. (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) {
  7651. return getMemberReturnExpressionWhenCalled(objectMembers, key);
  7652. }
  7653. if (!propertyMap[key] ||
  7654. propertyMap[key].exactMatchRead === null ||
  7655. propertyMap[key].propertiesRead.length > 1) {
  7656. return UNKNOWN_EXPRESSION;
  7657. }
  7658. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7659. return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
  7660. }
  7661. hasEffectsWhenAccessedAtPath(path, context) {
  7662. if (path.length === 0)
  7663. return false;
  7664. const key = path[0];
  7665. const propertyMap = this.propertyMap;
  7666. if (path.length > 1 &&
  7667. (this.hasUnknownDeoptimizedProperty ||
  7668. typeof key !== 'string' ||
  7669. this.deoptimizedPaths.has(key) ||
  7670. !propertyMap[key] ||
  7671. propertyMap[key].exactMatchRead === null))
  7672. return true;
  7673. const subPath = path.slice(1);
  7674. for (const property of typeof key !== 'string'
  7675. ? this.properties
  7676. : propertyMap[key]
  7677. ? propertyMap[key].propertiesRead
  7678. : []) {
  7679. if (property.hasEffectsWhenAccessedAtPath(subPath, context))
  7680. return true;
  7681. }
  7682. return false;
  7683. }
  7684. hasEffectsWhenAssignedAtPath(path, context) {
  7685. const key = path[0];
  7686. const propertyMap = this.propertyMap;
  7687. if (path.length > 1 &&
  7688. (this.hasUnknownDeoptimizedProperty ||
  7689. this.deoptimizedPaths.has(key) ||
  7690. !propertyMap[key] ||
  7691. propertyMap[key].exactMatchRead === null)) {
  7692. return true;
  7693. }
  7694. const subPath = path.slice(1);
  7695. for (const property of typeof key !== 'string'
  7696. ? this.properties
  7697. : path.length > 1
  7698. ? propertyMap[key].propertiesRead
  7699. : propertyMap[key]
  7700. ? propertyMap[key].propertiesWrite
  7701. : []) {
  7702. if (property.hasEffectsWhenAssignedAtPath(subPath, context))
  7703. return true;
  7704. }
  7705. return false;
  7706. }
  7707. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7708. const key = path[0];
  7709. if (typeof key !== 'string' ||
  7710. this.hasUnknownDeoptimizedProperty ||
  7711. this.deoptimizedPaths.has(key) ||
  7712. (this.propertyMap[key]
  7713. ? !this.propertyMap[key].exactMatchRead
  7714. : path.length > 1 || !objectMembers[key])) {
  7715. return true;
  7716. }
  7717. const subPath = path.slice(1);
  7718. if (this.propertyMap[key]) {
  7719. for (const property of this.propertyMap[key].propertiesRead) {
  7720. if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
  7721. return true;
  7722. }
  7723. }
  7724. if (path.length === 1 && objectMembers[key])
  7725. return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
  7726. return false;
  7727. }
  7728. render(code, options, { renderedParentType } = BLANK) {
  7729. super.render(code, options);
  7730. if (renderedParentType === ExpressionStatement ||
  7731. renderedParentType === ArrowFunctionExpression) {
  7732. code.appendRight(this.start, '(');
  7733. code.prependLeft(this.end, ')');
  7734. }
  7735. }
  7736. deoptimizeAllProperties() {
  7737. this.hasUnknownDeoptimizedProperty = true;
  7738. for (const property of this.properties) {
  7739. property.deoptimizePath(UNKNOWN_PATH);
  7740. }
  7741. for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
  7742. for (const expression of expressionsToBeDeoptimized) {
  7743. expression.deoptimizeCache();
  7744. }
  7745. }
  7746. }
  7747. getPropertyMap() {
  7748. if (this.propertyMap !== null) {
  7749. return this.propertyMap;
  7750. }
  7751. const propertyMap = (this.propertyMap = Object.create(null));
  7752. for (let index = this.properties.length - 1; index >= 0; index--) {
  7753. const property = this.properties[index];
  7754. if (property instanceof SpreadElement) {
  7755. this.unmatchablePropertiesRead.push(property);
  7756. continue;
  7757. }
  7758. const isWrite = property.kind !== 'get';
  7759. const isRead = property.kind !== 'set';
  7760. let key;
  7761. if (property.computed) {
  7762. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7763. if (keyValue === UnknownValue) {
  7764. if (isRead) {
  7765. this.unmatchablePropertiesRead.push(property);
  7766. }
  7767. else {
  7768. this.unmatchablePropertiesWrite.push(property);
  7769. }
  7770. continue;
  7771. }
  7772. key = String(keyValue);
  7773. }
  7774. else if (property.key instanceof Identifier$1) {
  7775. key = property.key.name;
  7776. }
  7777. else {
  7778. key = String(property.key.value);
  7779. }
  7780. const propertyMapProperty = propertyMap[key];
  7781. if (!propertyMapProperty) {
  7782. propertyMap[key] = {
  7783. exactMatchRead: isRead ? property : null,
  7784. exactMatchWrite: isWrite ? property : null,
  7785. propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
  7786. propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
  7787. };
  7788. continue;
  7789. }
  7790. if (isRead && propertyMapProperty.exactMatchRead === null) {
  7791. propertyMapProperty.exactMatchRead = property;
  7792. propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
  7793. }
  7794. if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
  7795. propertyMapProperty.exactMatchWrite = property;
  7796. propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
  7797. }
  7798. }
  7799. return propertyMap;
  7800. }
  7801. }
  7802. class ObjectPattern extends NodeBase {
  7803. addExportedVariables(variables, exportNamesByVariable) {
  7804. for (const property of this.properties) {
  7805. if (property.type === Property) {
  7806. property.value.addExportedVariables(variables, exportNamesByVariable);
  7807. }
  7808. else {
  7809. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7810. }
  7811. }
  7812. }
  7813. declare(kind, init) {
  7814. const variables = [];
  7815. for (const property of this.properties) {
  7816. variables.push(...property.declare(kind, init));
  7817. }
  7818. return variables;
  7819. }
  7820. deoptimizePath(path) {
  7821. if (path.length === 0) {
  7822. for (const property of this.properties) {
  7823. property.deoptimizePath(path);
  7824. }
  7825. }
  7826. }
  7827. hasEffectsWhenAssignedAtPath(path, context) {
  7828. if (path.length > 0)
  7829. return true;
  7830. for (const property of this.properties) {
  7831. if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  7832. return true;
  7833. }
  7834. return false;
  7835. }
  7836. }
  7837. class PrivateName extends NodeBase {
  7838. }
  7839. class Program$1 extends NodeBase {
  7840. constructor() {
  7841. super(...arguments);
  7842. this.hasCachedEffect = false;
  7843. }
  7844. hasEffects(context) {
  7845. // We are caching here to later more efficiently identify side-effect-free modules
  7846. if (this.hasCachedEffect)
  7847. return true;
  7848. for (const node of this.body) {
  7849. if (node.hasEffects(context)) {
  7850. return (this.hasCachedEffect = true);
  7851. }
  7852. }
  7853. return false;
  7854. }
  7855. include(context, includeChildrenRecursively) {
  7856. this.included = true;
  7857. for (const node of this.body) {
  7858. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  7859. node.include(context, includeChildrenRecursively);
  7860. }
  7861. }
  7862. }
  7863. render(code, options) {
  7864. if (this.body.length) {
  7865. renderStatementList(this.body, code, this.start, this.end, options);
  7866. }
  7867. else {
  7868. super.render(code, options);
  7869. }
  7870. }
  7871. }
  7872. class Property$1 extends NodeBase {
  7873. constructor() {
  7874. super(...arguments);
  7875. this.declarationInit = null;
  7876. this.returnExpression = null;
  7877. }
  7878. bind() {
  7879. super.bind();
  7880. if (this.kind === 'get') {
  7881. // ensure the returnExpression is set for the tree-shaking passes
  7882. this.getReturnExpression();
  7883. }
  7884. if (this.declarationInit !== null) {
  7885. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7886. }
  7887. }
  7888. declare(kind, init) {
  7889. this.declarationInit = init;
  7890. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  7891. }
  7892. // As getter properties directly receive their values from function expressions that always
  7893. // have a fixed return value, there is no known situation where a getter is deoptimized.
  7894. deoptimizeCache() { }
  7895. deoptimizePath(path) {
  7896. if (this.kind === 'get') {
  7897. this.getReturnExpression().deoptimizePath(path);
  7898. }
  7899. else {
  7900. this.value.deoptimizePath(path);
  7901. }
  7902. }
  7903. getLiteralValueAtPath(path, recursionTracker, origin) {
  7904. if (this.kind === 'get') {
  7905. return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
  7906. }
  7907. return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
  7908. }
  7909. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7910. if (this.kind === 'get') {
  7911. return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7912. }
  7913. return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7914. }
  7915. hasEffects(context) {
  7916. return this.key.hasEffects(context) || this.value.hasEffects(context);
  7917. }
  7918. hasEffectsWhenAccessedAtPath(path, context) {
  7919. if (this.kind === 'get') {
  7920. const trackedExpressions = context.accessed.getEntities(path);
  7921. if (trackedExpressions.has(this))
  7922. return false;
  7923. trackedExpressions.add(this);
  7924. return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
  7925. (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
  7926. }
  7927. return this.value.hasEffectsWhenAccessedAtPath(path, context);
  7928. }
  7929. hasEffectsWhenAssignedAtPath(path, context) {
  7930. if (this.kind === 'get') {
  7931. const trackedExpressions = context.assigned.getEntities(path);
  7932. if (trackedExpressions.has(this))
  7933. return false;
  7934. trackedExpressions.add(this);
  7935. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  7936. }
  7937. if (this.kind === 'set') {
  7938. const trackedExpressions = context.assigned.getEntities(path);
  7939. if (trackedExpressions.has(this))
  7940. return false;
  7941. trackedExpressions.add(this);
  7942. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  7943. }
  7944. return this.value.hasEffectsWhenAssignedAtPath(path, context);
  7945. }
  7946. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7947. if (this.kind === 'get') {
  7948. const trackedExpressions = (callOptions.withNew
  7949. ? context.instantiated
  7950. : context.called).getEntities(path, callOptions);
  7951. if (trackedExpressions.has(this))
  7952. return false;
  7953. trackedExpressions.add(this);
  7954. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7955. }
  7956. return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7957. }
  7958. initialise() {
  7959. this.accessorCallOptions = {
  7960. args: NO_ARGS,
  7961. withNew: false
  7962. };
  7963. }
  7964. render(code, options) {
  7965. if (!this.shorthand) {
  7966. this.key.render(code, options);
  7967. }
  7968. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  7969. }
  7970. getReturnExpression() {
  7971. if (this.returnExpression === null) {
  7972. this.returnExpression = UNKNOWN_EXPRESSION;
  7973. return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  7974. }
  7975. return this.returnExpression;
  7976. }
  7977. }
  7978. class ReturnStatement$1 extends NodeBase {
  7979. hasEffects(context) {
  7980. if (!context.ignore.returnAwaitYield ||
  7981. (this.argument !== null && this.argument.hasEffects(context)))
  7982. return true;
  7983. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7984. return false;
  7985. }
  7986. include(context, includeChildrenRecursively) {
  7987. this.included = true;
  7988. if (this.argument) {
  7989. this.argument.include(context, includeChildrenRecursively);
  7990. }
  7991. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7992. }
  7993. initialise() {
  7994. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  7995. }
  7996. render(code, options) {
  7997. if (this.argument) {
  7998. this.argument.render(code, options, { preventASI: true });
  7999. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  8000. code.prependLeft(this.start + 6, ' ');
  8001. }
  8002. }
  8003. }
  8004. }
  8005. class SequenceExpression extends NodeBase {
  8006. deoptimizePath(path) {
  8007. if (path.length > 0)
  8008. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  8009. }
  8010. getLiteralValueAtPath(path, recursionTracker, origin) {
  8011. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  8012. }
  8013. hasEffects(context) {
  8014. for (const expression of this.expressions) {
  8015. if (expression.hasEffects(context))
  8016. return true;
  8017. }
  8018. return false;
  8019. }
  8020. hasEffectsWhenAccessedAtPath(path, context) {
  8021. return (path.length > 0 &&
  8022. this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
  8023. }
  8024. hasEffectsWhenAssignedAtPath(path, context) {
  8025. return (path.length === 0 ||
  8026. this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
  8027. }
  8028. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8029. return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
  8030. }
  8031. include(context, includeChildrenRecursively) {
  8032. this.included = true;
  8033. for (let i = 0; i < this.expressions.length - 1; i++) {
  8034. const node = this.expressions[i];
  8035. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8036. node.include(context, includeChildrenRecursively);
  8037. }
  8038. this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
  8039. }
  8040. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  8041. let includedNodes = 0;
  8042. for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  8043. if (!node.included) {
  8044. treeshakeNode(node, code, start, end);
  8045. continue;
  8046. }
  8047. includedNodes++;
  8048. if (includedNodes === 1 && preventASI) {
  8049. removeLineBreaks(code, start, node.start);
  8050. }
  8051. if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
  8052. node.render(code, options, {
  8053. isCalleeOfRenderedParent: renderedParentType
  8054. ? isCalleeOfRenderedParent
  8055. : this.parent.callee === this,
  8056. renderedParentType: renderedParentType || this.parent.type
  8057. });
  8058. }
  8059. else {
  8060. node.render(code, options);
  8061. }
  8062. }
  8063. }
  8064. }
  8065. class Super extends NodeBase {
  8066. }
  8067. class SwitchCase extends NodeBase {
  8068. hasEffects(context) {
  8069. if (this.test && this.test.hasEffects(context))
  8070. return true;
  8071. for (const node of this.consequent) {
  8072. if (context.brokenFlow)
  8073. break;
  8074. if (node.hasEffects(context))
  8075. return true;
  8076. }
  8077. return false;
  8078. }
  8079. include(context, includeChildrenRecursively) {
  8080. this.included = true;
  8081. if (this.test)
  8082. this.test.include(context, includeChildrenRecursively);
  8083. for (const node of this.consequent) {
  8084. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8085. node.include(context, includeChildrenRecursively);
  8086. }
  8087. }
  8088. render(code, options, nodeRenderOptions) {
  8089. if (this.consequent.length) {
  8090. this.test && this.test.render(code, options);
  8091. const testEnd = this.test
  8092. ? this.test.end
  8093. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  8094. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  8095. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  8096. }
  8097. else {
  8098. super.render(code, options);
  8099. }
  8100. }
  8101. }
  8102. SwitchCase.prototype.needsBoundaries = true;
  8103. class SwitchStatement extends NodeBase {
  8104. createScope(parentScope) {
  8105. this.scope = new BlockScope(parentScope);
  8106. }
  8107. hasEffects(context) {
  8108. if (this.discriminant.hasEffects(context))
  8109. return true;
  8110. const { brokenFlow, ignore: { breaks } } = context;
  8111. let minBrokenFlow = Infinity;
  8112. context.ignore.breaks = true;
  8113. for (const switchCase of this.cases) {
  8114. if (switchCase.hasEffects(context))
  8115. return true;
  8116. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  8117. context.brokenFlow = brokenFlow;
  8118. }
  8119. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8120. context.brokenFlow = minBrokenFlow;
  8121. }
  8122. context.ignore.breaks = breaks;
  8123. return false;
  8124. }
  8125. include(context, includeChildrenRecursively) {
  8126. this.included = true;
  8127. this.discriminant.include(context, includeChildrenRecursively);
  8128. const { brokenFlow } = context;
  8129. let minBrokenFlow = Infinity;
  8130. let isCaseIncluded = includeChildrenRecursively ||
  8131. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  8132. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  8133. const switchCase = this.cases[caseIndex];
  8134. if (switchCase.included) {
  8135. isCaseIncluded = true;
  8136. }
  8137. if (!isCaseIncluded) {
  8138. const hasEffectsContext = createHasEffectsContext();
  8139. hasEffectsContext.ignore.breaks = true;
  8140. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  8141. }
  8142. if (isCaseIncluded) {
  8143. switchCase.include(context, includeChildrenRecursively);
  8144. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  8145. context.brokenFlow = brokenFlow;
  8146. }
  8147. else {
  8148. minBrokenFlow = brokenFlow;
  8149. }
  8150. }
  8151. if (isCaseIncluded &&
  8152. this.defaultCase !== null &&
  8153. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8154. context.brokenFlow = minBrokenFlow;
  8155. }
  8156. }
  8157. initialise() {
  8158. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  8159. if (this.cases[caseIndex].test === null) {
  8160. this.defaultCase = caseIndex;
  8161. return;
  8162. }
  8163. }
  8164. this.defaultCase = null;
  8165. }
  8166. render(code, options) {
  8167. this.discriminant.render(code, options);
  8168. if (this.cases.length > 0) {
  8169. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  8170. }
  8171. }
  8172. }
  8173. class TaggedTemplateExpression extends NodeBase {
  8174. bind() {
  8175. super.bind();
  8176. if (this.tag.type === Identifier) {
  8177. const name = this.tag.name;
  8178. const variable = this.scope.findVariable(name);
  8179. if (variable.isNamespace) {
  8180. this.context.warn({
  8181. code: 'CANNOT_CALL_NAMESPACE',
  8182. message: `Cannot call a namespace ('${name}')`,
  8183. }, this.start);
  8184. }
  8185. if (name === 'eval') {
  8186. this.context.warn({
  8187. code: 'EVAL',
  8188. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8189. url: 'https://rollupjs.org/guide/en/#avoiding-eval',
  8190. }, this.start);
  8191. }
  8192. }
  8193. }
  8194. hasEffects(context) {
  8195. return (super.hasEffects(context) ||
  8196. this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8197. }
  8198. initialise() {
  8199. this.callOptions = {
  8200. args: NO_ARGS,
  8201. withNew: false,
  8202. };
  8203. }
  8204. }
  8205. class TemplateElement extends NodeBase {
  8206. bind() { }
  8207. hasEffects() {
  8208. return false;
  8209. }
  8210. include() {
  8211. this.included = true;
  8212. }
  8213. parseNode(esTreeNode) {
  8214. this.value = esTreeNode.value;
  8215. super.parseNode(esTreeNode);
  8216. }
  8217. render() { }
  8218. }
  8219. class TemplateLiteral extends NodeBase {
  8220. getLiteralValueAtPath(path) {
  8221. if (path.length > 0 || this.quasis.length !== 1) {
  8222. return UnknownValue;
  8223. }
  8224. return this.quasis[0].value.cooked;
  8225. }
  8226. render(code, options) {
  8227. code.indentExclusionRanges.push([this.start, this.end]);
  8228. super.render(code, options);
  8229. }
  8230. }
  8231. class ModuleScope extends ChildScope {
  8232. constructor(parent, context) {
  8233. super(parent);
  8234. this.context = context;
  8235. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  8236. }
  8237. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  8238. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  8239. this.variables.set('default', variable);
  8240. return variable;
  8241. }
  8242. addNamespaceMemberAccess() { }
  8243. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8244. // all module level variables are already deconflicted when deconflicting the chunk
  8245. for (const scope of this.children)
  8246. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8247. }
  8248. findLexicalBoundary() {
  8249. return this;
  8250. }
  8251. findVariable(name) {
  8252. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8253. if (knownVariable) {
  8254. return knownVariable;
  8255. }
  8256. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  8257. if (variable instanceof GlobalVariable) {
  8258. this.accessedOutsideVariables.set(name, variable);
  8259. }
  8260. return variable;
  8261. }
  8262. }
  8263. class ThisExpression extends NodeBase {
  8264. bind() {
  8265. super.bind();
  8266. this.variable = this.scope.findVariable('this');
  8267. }
  8268. hasEffectsWhenAccessedAtPath(path, context) {
  8269. return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  8270. }
  8271. hasEffectsWhenAssignedAtPath(path, context) {
  8272. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  8273. }
  8274. initialise() {
  8275. this.alias =
  8276. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  8277. if (this.alias === 'undefined') {
  8278. this.context.warn({
  8279. code: 'THIS_IS_UNDEFINED',
  8280. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  8281. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  8282. }, this.start);
  8283. }
  8284. }
  8285. render(code) {
  8286. if (this.alias !== null) {
  8287. code.overwrite(this.start, this.end, this.alias, {
  8288. contentOnly: false,
  8289. storeName: true
  8290. });
  8291. }
  8292. }
  8293. }
  8294. class ThrowStatement extends NodeBase {
  8295. hasEffects() {
  8296. return true;
  8297. }
  8298. include(context, includeChildrenRecursively) {
  8299. this.included = true;
  8300. this.argument.include(context, includeChildrenRecursively);
  8301. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8302. }
  8303. render(code, options) {
  8304. this.argument.render(code, options, { preventASI: true });
  8305. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  8306. code.prependLeft(this.start + 5, ' ');
  8307. }
  8308. }
  8309. }
  8310. class TryStatement extends NodeBase {
  8311. constructor() {
  8312. super(...arguments);
  8313. this.directlyIncluded = false;
  8314. }
  8315. hasEffects(context) {
  8316. return ((this.context.options.treeshake.tryCatchDeoptimization
  8317. ? this.block.body.length > 0
  8318. : this.block.hasEffects(context)) ||
  8319. (this.finalizer !== null && this.finalizer.hasEffects(context)));
  8320. }
  8321. include(context, includeChildrenRecursively) {
  8322. var _a;
  8323. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  8324. const { brokenFlow } = context;
  8325. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  8326. this.included = true;
  8327. this.directlyIncluded = true;
  8328. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  8329. context.brokenFlow = brokenFlow;
  8330. }
  8331. if (this.handler !== null) {
  8332. this.handler.include(context, includeChildrenRecursively);
  8333. context.brokenFlow = brokenFlow;
  8334. }
  8335. if (this.finalizer !== null) {
  8336. this.finalizer.include(context, includeChildrenRecursively);
  8337. }
  8338. }
  8339. }
  8340. const unaryOperators = {
  8341. '!': value => !value,
  8342. '+': value => +value,
  8343. '-': value => -value,
  8344. delete: () => UnknownValue,
  8345. typeof: value => typeof value,
  8346. void: () => undefined,
  8347. '~': value => ~value
  8348. };
  8349. class UnaryExpression extends NodeBase {
  8350. bind() {
  8351. super.bind();
  8352. if (this.operator === 'delete') {
  8353. this.argument.deoptimizePath(EMPTY_PATH);
  8354. }
  8355. }
  8356. getLiteralValueAtPath(path, recursionTracker, origin) {
  8357. if (path.length > 0)
  8358. return UnknownValue;
  8359. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8360. if (argumentValue === UnknownValue)
  8361. return UnknownValue;
  8362. return unaryOperators[this.operator](argumentValue);
  8363. }
  8364. hasEffects(context) {
  8365. if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
  8366. return false;
  8367. return (this.argument.hasEffects(context) ||
  8368. (this.operator === 'delete' &&
  8369. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
  8370. }
  8371. hasEffectsWhenAccessedAtPath(path) {
  8372. if (this.operator === 'void') {
  8373. return path.length > 0;
  8374. }
  8375. return path.length > 1;
  8376. }
  8377. }
  8378. class UnknownNode extends NodeBase {
  8379. hasEffects() {
  8380. return true;
  8381. }
  8382. include(context) {
  8383. super.include(context, true);
  8384. }
  8385. }
  8386. class UpdateExpression extends NodeBase {
  8387. bind() {
  8388. super.bind();
  8389. this.argument.deoptimizePath(EMPTY_PATH);
  8390. if (this.argument instanceof Identifier$1) {
  8391. const variable = this.scope.findVariable(this.argument.name);
  8392. variable.isReassigned = true;
  8393. }
  8394. }
  8395. hasEffects(context) {
  8396. return (this.argument.hasEffects(context) ||
  8397. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  8398. }
  8399. hasEffectsWhenAccessedAtPath(path) {
  8400. return path.length > 1;
  8401. }
  8402. render(code, options) {
  8403. this.argument.render(code, options);
  8404. if (options.format === 'system') {
  8405. const variable = this.argument.variable;
  8406. const exportNames = options.exportNamesByVariable.get(variable);
  8407. if (exportNames && exportNames.length) {
  8408. const _ = options.compact ? '' : ' ';
  8409. const name = variable.getName();
  8410. if (this.prefix) {
  8411. if (exportNames.length === 1) {
  8412. code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
  8413. }
  8414. else {
  8415. code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
  8416. }
  8417. }
  8418. else if (exportNames.length > 1) {
  8419. code.overwrite(this.start, this.end, `${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name})`);
  8420. }
  8421. else {
  8422. let op;
  8423. switch (this.operator) {
  8424. case '++':
  8425. op = `${name}${_}+${_}1`;
  8426. break;
  8427. case '--':
  8428. op = `${name}${_}-${_}1`;
  8429. break;
  8430. }
  8431. code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
  8432. }
  8433. }
  8434. }
  8435. }
  8436. }
  8437. function isReassignedExportsMember(variable, exportNamesByVariable) {
  8438. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  8439. }
  8440. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  8441. for (const declarator of declarations) {
  8442. if (!declarator.included)
  8443. return false;
  8444. if (declarator.id.type === Identifier) {
  8445. if (exportNamesByVariable.has(declarator.id.variable))
  8446. return false;
  8447. }
  8448. else {
  8449. const exportedVariables = [];
  8450. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  8451. if (exportedVariables.length > 0)
  8452. return false;
  8453. }
  8454. }
  8455. return true;
  8456. }
  8457. class VariableDeclaration extends NodeBase {
  8458. deoptimizePath() {
  8459. for (const declarator of this.declarations) {
  8460. declarator.deoptimizePath(EMPTY_PATH);
  8461. }
  8462. }
  8463. hasEffectsWhenAssignedAtPath() {
  8464. return false;
  8465. }
  8466. include(context, includeChildrenRecursively) {
  8467. this.included = true;
  8468. for (const declarator of this.declarations) {
  8469. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  8470. declarator.include(context, includeChildrenRecursively);
  8471. }
  8472. }
  8473. includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
  8474. this.included = true;
  8475. for (const declarator of this.declarations) {
  8476. declarator.include(context, includeChildrenRecursively);
  8477. }
  8478. }
  8479. initialise() {
  8480. for (const declarator of this.declarations) {
  8481. declarator.declareDeclarator(this.kind);
  8482. }
  8483. }
  8484. render(code, options, nodeRenderOptions = BLANK) {
  8485. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  8486. for (const declarator of this.declarations) {
  8487. declarator.render(code, options);
  8488. }
  8489. if (!nodeRenderOptions.isNoStatement &&
  8490. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  8491. code.appendLeft(this.end, ';');
  8492. }
  8493. }
  8494. else {
  8495. this.renderReplacedDeclarations(code, options, nodeRenderOptions);
  8496. }
  8497. }
  8498. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports, options) {
  8499. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  8500. code.remove(this.end - 1, this.end);
  8501. }
  8502. if (addSemicolon) {
  8503. separatorString += ';';
  8504. }
  8505. if (lastSeparatorPos !== null) {
  8506. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  8507. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  8508. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  8509. actualContentEnd--;
  8510. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  8511. actualContentEnd--;
  8512. }
  8513. }
  8514. if (actualContentEnd === lastSeparatorPos + 1) {
  8515. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  8516. }
  8517. else {
  8518. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8519. code.remove(actualContentEnd, renderedContentEnd);
  8520. }
  8521. }
  8522. else {
  8523. code.appendLeft(renderedContentEnd, separatorString);
  8524. }
  8525. if (systemPatternExports.length > 0) {
  8526. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  8527. }
  8528. }
  8529. renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
  8530. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  8531. let actualContentEnd, renderedContentEnd;
  8532. if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
  8533. renderedContentEnd = this.start + this.kind.length;
  8534. }
  8535. else {
  8536. renderedContentEnd = separatedNodes[0].start;
  8537. }
  8538. let lastSeparatorPos = renderedContentEnd - 1;
  8539. code.remove(this.start, lastSeparatorPos);
  8540. let isInDeclaration = false;
  8541. let hasRenderedContent = false;
  8542. let separatorString = '', leadingString, nextSeparatorString;
  8543. const systemPatternExports = [];
  8544. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  8545. if (!node.included ||
  8546. (node.id instanceof Identifier$1 &&
  8547. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable) &&
  8548. node.init === null)) {
  8549. code.remove(start, end);
  8550. continue;
  8551. }
  8552. leadingString = '';
  8553. nextSeparatorString = '';
  8554. if (node.id instanceof Identifier$1 &&
  8555. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable)) {
  8556. if (hasRenderedContent) {
  8557. separatorString += ';';
  8558. }
  8559. isInDeclaration = false;
  8560. }
  8561. else {
  8562. if (options.format === 'system' && node.init !== null) {
  8563. if (node.id.type !== Identifier) {
  8564. node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  8565. }
  8566. else {
  8567. const exportNames = options.exportNamesByVariable.get(node.id.variable);
  8568. if (exportNames) {
  8569. const _ = options.compact ? '' : ' ';
  8570. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  8571. code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
  8572. ? `exports('${exportNames[0]}',${_}`
  8573. : getSystemExportFunctionLeft([node.id.variable], false, options));
  8574. nextSeparatorString += ')';
  8575. }
  8576. }
  8577. }
  8578. if (isInDeclaration) {
  8579. separatorString += ',';
  8580. }
  8581. else {
  8582. if (hasRenderedContent) {
  8583. separatorString += ';';
  8584. }
  8585. leadingString += `${this.kind} `;
  8586. isInDeclaration = true;
  8587. }
  8588. }
  8589. if (renderedContentEnd === lastSeparatorPos + 1) {
  8590. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  8591. }
  8592. else {
  8593. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8594. code.appendLeft(renderedContentEnd, leadingString);
  8595. }
  8596. node.render(code, options);
  8597. actualContentEnd = contentEnd;
  8598. renderedContentEnd = end;
  8599. hasRenderedContent = true;
  8600. lastSeparatorPos = separator;
  8601. separatorString = nextSeparatorString;
  8602. }
  8603. if (hasRenderedContent) {
  8604. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports, options);
  8605. }
  8606. else {
  8607. code.remove(start, end);
  8608. }
  8609. }
  8610. }
  8611. class VariableDeclarator extends NodeBase {
  8612. declareDeclarator(kind) {
  8613. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  8614. }
  8615. deoptimizePath(path) {
  8616. this.id.deoptimizePath(path);
  8617. }
  8618. }
  8619. class WhileStatement extends NodeBase {
  8620. hasEffects(context) {
  8621. if (this.test.hasEffects(context))
  8622. return true;
  8623. const { brokenFlow, ignore: { breaks, continues } } = context;
  8624. context.ignore.breaks = true;
  8625. context.ignore.continues = true;
  8626. if (this.body.hasEffects(context))
  8627. return true;
  8628. context.ignore.breaks = breaks;
  8629. context.ignore.continues = continues;
  8630. context.brokenFlow = brokenFlow;
  8631. return false;
  8632. }
  8633. include(context, includeChildrenRecursively) {
  8634. this.included = true;
  8635. this.test.include(context, includeChildrenRecursively);
  8636. const { brokenFlow } = context;
  8637. this.body.include(context, includeChildrenRecursively);
  8638. context.brokenFlow = brokenFlow;
  8639. }
  8640. }
  8641. class YieldExpression extends NodeBase {
  8642. bind() {
  8643. super.bind();
  8644. if (this.argument !== null) {
  8645. this.argument.deoptimizePath(UNKNOWN_PATH);
  8646. }
  8647. }
  8648. hasEffects(context) {
  8649. return (!context.ignore.returnAwaitYield ||
  8650. (this.argument !== null && this.argument.hasEffects(context)));
  8651. }
  8652. render(code, options) {
  8653. if (this.argument) {
  8654. this.argument.render(code, options, { preventASI: true });
  8655. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  8656. code.prependLeft(this.start + 5, ' ');
  8657. }
  8658. }
  8659. }
  8660. }
  8661. const nodeConstructors = {
  8662. ArrayExpression,
  8663. ArrayPattern,
  8664. ArrowFunctionExpression: ArrowFunctionExpression$1,
  8665. AssignmentExpression,
  8666. AssignmentPattern,
  8667. AwaitExpression,
  8668. BinaryExpression,
  8669. BlockStatement: BlockStatement$1,
  8670. BreakStatement,
  8671. CallExpression: CallExpression$1,
  8672. CatchClause,
  8673. ChainExpression,
  8674. ClassBody,
  8675. ClassDeclaration,
  8676. ClassExpression,
  8677. ConditionalExpression,
  8678. ContinueStatement,
  8679. DoWhileStatement,
  8680. EmptyStatement,
  8681. ExportAllDeclaration,
  8682. ExportDefaultDeclaration,
  8683. ExportNamedDeclaration,
  8684. ExportSpecifier,
  8685. ExpressionStatement: ExpressionStatement$1,
  8686. FieldDefinition,
  8687. ForInStatement,
  8688. ForOfStatement,
  8689. ForStatement,
  8690. FunctionDeclaration,
  8691. FunctionExpression: FunctionExpression$1,
  8692. Identifier: Identifier$1,
  8693. IfStatement,
  8694. ImportDeclaration,
  8695. ImportDefaultSpecifier: ImportDefaultSpecifier$1,
  8696. ImportExpression,
  8697. ImportNamespaceSpecifier: ImportNamespaceSpecifier$1,
  8698. ImportSpecifier,
  8699. LabeledStatement,
  8700. Literal,
  8701. LogicalExpression,
  8702. MemberExpression,
  8703. MetaProperty,
  8704. MethodDefinition,
  8705. NewExpression,
  8706. ObjectExpression,
  8707. ObjectPattern,
  8708. PrivateName,
  8709. Program: Program$1,
  8710. Property: Property$1,
  8711. RestElement,
  8712. ReturnStatement: ReturnStatement$1,
  8713. SequenceExpression,
  8714. SpreadElement,
  8715. Super,
  8716. SwitchCase,
  8717. SwitchStatement,
  8718. TaggedTemplateExpression,
  8719. TemplateElement,
  8720. TemplateLiteral,
  8721. ThisExpression,
  8722. ThrowStatement,
  8723. TryStatement,
  8724. UnaryExpression,
  8725. UnknownNode,
  8726. UpdateExpression,
  8727. VariableDeclaration,
  8728. VariableDeclarator,
  8729. WhileStatement,
  8730. YieldExpression
  8731. };
  8732. function getId(m) {
  8733. return m.id;
  8734. }
  8735. function getOriginalLocation(sourcemapChain, location) {
  8736. // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
  8737. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
  8738. while (filteredSourcemapChain.length > 0) {
  8739. const sourcemap = filteredSourcemapChain.pop();
  8740. const line = sourcemap.mappings[location.line - 1];
  8741. let locationFound = false;
  8742. if (line !== undefined) {
  8743. for (const segment of line) {
  8744. if (segment[0] >= location.column) {
  8745. if (segment.length === 1)
  8746. break;
  8747. location = {
  8748. column: segment[3],
  8749. line: segment[2] + 1,
  8750. name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
  8751. source: sourcemap.sources[segment[1]]
  8752. };
  8753. locationFound = true;
  8754. break;
  8755. }
  8756. }
  8757. }
  8758. if (!locationFound) {
  8759. throw new Error("Can't resolve original location of error.");
  8760. }
  8761. }
  8762. return location;
  8763. }
  8764. // AST walker module for Mozilla Parser API compatible trees
  8765. function skipThrough(node, st, c) { c(node, st); }
  8766. function ignore(_node, _st, _c) {}
  8767. // Node walkers.
  8768. var base$1 = {};
  8769. base$1.Program = base$1.BlockStatement = function (node, st, c) {
  8770. for (var i = 0, list = node.body; i < list.length; i += 1)
  8771. {
  8772. var stmt = list[i];
  8773. c(stmt, st, "Statement");
  8774. }
  8775. };
  8776. base$1.Statement = skipThrough;
  8777. base$1.EmptyStatement = ignore;
  8778. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  8779. function (node, st, c) { return c(node.expression, st, "Expression"); };
  8780. base$1.IfStatement = function (node, st, c) {
  8781. c(node.test, st, "Expression");
  8782. c(node.consequent, st, "Statement");
  8783. if (node.alternate) { c(node.alternate, st, "Statement"); }
  8784. };
  8785. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  8786. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  8787. base$1.WithStatement = function (node, st, c) {
  8788. c(node.object, st, "Expression");
  8789. c(node.body, st, "Statement");
  8790. };
  8791. base$1.SwitchStatement = function (node, st, c) {
  8792. c(node.discriminant, st, "Expression");
  8793. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  8794. var cs = list$1[i$1];
  8795. if (cs.test) { c(cs.test, st, "Expression"); }
  8796. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  8797. {
  8798. var cons = list[i];
  8799. c(cons, st, "Statement");
  8800. }
  8801. }
  8802. };
  8803. base$1.SwitchCase = function (node, st, c) {
  8804. if (node.test) { c(node.test, st, "Expression"); }
  8805. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  8806. {
  8807. var cons = list[i];
  8808. c(cons, st, "Statement");
  8809. }
  8810. };
  8811. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  8812. if (node.argument) { c(node.argument, st, "Expression"); }
  8813. };
  8814. base$1.ThrowStatement = base$1.SpreadElement =
  8815. function (node, st, c) { return c(node.argument, st, "Expression"); };
  8816. base$1.TryStatement = function (node, st, c) {
  8817. c(node.block, st, "Statement");
  8818. if (node.handler) { c(node.handler, st); }
  8819. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  8820. };
  8821. base$1.CatchClause = function (node, st, c) {
  8822. if (node.param) { c(node.param, st, "Pattern"); }
  8823. c(node.body, st, "Statement");
  8824. };
  8825. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  8826. c(node.test, st, "Expression");
  8827. c(node.body, st, "Statement");
  8828. };
  8829. base$1.ForStatement = function (node, st, c) {
  8830. if (node.init) { c(node.init, st, "ForInit"); }
  8831. if (node.test) { c(node.test, st, "Expression"); }
  8832. if (node.update) { c(node.update, st, "Expression"); }
  8833. c(node.body, st, "Statement");
  8834. };
  8835. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  8836. c(node.left, st, "ForInit");
  8837. c(node.right, st, "Expression");
  8838. c(node.body, st, "Statement");
  8839. };
  8840. base$1.ForInit = function (node, st, c) {
  8841. if (node.type === "VariableDeclaration") { c(node, st); }
  8842. else { c(node, st, "Expression"); }
  8843. };
  8844. base$1.DebuggerStatement = ignore;
  8845. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  8846. base$1.VariableDeclaration = function (node, st, c) {
  8847. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  8848. {
  8849. var decl = list[i];
  8850. c(decl, st);
  8851. }
  8852. };
  8853. base$1.VariableDeclarator = function (node, st, c) {
  8854. c(node.id, st, "Pattern");
  8855. if (node.init) { c(node.init, st, "Expression"); }
  8856. };
  8857. base$1.Function = function (node, st, c) {
  8858. if (node.id) { c(node.id, st, "Pattern"); }
  8859. for (var i = 0, list = node.params; i < list.length; i += 1)
  8860. {
  8861. var param = list[i];
  8862. c(param, st, "Pattern");
  8863. }
  8864. c(node.body, st, node.expression ? "Expression" : "Statement");
  8865. };
  8866. base$1.Pattern = function (node, st, c) {
  8867. if (node.type === "Identifier")
  8868. { c(node, st, "VariablePattern"); }
  8869. else if (node.type === "MemberExpression")
  8870. { c(node, st, "MemberPattern"); }
  8871. else
  8872. { c(node, st); }
  8873. };
  8874. base$1.VariablePattern = ignore;
  8875. base$1.MemberPattern = skipThrough;
  8876. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  8877. base$1.ArrayPattern = function (node, st, c) {
  8878. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  8879. var elt = list[i];
  8880. if (elt) { c(elt, st, "Pattern"); }
  8881. }
  8882. };
  8883. base$1.ObjectPattern = function (node, st, c) {
  8884. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  8885. var prop = list[i];
  8886. if (prop.type === "Property") {
  8887. if (prop.computed) { c(prop.key, st, "Expression"); }
  8888. c(prop.value, st, "Pattern");
  8889. } else if (prop.type === "RestElement") {
  8890. c(prop.argument, st, "Pattern");
  8891. }
  8892. }
  8893. };
  8894. base$1.Expression = skipThrough;
  8895. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  8896. base$1.ArrayExpression = function (node, st, c) {
  8897. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  8898. var elt = list[i];
  8899. if (elt) { c(elt, st, "Expression"); }
  8900. }
  8901. };
  8902. base$1.ObjectExpression = function (node, st, c) {
  8903. for (var i = 0, list = node.properties; i < list.length; i += 1)
  8904. {
  8905. var prop = list[i];
  8906. c(prop, st);
  8907. }
  8908. };
  8909. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  8910. base$1.SequenceExpression = function (node, st, c) {
  8911. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  8912. {
  8913. var expr = list[i];
  8914. c(expr, st, "Expression");
  8915. }
  8916. };
  8917. base$1.TemplateLiteral = function (node, st, c) {
  8918. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  8919. {
  8920. var quasi = list[i];
  8921. c(quasi, st);
  8922. }
  8923. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  8924. {
  8925. var expr = list$1[i$1];
  8926. c(expr, st, "Expression");
  8927. }
  8928. };
  8929. base$1.TemplateElement = ignore;
  8930. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  8931. c(node.argument, st, "Expression");
  8932. };
  8933. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  8934. c(node.left, st, "Expression");
  8935. c(node.right, st, "Expression");
  8936. };
  8937. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  8938. c(node.left, st, "Pattern");
  8939. c(node.right, st, "Expression");
  8940. };
  8941. base$1.ConditionalExpression = function (node, st, c) {
  8942. c(node.test, st, "Expression");
  8943. c(node.consequent, st, "Expression");
  8944. c(node.alternate, st, "Expression");
  8945. };
  8946. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  8947. c(node.callee, st, "Expression");
  8948. if (node.arguments)
  8949. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  8950. {
  8951. var arg = list[i];
  8952. c(arg, st, "Expression");
  8953. } }
  8954. };
  8955. base$1.MemberExpression = function (node, st, c) {
  8956. c(node.object, st, "Expression");
  8957. if (node.computed) { c(node.property, st, "Expression"); }
  8958. };
  8959. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  8960. if (node.declaration)
  8961. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  8962. if (node.source) { c(node.source, st, "Expression"); }
  8963. };
  8964. base$1.ExportAllDeclaration = function (node, st, c) {
  8965. if (node.exported)
  8966. { c(node.exported, st); }
  8967. c(node.source, st, "Expression");
  8968. };
  8969. base$1.ImportDeclaration = function (node, st, c) {
  8970. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  8971. {
  8972. var spec = list[i];
  8973. c(spec, st);
  8974. }
  8975. c(node.source, st, "Expression");
  8976. };
  8977. base$1.ImportExpression = function (node, st, c) {
  8978. c(node.source, st, "Expression");
  8979. };
  8980. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
  8981. base$1.TaggedTemplateExpression = function (node, st, c) {
  8982. c(node.tag, st, "Expression");
  8983. c(node.quasi, st, "Expression");
  8984. };
  8985. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  8986. base$1.Class = function (node, st, c) {
  8987. if (node.id) { c(node.id, st, "Pattern"); }
  8988. if (node.superClass) { c(node.superClass, st, "Expression"); }
  8989. c(node.body, st);
  8990. };
  8991. base$1.ClassBody = function (node, st, c) {
  8992. for (var i = 0, list = node.body; i < list.length; i += 1)
  8993. {
  8994. var elt = list[i];
  8995. c(elt, st);
  8996. }
  8997. };
  8998. base$1.MethodDefinition = base$1.Property = function (node, st, c) {
  8999. if (node.computed) { c(node.key, st, "Expression"); }
  9000. c(node.value, st, "Expression");
  9001. };
  9002. // @ts-ignore
  9003. // patch up acorn-walk until class-fields are officially supported
  9004. base$1.FieldDefinition = function (node, st, c) {
  9005. if (node.computed) {
  9006. c(node.key, st, 'Expression');
  9007. }
  9008. if (node.value) {
  9009. c(node.value, st, 'Expression');
  9010. }
  9011. };
  9012. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  9013. let commentNode = state.commentNodes[state.commentIndex];
  9014. while (commentNode && node.start >= commentNode.end) {
  9015. markPureNode(node, commentNode);
  9016. commentNode = state.commentNodes[++state.commentIndex];
  9017. }
  9018. if (commentNode && commentNode.end <= node.end) {
  9019. base$1[type](node, state, handlePureAnnotationsOfNode);
  9020. }
  9021. }
  9022. function markPureNode(node, comment) {
  9023. if (node.annotations) {
  9024. node.annotations.push(comment);
  9025. }
  9026. else {
  9027. node.annotations = [comment];
  9028. }
  9029. if (node.type === 'ExpressionStatement') {
  9030. node = node.expression;
  9031. }
  9032. if (node.type === 'CallExpression' || node.type === 'NewExpression') {
  9033. node.annotatedPure = true;
  9034. }
  9035. }
  9036. const pureCommentRegex = /[@#]__PURE__/;
  9037. const isPureComment = (comment) => pureCommentRegex.test(comment.text);
  9038. function markPureCallExpressions(comments, esTreeAst) {
  9039. handlePureAnnotationsOfNode(esTreeAst, {
  9040. commentIndex: 0,
  9041. commentNodes: comments.filter(isPureComment)
  9042. });
  9043. }
  9044. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  9045. // this for an actual sourceMappingURL
  9046. let SOURCEMAPPING_URL = 'sourceMa';
  9047. SOURCEMAPPING_URL += 'ppingURL';
  9048. const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
  9049. const NOOP = () => { };
  9050. let getStartTime = () => [0, 0];
  9051. let getElapsedTime = () => 0;
  9052. let getMemory = () => 0;
  9053. let timers = {};
  9054. const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
  9055. function setTimeHelpers() {
  9056. if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
  9057. getStartTime = process.hrtime.bind(process);
  9058. getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
  9059. }
  9060. else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
  9061. getStartTime = () => [performance.now(), 0];
  9062. getElapsedTime = previous => performance.now() - previous[0];
  9063. }
  9064. if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
  9065. getMemory = () => process.memoryUsage().heapUsed;
  9066. }
  9067. }
  9068. function getPersistedLabel(label, level) {
  9069. switch (level) {
  9070. case 1:
  9071. return `# ${label}`;
  9072. case 2:
  9073. return `## ${label}`;
  9074. case 3:
  9075. return label;
  9076. default:
  9077. return `${' '.repeat(level - 4)}- ${label}`;
  9078. }
  9079. }
  9080. function timeStartImpl(label, level = 3) {
  9081. label = getPersistedLabel(label, level);
  9082. if (!timers.hasOwnProperty(label)) {
  9083. timers[label] = {
  9084. memory: 0,
  9085. startMemory: undefined,
  9086. startTime: undefined,
  9087. time: 0,
  9088. totalMemory: 0
  9089. };
  9090. }
  9091. const currentMemory = getMemory();
  9092. timers[label].startTime = getStartTime();
  9093. timers[label].startMemory = currentMemory;
  9094. }
  9095. function timeEndImpl(label, level = 3) {
  9096. label = getPersistedLabel(label, level);
  9097. if (timers.hasOwnProperty(label)) {
  9098. const currentMemory = getMemory();
  9099. timers[label].time += getElapsedTime(timers[label].startTime);
  9100. timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
  9101. timers[label].memory += currentMemory - timers[label].startMemory;
  9102. }
  9103. }
  9104. function getTimings() {
  9105. const newTimings = {};
  9106. for (const label of Object.keys(timers)) {
  9107. newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
  9108. }
  9109. return newTimings;
  9110. }
  9111. let timeStart = NOOP, timeEnd = NOOP;
  9112. const TIMED_PLUGIN_HOOKS = {
  9113. load: true,
  9114. resolveDynamicImport: true,
  9115. resolveId: true,
  9116. transform: true
  9117. };
  9118. function getPluginWithTimers(plugin, index) {
  9119. const timedPlugin = {};
  9120. for (const hook of Object.keys(plugin)) {
  9121. if (TIMED_PLUGIN_HOOKS[hook] === true) {
  9122. let timerLabel = `plugin ${index}`;
  9123. if (plugin.name) {
  9124. timerLabel += ` (${plugin.name})`;
  9125. }
  9126. timerLabel += ` - ${hook}`;
  9127. timedPlugin[hook] = function () {
  9128. timeStart(timerLabel, 4);
  9129. const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
  9130. timeEnd(timerLabel, 4);
  9131. if (result && typeof result.then === 'function') {
  9132. timeStart(`${timerLabel} (async)`, 4);
  9133. result.then(() => timeEnd(`${timerLabel} (async)`, 4));
  9134. }
  9135. return result;
  9136. };
  9137. }
  9138. else {
  9139. timedPlugin[hook] = plugin[hook];
  9140. }
  9141. }
  9142. return timedPlugin;
  9143. }
  9144. function initialiseTimers(inputOptions) {
  9145. if (inputOptions.perf) {
  9146. timers = {};
  9147. setTimeHelpers();
  9148. timeStart = timeStartImpl;
  9149. timeEnd = timeEndImpl;
  9150. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  9151. }
  9152. else {
  9153. timeStart = NOOP;
  9154. timeEnd = NOOP;
  9155. }
  9156. }
  9157. function tryParse(module, Parser, acornOptions) {
  9158. try {
  9159. return Parser.parse(module.info.code, {
  9160. ...acornOptions,
  9161. onComment: (block, text, start, end) => module.comments.push({ block, text, start, end })
  9162. });
  9163. }
  9164. catch (err) {
  9165. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  9166. if (module.id.endsWith('.json')) {
  9167. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  9168. }
  9169. else if (!module.id.endsWith('.js')) {
  9170. message += ' (Note that you need plugins to import files that are not JavaScript)';
  9171. }
  9172. return module.error({
  9173. code: 'PARSE_ERROR',
  9174. message,
  9175. parserError: err
  9176. }, err.pos);
  9177. }
  9178. }
  9179. function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
  9180. return importingModule.error({
  9181. code: 'MISSING_EXPORT',
  9182. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule.id)}`,
  9183. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  9184. }, importerStart);
  9185. }
  9186. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  9187. identifier: null,
  9188. localName: MISSING_EXPORT_SHIM_VARIABLE
  9189. };
  9190. function getVariableForExportNameRecursive(target, name, isExportAllSearch, searchedNamesAndModules = new Map()) {
  9191. const searchedModules = searchedNamesAndModules.get(name);
  9192. if (searchedModules) {
  9193. if (searchedModules.has(target)) {
  9194. return null;
  9195. }
  9196. searchedModules.add(target);
  9197. }
  9198. else {
  9199. searchedNamesAndModules.set(name, new Set([target]));
  9200. }
  9201. return target.getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules);
  9202. }
  9203. class Module {
  9204. constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
  9205. this.graph = graph;
  9206. this.id = id;
  9207. this.options = options;
  9208. this.ast = null;
  9209. this.chunkFileNames = new Set();
  9210. this.chunkName = null;
  9211. this.comments = [];
  9212. this.dependencies = new Set();
  9213. this.dynamicDependencies = new Set();
  9214. this.dynamicImporters = [];
  9215. this.dynamicImports = [];
  9216. this.execIndex = Infinity;
  9217. this.exportAllSources = new Set();
  9218. this.exports = Object.create(null);
  9219. this.exportsAll = Object.create(null);
  9220. this.implicitlyLoadedAfter = new Set();
  9221. this.implicitlyLoadedBefore = new Set();
  9222. this.importDescriptions = Object.create(null);
  9223. this.importers = [];
  9224. this.importMetas = [];
  9225. this.imports = new Set();
  9226. this.includedDynamicImporters = [];
  9227. this.isExecuted = false;
  9228. this.isUserDefinedEntryPoint = false;
  9229. this.preserveSignature = this.options.preserveEntrySignatures;
  9230. this.reexportDescriptions = Object.create(null);
  9231. this.sources = new Set();
  9232. this.userChunkNames = new Set();
  9233. this.usesTopLevelAwait = false;
  9234. this.allExportNames = null;
  9235. this.exportAllModules = [];
  9236. this.exportNamesByVariable = null;
  9237. this.exportShimVariable = new ExportShimVariable(this);
  9238. this.relevantDependencies = null;
  9239. this.syntheticExports = new Map();
  9240. this.syntheticNamespace = null;
  9241. this.transformDependencies = [];
  9242. this.transitiveReexports = null;
  9243. this.excludeFromSourcemap = /\0/.test(id);
  9244. this.context = options.moduleContext(id);
  9245. const module = this;
  9246. this.info = {
  9247. ast: null,
  9248. code: null,
  9249. get dynamicallyImportedIds() {
  9250. const dynamicallyImportedIds = [];
  9251. for (const { resolution } of module.dynamicImports) {
  9252. if (resolution instanceof Module || resolution instanceof ExternalModule) {
  9253. dynamicallyImportedIds.push(resolution.id);
  9254. }
  9255. }
  9256. return dynamicallyImportedIds;
  9257. },
  9258. get dynamicImporters() {
  9259. return module.dynamicImporters.sort();
  9260. },
  9261. hasModuleSideEffects,
  9262. id,
  9263. get implicitlyLoadedAfterOneOf() {
  9264. return Array.from(module.implicitlyLoadedAfter, getId);
  9265. },
  9266. get implicitlyLoadedBefore() {
  9267. return Array.from(module.implicitlyLoadedBefore, getId);
  9268. },
  9269. get importedIds() {
  9270. return Array.from(module.sources, source => module.resolvedIds[source].id);
  9271. },
  9272. get importers() {
  9273. return module.importers.sort();
  9274. },
  9275. isEntry,
  9276. isExternal: false,
  9277. meta,
  9278. syntheticNamedExports
  9279. };
  9280. }
  9281. basename() {
  9282. const base = basename(this.id);
  9283. const ext = extname(this.id);
  9284. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  9285. }
  9286. bindReferences() {
  9287. this.ast.bind();
  9288. }
  9289. error(props, pos) {
  9290. this.addLocationToLogProps(props, pos);
  9291. return error(props);
  9292. }
  9293. getAllExportNames() {
  9294. if (this.allExportNames) {
  9295. return this.allExportNames;
  9296. }
  9297. const allExportNames = (this.allExportNames = new Set());
  9298. for (const name of Object.keys(this.exports)) {
  9299. allExportNames.add(name);
  9300. }
  9301. for (const name of Object.keys(this.reexportDescriptions)) {
  9302. allExportNames.add(name);
  9303. }
  9304. for (const module of this.exportAllModules) {
  9305. if (module instanceof ExternalModule) {
  9306. allExportNames.add(`*${module.id}`);
  9307. continue;
  9308. }
  9309. for (const name of module.getAllExportNames()) {
  9310. if (name !== 'default')
  9311. allExportNames.add(name);
  9312. }
  9313. }
  9314. return allExportNames;
  9315. }
  9316. getDependenciesToBeIncluded() {
  9317. if (this.relevantDependencies)
  9318. return this.relevantDependencies;
  9319. const relevantDependencies = new Set();
  9320. const additionalSideEffectModules = new Set();
  9321. const possibleDependencies = new Set(this.dependencies);
  9322. let dependencyVariables = this.imports;
  9323. if (this.info.isEntry ||
  9324. this.includedDynamicImporters.length > 0 ||
  9325. this.namespace.included ||
  9326. this.implicitlyLoadedAfter.size > 0) {
  9327. dependencyVariables = new Set(dependencyVariables);
  9328. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  9329. dependencyVariables.add(this.getVariableForExportName(exportName));
  9330. }
  9331. }
  9332. for (let variable of dependencyVariables) {
  9333. if (variable instanceof SyntheticNamedExportVariable) {
  9334. variable = variable.getBaseVariable();
  9335. }
  9336. else if (variable instanceof ExportDefaultVariable) {
  9337. const { modules, original } = variable.getOriginalVariableAndDeclarationModules();
  9338. variable = original;
  9339. for (const module of modules) {
  9340. additionalSideEffectModules.add(module);
  9341. possibleDependencies.add(module);
  9342. }
  9343. }
  9344. relevantDependencies.add(variable.module);
  9345. }
  9346. if (this.options.treeshake && this.info.hasModuleSideEffects !== 'no-treeshake') {
  9347. for (const dependency of possibleDependencies) {
  9348. if (!(dependency.info.hasModuleSideEffects ||
  9349. additionalSideEffectModules.has(dependency)) ||
  9350. relevantDependencies.has(dependency)) {
  9351. continue;
  9352. }
  9353. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  9354. relevantDependencies.add(dependency);
  9355. }
  9356. else {
  9357. for (const transitiveDependency of dependency.dependencies) {
  9358. possibleDependencies.add(transitiveDependency);
  9359. }
  9360. }
  9361. }
  9362. }
  9363. else {
  9364. for (const dependency of this.dependencies) {
  9365. relevantDependencies.add(dependency);
  9366. }
  9367. }
  9368. return (this.relevantDependencies = relevantDependencies);
  9369. }
  9370. getExportNamesByVariable() {
  9371. if (this.exportNamesByVariable) {
  9372. return this.exportNamesByVariable;
  9373. }
  9374. const exportNamesByVariable = new Map();
  9375. for (const exportName of this.getAllExportNames()) {
  9376. if (exportName === this.info.syntheticNamedExports)
  9377. continue;
  9378. let tracedVariable = this.getVariableForExportName(exportName);
  9379. if (tracedVariable instanceof ExportDefaultVariable) {
  9380. tracedVariable = tracedVariable.getOriginalVariable();
  9381. }
  9382. if (!tracedVariable ||
  9383. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  9384. continue;
  9385. }
  9386. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  9387. if (existingExportNames) {
  9388. existingExportNames.push(exportName);
  9389. }
  9390. else {
  9391. exportNamesByVariable.set(tracedVariable, [exportName]);
  9392. }
  9393. }
  9394. return (this.exportNamesByVariable = exportNamesByVariable);
  9395. }
  9396. getExports() {
  9397. return Object.keys(this.exports);
  9398. }
  9399. getReexports() {
  9400. if (this.transitiveReexports) {
  9401. return this.transitiveReexports;
  9402. }
  9403. // to avoid infinite recursion when using circular `export * from X`
  9404. this.transitiveReexports = [];
  9405. const reexports = new Set();
  9406. for (const name in this.reexportDescriptions) {
  9407. reexports.add(name);
  9408. }
  9409. for (const module of this.exportAllModules) {
  9410. if (module instanceof ExternalModule) {
  9411. reexports.add(`*${module.id}`);
  9412. }
  9413. else {
  9414. for (const name of [...module.getReexports(), ...module.getExports()]) {
  9415. if (name !== 'default')
  9416. reexports.add(name);
  9417. }
  9418. }
  9419. }
  9420. return (this.transitiveReexports = [...reexports]);
  9421. }
  9422. getRenderedExports() {
  9423. // only direct exports are counted here, not reexports at all
  9424. const renderedExports = [];
  9425. const removedExports = [];
  9426. for (const exportName in this.exports) {
  9427. const variable = this.getVariableForExportName(exportName);
  9428. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  9429. }
  9430. return { renderedExports, removedExports };
  9431. }
  9432. getSyntheticNamespace() {
  9433. if (this.syntheticNamespace === null) {
  9434. this.syntheticNamespace = undefined;
  9435. this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  9436. ? this.info.syntheticNamedExports
  9437. : 'default');
  9438. }
  9439. if (!this.syntheticNamespace) {
  9440. return error({
  9441. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  9442. id: this.id,
  9443. message: `Module "${relativeId(this.id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(this.info.syntheticNamedExports)}' needs ${typeof this.info.syntheticNamedExports === 'string' &&
  9444. this.info.syntheticNamedExports !== 'default'
  9445. ? `an export named "${this.info.syntheticNamedExports}"`
  9446. : 'a default export'}.`
  9447. });
  9448. }
  9449. return this.syntheticNamespace;
  9450. }
  9451. getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules) {
  9452. if (name[0] === '*') {
  9453. if (name.length === 1) {
  9454. return this.namespace;
  9455. }
  9456. else {
  9457. // export * from 'external'
  9458. const module = this.graph.modulesById.get(name.slice(1));
  9459. return module.getVariableForExportName('*');
  9460. }
  9461. }
  9462. // export { foo } from './other'
  9463. const reexportDeclaration = this.reexportDescriptions[name];
  9464. if (reexportDeclaration) {
  9465. const declaration = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, false, searchedNamesAndModules);
  9466. if (!declaration) {
  9467. return handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
  9468. }
  9469. return declaration;
  9470. }
  9471. const exportDeclaration = this.exports[name];
  9472. if (exportDeclaration) {
  9473. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  9474. return this.exportShimVariable;
  9475. }
  9476. const name = exportDeclaration.localName;
  9477. return this.traceVariable(name);
  9478. }
  9479. if (name !== 'default') {
  9480. for (const module of this.exportAllModules) {
  9481. const declaration = getVariableForExportNameRecursive(module, name, true, searchedNamesAndModules);
  9482. if (declaration)
  9483. return declaration;
  9484. }
  9485. }
  9486. // we don't want to create shims when we are just
  9487. // probing export * modules for exports
  9488. if (!isExportAllSearch) {
  9489. if (this.info.syntheticNamedExports) {
  9490. let syntheticExport = this.syntheticExports.get(name);
  9491. if (!syntheticExport) {
  9492. const syntheticNamespace = this.getSyntheticNamespace();
  9493. syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
  9494. this.syntheticExports.set(name, syntheticExport);
  9495. return syntheticExport;
  9496. }
  9497. return syntheticExport;
  9498. }
  9499. if (this.options.shimMissingExports) {
  9500. this.shimMissingExport(name);
  9501. return this.exportShimVariable;
  9502. }
  9503. }
  9504. return null;
  9505. }
  9506. hasEffects() {
  9507. return (this.info.hasModuleSideEffects === 'no-treeshake' ||
  9508. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  9509. }
  9510. include() {
  9511. const context = createInclusionContext();
  9512. if (this.ast.shouldBeIncluded(context))
  9513. this.ast.include(context, false);
  9514. }
  9515. includeAllExports(includeNamespaceMembers) {
  9516. if (!this.isExecuted) {
  9517. this.graph.needsTreeshakingPass = true;
  9518. markModuleAndImpureDependenciesAsExecuted(this);
  9519. }
  9520. for (const exportName of this.getExports()) {
  9521. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  9522. const variable = this.getVariableForExportName(exportName);
  9523. variable.deoptimizePath(UNKNOWN_PATH);
  9524. if (!variable.included) {
  9525. variable.include();
  9526. this.graph.needsTreeshakingPass = true;
  9527. }
  9528. }
  9529. }
  9530. for (const name of this.getReexports()) {
  9531. const variable = this.getVariableForExportName(name);
  9532. variable.deoptimizePath(UNKNOWN_PATH);
  9533. if (!variable.included) {
  9534. variable.include();
  9535. this.graph.needsTreeshakingPass = true;
  9536. }
  9537. if (variable instanceof ExternalVariable) {
  9538. variable.module.reexported = true;
  9539. }
  9540. }
  9541. if (includeNamespaceMembers) {
  9542. this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
  9543. }
  9544. }
  9545. includeAllInBundle() {
  9546. this.ast.include(createInclusionContext(), true);
  9547. }
  9548. isIncluded() {
  9549. return this.ast.included || this.namespace.included;
  9550. }
  9551. linkImports() {
  9552. this.addModulesToImportDescriptions(this.importDescriptions);
  9553. this.addModulesToImportDescriptions(this.reexportDescriptions);
  9554. for (const name in this.exports) {
  9555. if (name !== 'default') {
  9556. this.exportsAll[name] = this.id;
  9557. }
  9558. }
  9559. const externalExportAllModules = [];
  9560. for (const source of this.exportAllSources) {
  9561. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  9562. if (module instanceof ExternalModule) {
  9563. externalExportAllModules.push(module);
  9564. continue;
  9565. }
  9566. this.exportAllModules.push(module);
  9567. for (const name in module.exportsAll) {
  9568. if (name in this.exportsAll) {
  9569. this.options.onwarn(errNamespaceConflict(name, this, module));
  9570. }
  9571. else {
  9572. this.exportsAll[name] = module.exportsAll[name];
  9573. }
  9574. }
  9575. }
  9576. this.exportAllModules.push(...externalExportAllModules);
  9577. }
  9578. render(options) {
  9579. const magicString = this.magicString.clone();
  9580. this.ast.render(magicString, options);
  9581. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  9582. return magicString;
  9583. }
  9584. setSource({ alwaysRemovedCode, ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  9585. this.info.code = code;
  9586. this.originalCode = originalCode;
  9587. this.originalSourcemap = originalSourcemap;
  9588. this.sourcemapChain = sourcemapChain;
  9589. if (transformFiles) {
  9590. this.transformFiles = transformFiles;
  9591. }
  9592. this.transformDependencies = transformDependencies;
  9593. this.customTransformCache = customTransformCache;
  9594. this.updateOptions(moduleOptions);
  9595. timeStart('generate ast', 3);
  9596. this.alwaysRemovedCode = alwaysRemovedCode || [];
  9597. if (!ast) {
  9598. ast = tryParse(this, this.graph.acornParser, this.options.acorn);
  9599. for (const comment of this.comments) {
  9600. if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
  9601. this.alwaysRemovedCode.push([comment.start, comment.end]);
  9602. }
  9603. }
  9604. markPureCallExpressions(this.comments, ast);
  9605. }
  9606. timeEnd('generate ast', 3);
  9607. this.resolvedIds = resolvedIds || Object.create(null);
  9608. // By default, `id` is the file name. Custom resolvers and loaders
  9609. // can change that, but it makes sense to use it for the source file name
  9610. const fileName = this.id;
  9611. this.magicString = new MagicString(code, {
  9612. filename: (this.excludeFromSourcemap ? null : fileName),
  9613. indentExclusionRanges: []
  9614. });
  9615. for (const [start, end] of this.alwaysRemovedCode) {
  9616. this.magicString.remove(start, end);
  9617. }
  9618. timeStart('analyse ast', 3);
  9619. this.astContext = {
  9620. addDynamicImport: this.addDynamicImport.bind(this),
  9621. addExport: this.addExport.bind(this),
  9622. addImport: this.addImport.bind(this),
  9623. addImportMeta: this.addImportMeta.bind(this),
  9624. code,
  9625. deoptimizationTracker: this.graph.deoptimizationTracker,
  9626. error: this.error.bind(this),
  9627. fileName,
  9628. getExports: this.getExports.bind(this),
  9629. getModuleExecIndex: () => this.execIndex,
  9630. getModuleName: this.basename.bind(this),
  9631. getReexports: this.getReexports.bind(this),
  9632. importDescriptions: this.importDescriptions,
  9633. includeAllExports: () => this.includeAllExports(true),
  9634. includeDynamicImport: this.includeDynamicImport.bind(this),
  9635. includeVariable: this.includeVariable.bind(this),
  9636. magicString: this.magicString,
  9637. module: this,
  9638. moduleContext: this.context,
  9639. nodeConstructors,
  9640. options: this.options,
  9641. traceExport: this.getVariableForExportName.bind(this),
  9642. traceVariable: this.traceVariable.bind(this),
  9643. usesTopLevelAwait: false,
  9644. warn: this.warn.bind(this)
  9645. };
  9646. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  9647. this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
  9648. this.ast = new Program$1(ast, { type: 'Module', context: this.astContext }, this.scope);
  9649. this.info.ast = ast;
  9650. timeEnd('analyse ast', 3);
  9651. }
  9652. toJSON() {
  9653. return {
  9654. alwaysRemovedCode: this.alwaysRemovedCode,
  9655. ast: this.ast.esTreeNode,
  9656. code: this.info.code,
  9657. customTransformCache: this.customTransformCache,
  9658. dependencies: Array.from(this.dependencies, getId),
  9659. id: this.id,
  9660. meta: this.info.meta,
  9661. moduleSideEffects: this.info.hasModuleSideEffects,
  9662. originalCode: this.originalCode,
  9663. originalSourcemap: this.originalSourcemap,
  9664. resolvedIds: this.resolvedIds,
  9665. sourcemapChain: this.sourcemapChain,
  9666. syntheticNamedExports: this.info.syntheticNamedExports,
  9667. transformDependencies: this.transformDependencies,
  9668. transformFiles: this.transformFiles
  9669. };
  9670. }
  9671. traceVariable(name) {
  9672. const localVariable = this.scope.variables.get(name);
  9673. if (localVariable) {
  9674. return localVariable;
  9675. }
  9676. if (name in this.importDescriptions) {
  9677. const importDeclaration = this.importDescriptions[name];
  9678. const otherModule = importDeclaration.module;
  9679. if (otherModule instanceof Module && importDeclaration.name === '*') {
  9680. return otherModule.namespace;
  9681. }
  9682. const declaration = otherModule.getVariableForExportName(importDeclaration.name);
  9683. if (!declaration) {
  9684. return handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
  9685. }
  9686. return declaration;
  9687. }
  9688. return null;
  9689. }
  9690. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  9691. if (moduleSideEffects != null) {
  9692. this.info.hasModuleSideEffects = moduleSideEffects;
  9693. }
  9694. if (syntheticNamedExports != null) {
  9695. this.info.syntheticNamedExports = syntheticNamedExports;
  9696. }
  9697. if (meta != null) {
  9698. this.info.meta = { ...this.info.meta, ...meta };
  9699. }
  9700. }
  9701. warn(props, pos) {
  9702. this.addLocationToLogProps(props, pos);
  9703. this.options.onwarn(props);
  9704. }
  9705. addDynamicImport(node) {
  9706. let argument = node.source;
  9707. if (argument instanceof TemplateLiteral) {
  9708. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  9709. argument = argument.quasis[0].value.cooked;
  9710. }
  9711. }
  9712. else if (argument instanceof Literal && typeof argument.value === 'string') {
  9713. argument = argument.value;
  9714. }
  9715. this.dynamicImports.push({ node, resolution: null, argument });
  9716. }
  9717. addExport(node) {
  9718. if (node instanceof ExportDefaultDeclaration) {
  9719. // export default foo;
  9720. this.exports.default = {
  9721. identifier: node.variable.getAssignedVariableName(),
  9722. localName: 'default'
  9723. };
  9724. }
  9725. else if (node instanceof ExportAllDeclaration) {
  9726. const source = node.source.value;
  9727. this.sources.add(source);
  9728. if (node.exported) {
  9729. // export * as name from './other'
  9730. const name = node.exported.name;
  9731. this.reexportDescriptions[name] = {
  9732. localName: '*',
  9733. module: null,
  9734. source,
  9735. start: node.start
  9736. };
  9737. }
  9738. else {
  9739. // export * from './other'
  9740. this.exportAllSources.add(source);
  9741. }
  9742. }
  9743. else if (node.source instanceof Literal) {
  9744. // export { name } from './other'
  9745. const source = node.source.value;
  9746. this.sources.add(source);
  9747. for (const specifier of node.specifiers) {
  9748. const name = specifier.exported.name;
  9749. this.reexportDescriptions[name] = {
  9750. localName: specifier.local.name,
  9751. module: null,
  9752. source,
  9753. start: specifier.start
  9754. };
  9755. }
  9756. }
  9757. else if (node.declaration) {
  9758. const declaration = node.declaration;
  9759. if (declaration instanceof VariableDeclaration) {
  9760. // export var { foo, bar } = ...
  9761. // export var foo = 1, bar = 2;
  9762. for (const declarator of declaration.declarations) {
  9763. for (const localName of extractAssignedNames(declarator.id)) {
  9764. this.exports[localName] = { identifier: null, localName };
  9765. }
  9766. }
  9767. }
  9768. else {
  9769. // export function foo () {}
  9770. const localName = declaration.id.name;
  9771. this.exports[localName] = { identifier: null, localName };
  9772. }
  9773. }
  9774. else {
  9775. // export { foo, bar, baz }
  9776. for (const specifier of node.specifiers) {
  9777. const localName = specifier.local.name;
  9778. const exportedName = specifier.exported.name;
  9779. this.exports[exportedName] = { identifier: null, localName };
  9780. }
  9781. }
  9782. }
  9783. addImport(node) {
  9784. const source = node.source.value;
  9785. this.sources.add(source);
  9786. for (const specifier of node.specifiers) {
  9787. const isDefault = specifier.type === ImportDefaultSpecifier;
  9788. const isNamespace = specifier.type === ImportNamespaceSpecifier;
  9789. const name = isDefault
  9790. ? 'default'
  9791. : isNamespace
  9792. ? '*'
  9793. : specifier.imported.name;
  9794. this.importDescriptions[specifier.local.name] = {
  9795. module: null,
  9796. name,
  9797. source,
  9798. start: specifier.start
  9799. };
  9800. }
  9801. }
  9802. addImportMeta(node) {
  9803. this.importMetas.push(node);
  9804. }
  9805. addLocationToLogProps(props, pos) {
  9806. props.id = this.id;
  9807. props.pos = pos;
  9808. let code = this.info.code;
  9809. let { column, line } = locate(code, pos, { offsetLine: 1 });
  9810. try {
  9811. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  9812. code = this.originalCode;
  9813. }
  9814. catch (e) {
  9815. this.options.onwarn({
  9816. code: 'SOURCEMAP_ERROR',
  9817. id: this.id,
  9818. loc: {
  9819. column,
  9820. file: this.id,
  9821. line
  9822. },
  9823. message: `Error when using sourcemap for reporting an error: ${e.message}`,
  9824. pos
  9825. });
  9826. }
  9827. augmentCodeLocation(props, { column, line }, code, this.id);
  9828. }
  9829. addModulesToImportDescriptions(importDescription) {
  9830. for (const name of Object.keys(importDescription)) {
  9831. const specifier = importDescription[name];
  9832. const id = this.resolvedIds[specifier.source].id;
  9833. specifier.module = this.graph.modulesById.get(id);
  9834. }
  9835. }
  9836. includeAndGetAdditionalMergedNamespaces() {
  9837. const mergedNamespaces = [];
  9838. for (const module of this.exportAllModules) {
  9839. if (module instanceof ExternalModule) {
  9840. const externalVariable = module.getVariableForExportName('*');
  9841. externalVariable.include();
  9842. this.imports.add(externalVariable);
  9843. mergedNamespaces.push(externalVariable);
  9844. }
  9845. else if (module.info.syntheticNamedExports) {
  9846. const syntheticNamespace = module.getSyntheticNamespace();
  9847. syntheticNamespace.include();
  9848. this.imports.add(syntheticNamespace);
  9849. mergedNamespaces.push(syntheticNamespace);
  9850. }
  9851. }
  9852. return mergedNamespaces;
  9853. }
  9854. includeDynamicImport(node) {
  9855. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  9856. if (resolution instanceof Module) {
  9857. resolution.includedDynamicImporters.push(this);
  9858. resolution.includeAllExports(true);
  9859. }
  9860. }
  9861. includeVariable(variable) {
  9862. const variableModule = variable.module;
  9863. if (!variable.included) {
  9864. variable.include();
  9865. this.graph.needsTreeshakingPass = true;
  9866. }
  9867. if (variableModule && variableModule !== this) {
  9868. this.imports.add(variable);
  9869. }
  9870. }
  9871. shimMissingExport(name) {
  9872. this.options.onwarn({
  9873. code: 'SHIMMED_EXPORT',
  9874. exporter: relativeId(this.id),
  9875. exportName: name,
  9876. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  9877. });
  9878. this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
  9879. }
  9880. }
  9881. class Source {
  9882. constructor(filename, content) {
  9883. this.isOriginal = true;
  9884. this.filename = filename;
  9885. this.content = content;
  9886. }
  9887. traceSegment(line, column, name) {
  9888. return { line, column, name, source: this };
  9889. }
  9890. }
  9891. class Link {
  9892. constructor(map, sources) {
  9893. this.sources = sources;
  9894. this.names = map.names;
  9895. this.mappings = map.mappings;
  9896. }
  9897. traceMappings() {
  9898. const sources = [];
  9899. const sourcesContent = [];
  9900. const names = [];
  9901. const mappings = [];
  9902. for (const line of this.mappings) {
  9903. const tracedLine = [];
  9904. for (const segment of line) {
  9905. if (segment.length == 1)
  9906. continue;
  9907. const source = this.sources[segment[1]];
  9908. if (!source)
  9909. continue;
  9910. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  9911. if (traced) {
  9912. // newer sources are more likely to be used, so search backwards.
  9913. let sourceIndex = sources.lastIndexOf(traced.source.filename);
  9914. if (sourceIndex === -1) {
  9915. sourceIndex = sources.length;
  9916. sources.push(traced.source.filename);
  9917. sourcesContent[sourceIndex] = traced.source.content;
  9918. }
  9919. else if (sourcesContent[sourceIndex] == null) {
  9920. sourcesContent[sourceIndex] = traced.source.content;
  9921. }
  9922. else if (traced.source.content != null &&
  9923. sourcesContent[sourceIndex] !== traced.source.content) {
  9924. return error({
  9925. message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
  9926. });
  9927. }
  9928. const tracedSegment = [
  9929. segment[0],
  9930. sourceIndex,
  9931. traced.line,
  9932. traced.column
  9933. ];
  9934. if (traced.name) {
  9935. let nameIndex = names.indexOf(traced.name);
  9936. if (nameIndex === -1) {
  9937. nameIndex = names.length;
  9938. names.push(traced.name);
  9939. }
  9940. tracedSegment[4] = nameIndex;
  9941. }
  9942. tracedLine.push(tracedSegment);
  9943. }
  9944. }
  9945. mappings.push(tracedLine);
  9946. }
  9947. return { sources, sourcesContent, names, mappings };
  9948. }
  9949. traceSegment(line, column, name) {
  9950. const segments = this.mappings[line];
  9951. if (!segments)
  9952. return null;
  9953. // binary search through segments for the given column
  9954. let i = 0;
  9955. let j = segments.length - 1;
  9956. while (i <= j) {
  9957. const m = (i + j) >> 1;
  9958. const segment = segments[m];
  9959. if (segment[0] === column) {
  9960. if (segment.length == 1)
  9961. return null;
  9962. const source = this.sources[segment[1]];
  9963. if (!source)
  9964. return null;
  9965. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  9966. }
  9967. if (segment[0] > column) {
  9968. j = m - 1;
  9969. }
  9970. else {
  9971. i = m + 1;
  9972. }
  9973. }
  9974. return null;
  9975. }
  9976. }
  9977. function getLinkMap(warn) {
  9978. return function linkMap(source, map) {
  9979. if (map.mappings) {
  9980. return new Link(map, [source]);
  9981. }
  9982. warn({
  9983. code: 'SOURCEMAP_BROKEN',
  9984. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  9985. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  9986. 'documentation for help',
  9987. plugin: map.plugin,
  9988. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  9989. });
  9990. return new Link({
  9991. mappings: [],
  9992. names: []
  9993. }, [source]);
  9994. };
  9995. }
  9996. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  9997. let source;
  9998. if (!originalSourcemap) {
  9999. source = new Source(id, originalCode);
  10000. }
  10001. else {
  10002. const sources = originalSourcemap.sources;
  10003. const sourcesContent = originalSourcemap.sourcesContent || [];
  10004. const directory = dirname(id) || '.';
  10005. const sourceRoot = originalSourcemap.sourceRoot || '.';
  10006. const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
  10007. source = new Link(originalSourcemap, baseSources);
  10008. }
  10009. return sourcemapChain.reduce(linkMap, source);
  10010. }
  10011. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  10012. const linkMap = getLinkMap(warn);
  10013. const moduleSources = modules
  10014. .filter(module => !module.excludeFromSourcemap)
  10015. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  10016. // DecodedSourceMap (from magic-string) uses a number[] instead of the more
  10017. // correct SourceMapSegment tuples. Cast it here to gain type safety.
  10018. let source = new Link(map, moduleSources);
  10019. source = bundleSourcemapChain.reduce(linkMap, source);
  10020. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  10021. if (file) {
  10022. const directory = dirname(file);
  10023. sources = sources.map((source) => relative$1(directory, source));
  10024. file = basename(file);
  10025. }
  10026. sourcesContent = (excludeContent ? null : sourcesContent);
  10027. return new SourceMap({ file, sources, sourcesContent, names, mappings });
  10028. }
  10029. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  10030. if (!sourcemapChain.length) {
  10031. return originalSourcemap;
  10032. }
  10033. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  10034. const map = source.traceMappings();
  10035. return { version: 3, ...map };
  10036. }
  10037. const createHash = () => createHash$1('sha256');
  10038. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  10039. amd: deconflictImportsOther,
  10040. cjs: deconflictImportsOther,
  10041. es: deconflictImportsEsmOrSystem,
  10042. iife: deconflictImportsOther,
  10043. system: deconflictImportsEsmOrSystem,
  10044. umd: deconflictImportsOther
  10045. };
  10046. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  10047. for (const module of modules) {
  10048. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  10049. }
  10050. deconflictTopLevelVariables(usedNames, modules, includedNamespaces);
  10051. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  10052. for (const module of modules) {
  10053. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10054. }
  10055. }
  10056. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  10057. // This is needed for namespace reexports
  10058. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  10059. if (preserveModules || dependency instanceof ExternalModule) {
  10060. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  10061. }
  10062. }
  10063. for (const variable of imports) {
  10064. const module = variable.module;
  10065. const name = variable.name;
  10066. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  10067. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  10068. }
  10069. else if (module instanceof ExternalModule && name === 'default') {
  10070. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  10071. ? module.suggestedVariableName + '__default'
  10072. : module.suggestedVariableName, usedNames));
  10073. }
  10074. else {
  10075. variable.setRenderNames(null, getSafeName(name, usedNames));
  10076. }
  10077. }
  10078. for (const variable of syntheticExports) {
  10079. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10080. }
  10081. }
  10082. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  10083. for (const chunkOrExternalModule of dependencies) {
  10084. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  10085. }
  10086. for (const externalModuleOrChunk of deconflictedNamespace) {
  10087. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  10088. }
  10089. for (const externalModule of deconflictedDefault) {
  10090. if (deconflictedNamespace.has(externalModule) &&
  10091. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  10092. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  10093. }
  10094. else {
  10095. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  10096. }
  10097. }
  10098. for (const variable of imports) {
  10099. const module = variable.module;
  10100. if (module instanceof ExternalModule) {
  10101. const name = variable.name;
  10102. if (name === 'default') {
  10103. const moduleInterop = String(interop(module.id));
  10104. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  10105. ? module.defaultVariableName
  10106. : module.variableName;
  10107. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  10108. variable.setRenderNames(variableName, 'default');
  10109. }
  10110. else {
  10111. variable.setRenderNames(null, variableName);
  10112. }
  10113. }
  10114. else if (name === '*') {
  10115. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  10116. ? module.namespaceVariableName
  10117. : module.variableName);
  10118. }
  10119. else {
  10120. // if the second parameter is `null`, it uses its "name" for the property name
  10121. variable.setRenderNames(module.variableName, null);
  10122. }
  10123. }
  10124. else {
  10125. const chunk = chunkByModule.get(module);
  10126. if (preserveModules && variable.isNamespace) {
  10127. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  10128. }
  10129. else if (chunk.exportMode === 'default') {
  10130. variable.setRenderNames(null, chunk.variableName);
  10131. }
  10132. else {
  10133. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  10134. }
  10135. }
  10136. }
  10137. }
  10138. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  10139. for (const module of modules) {
  10140. for (const variable of module.scope.variables.values()) {
  10141. if (variable.included &&
  10142. // this will only happen for exports in some formats
  10143. !(variable.renderBaseName ||
  10144. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  10145. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10146. }
  10147. }
  10148. if (includedNamespaces.has(module)) {
  10149. const namespace = module.namespace;
  10150. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  10151. }
  10152. }
  10153. }
  10154. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  10155. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  10156. const backSlashRegEx = /\\/g;
  10157. function escapeId(id) {
  10158. if (!id.match(needsEscapeRegEx))
  10159. return id;
  10160. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  10161. }
  10162. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  10163. function sortByExecutionOrder(units) {
  10164. units.sort(compareExecIndex);
  10165. }
  10166. function analyseModuleExecution(entryModules) {
  10167. let nextExecIndex = 0;
  10168. const cyclePaths = [];
  10169. const analysedModules = new Set();
  10170. const dynamicImports = new Set();
  10171. const parents = new Map();
  10172. const orderedModules = [];
  10173. const analyseModule = (module) => {
  10174. if (module instanceof Module) {
  10175. for (const dependency of module.dependencies) {
  10176. if (parents.has(dependency)) {
  10177. if (!analysedModules.has(dependency)) {
  10178. cyclePaths.push(getCyclePath(dependency, module, parents));
  10179. }
  10180. continue;
  10181. }
  10182. parents.set(dependency, module);
  10183. analyseModule(dependency);
  10184. }
  10185. for (const dependency of module.implicitlyLoadedBefore) {
  10186. dynamicImports.add(dependency);
  10187. }
  10188. for (const { resolution } of module.dynamicImports) {
  10189. if (resolution instanceof Module) {
  10190. dynamicImports.add(resolution);
  10191. }
  10192. }
  10193. orderedModules.push(module);
  10194. }
  10195. module.execIndex = nextExecIndex++;
  10196. analysedModules.add(module);
  10197. };
  10198. for (const curEntry of entryModules) {
  10199. if (!parents.has(curEntry)) {
  10200. parents.set(curEntry, null);
  10201. analyseModule(curEntry);
  10202. }
  10203. }
  10204. for (const curEntry of dynamicImports) {
  10205. if (!parents.has(curEntry)) {
  10206. parents.set(curEntry, null);
  10207. analyseModule(curEntry);
  10208. }
  10209. }
  10210. return { orderedModules, cyclePaths };
  10211. }
  10212. function getCyclePath(module, parent, parents) {
  10213. const path = [relativeId(module.id)];
  10214. let nextModule = parent;
  10215. while (nextModule !== module) {
  10216. path.push(relativeId(nextModule.id));
  10217. nextModule = parents.get(nextModule);
  10218. }
  10219. path.push(path[0]);
  10220. path.reverse();
  10221. return path;
  10222. }
  10223. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  10224. let nameIndex = 0;
  10225. for (const variable of exports) {
  10226. let exportName = variable.name[0];
  10227. if (exportsByName[exportName]) {
  10228. do {
  10229. exportName = toBase64(++nameIndex);
  10230. // skip past leading number identifiers
  10231. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  10232. nameIndex += 9 * 64 ** (exportName.length - 1);
  10233. exportName = toBase64(nameIndex);
  10234. }
  10235. } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
  10236. }
  10237. exportsByName[exportName] = variable;
  10238. exportNamesByVariable.set(variable, [exportName]);
  10239. }
  10240. }
  10241. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  10242. for (const variable of exports) {
  10243. let nameIndex = 0;
  10244. let exportName = variable.name;
  10245. while (exportsByName[exportName]) {
  10246. exportName = variable.name + '$' + ++nameIndex;
  10247. }
  10248. exportsByName[exportName] = variable;
  10249. exportNamesByVariable.set(variable, [exportName]);
  10250. }
  10251. }
  10252. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  10253. const exportKeys = chunk.getExportNames();
  10254. if (exportMode === 'default') {
  10255. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  10256. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  10257. }
  10258. }
  10259. else if (exportMode === 'none' && exportKeys.length) {
  10260. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  10261. }
  10262. if (exportMode === 'auto') {
  10263. if (exportKeys.length === 0) {
  10264. exportMode = 'none';
  10265. }
  10266. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  10267. if (format === 'cjs' && unsetOptions.has('exports')) {
  10268. warn(errPreferNamedExports(facadeModuleId));
  10269. }
  10270. exportMode = 'default';
  10271. }
  10272. else {
  10273. if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
  10274. warn(errMixedExport(facadeModuleId, name));
  10275. }
  10276. exportMode = 'named';
  10277. }
  10278. }
  10279. return exportMode;
  10280. }
  10281. function guessIndentString(code) {
  10282. const lines = code.split('\n');
  10283. const tabbed = lines.filter(line => /^\t+/.test(line));
  10284. const spaced = lines.filter(line => /^ {2,}/.test(line));
  10285. if (tabbed.length === 0 && spaced.length === 0) {
  10286. return null;
  10287. }
  10288. // More lines tabbed than spaced? Assume tabs, and
  10289. // default to tabs in the case of a tie (or nothing
  10290. // to go on)
  10291. if (tabbed.length >= spaced.length) {
  10292. return '\t';
  10293. }
  10294. // Otherwise, we need to guess the multiple
  10295. const min = spaced.reduce((previous, current) => {
  10296. const numSpaces = /^ +/.exec(current)[0].length;
  10297. return Math.min(numSpaces, previous);
  10298. }, Infinity);
  10299. return new Array(min + 1).join(' ');
  10300. }
  10301. function getIndentString(modules, options) {
  10302. if (options.indent !== true)
  10303. return options.indent;
  10304. for (let i = 0; i < modules.length; i++) {
  10305. const indent = guessIndentString(modules[i].originalCode);
  10306. if (indent !== null)
  10307. return indent;
  10308. }
  10309. return '\t';
  10310. }
  10311. function decodedSourcemap(map) {
  10312. if (!map)
  10313. return null;
  10314. if (typeof map === 'string') {
  10315. map = JSON.parse(map);
  10316. }
  10317. if (map.mappings === '') {
  10318. return {
  10319. mappings: [],
  10320. names: [],
  10321. sources: [],
  10322. version: 3
  10323. };
  10324. }
  10325. let mappings;
  10326. if (typeof map.mappings === 'string') {
  10327. mappings = decode(map.mappings);
  10328. }
  10329. else {
  10330. mappings = map.mappings;
  10331. }
  10332. return { ...map, mappings };
  10333. }
  10334. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  10335. const renderChunkReducer = (code, result, plugin) => {
  10336. if (result == null)
  10337. return code;
  10338. if (typeof result === 'string')
  10339. result = {
  10340. code: result,
  10341. map: undefined
  10342. };
  10343. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  10344. if (result.map !== null) {
  10345. const map = decodedSourcemap(result.map);
  10346. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  10347. }
  10348. return result.code;
  10349. };
  10350. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  10351. }
  10352. function renderNamePattern(pattern, patternName, replacements, getFileInfo) {
  10353. if (typeof pattern === 'function') {
  10354. pattern = pattern(getFileInfo());
  10355. }
  10356. if (!isPlainPathFragment(pattern))
  10357. return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
  10358. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  10359. if (!replacements.hasOwnProperty(type)) {
  10360. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  10361. }
  10362. const replacement = replacements[type]();
  10363. if (!isPlainPathFragment(replacement))
  10364. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  10365. return replacement;
  10366. });
  10367. }
  10368. function makeUnique(name, existingNames) {
  10369. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  10370. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  10371. return name;
  10372. const ext = extname(name);
  10373. name = name.substr(0, name.length - ext.length);
  10374. let uniqueName, uniqueIndex = 1;
  10375. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  10376. ;
  10377. return uniqueName;
  10378. }
  10379. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  10380. function getGlobalName(module, globals, hasExports, warn) {
  10381. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  10382. if (globalName) {
  10383. return globalName;
  10384. }
  10385. if (hasExports) {
  10386. warn({
  10387. code: 'MISSING_GLOBAL_NAME',
  10388. guess: module.variableName,
  10389. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  10390. source: module.id
  10391. });
  10392. return module.variableName;
  10393. }
  10394. }
  10395. class Chunk$1 {
  10396. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  10397. this.orderedModules = orderedModules;
  10398. this.inputOptions = inputOptions;
  10399. this.outputOptions = outputOptions;
  10400. this.unsetOptions = unsetOptions;
  10401. this.pluginDriver = pluginDriver;
  10402. this.modulesById = modulesById;
  10403. this.chunkByModule = chunkByModule;
  10404. this.facadeChunkByModule = facadeChunkByModule;
  10405. this.includedNamespaces = includedNamespaces;
  10406. this.manualChunkAlias = manualChunkAlias;
  10407. this.entryModules = [];
  10408. this.exportMode = 'named';
  10409. this.facadeModule = null;
  10410. this.id = null;
  10411. this.namespaceVariableName = '';
  10412. this.variableName = '';
  10413. this.accessedGlobalsByScope = new Map();
  10414. this.dependencies = new Set();
  10415. this.dynamicDependencies = new Set();
  10416. this.dynamicEntryModules = [];
  10417. this.exportNamesByVariable = new Map();
  10418. this.exports = new Set();
  10419. this.exportsByName = Object.create(null);
  10420. this.fileName = null;
  10421. this.implicitEntryModules = [];
  10422. this.implicitlyLoadedBefore = new Set();
  10423. this.imports = new Set();
  10424. this.indentString = undefined;
  10425. this.isEmpty = true;
  10426. this.name = null;
  10427. this.needsExportsShim = false;
  10428. this.renderedDependencies = null;
  10429. this.renderedExports = null;
  10430. this.renderedHash = undefined;
  10431. this.renderedModules = Object.create(null);
  10432. this.renderedModuleSources = new Map();
  10433. this.renderedSource = null;
  10434. this.sortedExportNames = null;
  10435. this.strictFacade = false;
  10436. this.usedModules = undefined;
  10437. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  10438. const chunkModules = new Set(orderedModules);
  10439. for (const module of orderedModules) {
  10440. if (module.namespace.included) {
  10441. includedNamespaces.add(module);
  10442. }
  10443. if (this.isEmpty && module.isIncluded()) {
  10444. this.isEmpty = false;
  10445. }
  10446. if (module.info.isEntry || outputOptions.preserveModules) {
  10447. this.entryModules.push(module);
  10448. }
  10449. for (const importer of module.includedDynamicImporters) {
  10450. if (!chunkModules.has(importer)) {
  10451. this.dynamicEntryModules.push(module);
  10452. // Modules with synthetic exports need an artificial namespace for dynamic imports
  10453. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  10454. includedNamespaces.add(module);
  10455. this.exports.add(module.namespace);
  10456. }
  10457. }
  10458. }
  10459. if (module.implicitlyLoadedAfter.size > 0) {
  10460. this.implicitEntryModules.push(module);
  10461. }
  10462. }
  10463. this.suggestedVariableName = makeLegal(this.generateVariableName());
  10464. }
  10465. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  10466. const chunk = new Chunk$1([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  10467. chunk.assignFacadeName(facadeName, facadedModule);
  10468. if (!facadeChunkByModule.has(facadedModule)) {
  10469. facadeChunkByModule.set(facadedModule, chunk);
  10470. }
  10471. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  10472. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  10473. }
  10474. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  10475. facadedModule.info.hasModuleSideEffects &&
  10476. facadedModule.hasEffects()) {
  10477. chunk.dependencies.add(chunkByModule.get(facadedModule));
  10478. }
  10479. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  10480. chunk.facadeModule = facadedModule;
  10481. chunk.strictFacade = true;
  10482. return chunk;
  10483. }
  10484. canModuleBeFacade(module, exposedVariables) {
  10485. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  10486. for (const exposedVariable of this.exports) {
  10487. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  10488. if (moduleExportNamesByVariable.size === 0 &&
  10489. module.isUserDefinedEntryPoint &&
  10490. module.preserveSignature === 'strict' &&
  10491. this.unsetOptions.has('preserveEntrySignatures')) {
  10492. this.inputOptions.onwarn({
  10493. code: 'EMPTY_FACADE',
  10494. id: module.id,
  10495. 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.`,
  10496. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  10497. });
  10498. }
  10499. return false;
  10500. }
  10501. }
  10502. for (const exposedVariable of exposedVariables) {
  10503. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  10504. return false;
  10505. }
  10506. }
  10507. return true;
  10508. }
  10509. generateExports() {
  10510. this.sortedExportNames = null;
  10511. const remainingExports = new Set(this.exports);
  10512. if (this.facadeModule !== null &&
  10513. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  10514. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  10515. for (const [variable, exportNames] of exportNamesByVariable) {
  10516. this.exportNamesByVariable.set(variable, [...exportNames]);
  10517. for (const exportName of exportNames) {
  10518. this.exportsByName[exportName] = variable;
  10519. }
  10520. remainingExports.delete(variable);
  10521. }
  10522. }
  10523. if (this.outputOptions.minifyInternalExports) {
  10524. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  10525. }
  10526. else {
  10527. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  10528. }
  10529. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  10530. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  10531. }
  10532. generateFacades() {
  10533. var _a;
  10534. const facades = [];
  10535. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  10536. const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
  10537. for (const module of entryModules) {
  10538. if (module.preserveSignature) {
  10539. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  10540. exposedVariables.add(exportedVariable);
  10541. }
  10542. }
  10543. }
  10544. for (const module of entryModules) {
  10545. const requiredFacades = Array.from(module.userChunkNames, name => ({
  10546. name
  10547. }));
  10548. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  10549. requiredFacades.push({});
  10550. }
  10551. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  10552. if (requiredFacades.length === 0) {
  10553. requiredFacades.push({});
  10554. }
  10555. if (!this.facadeModule) {
  10556. const needsStrictFacade = module.preserveSignature === 'strict' ||
  10557. (module.preserveSignature === 'exports-only' &&
  10558. module.getExportNamesByVariable().size !== 0);
  10559. if (!needsStrictFacade ||
  10560. this.outputOptions.preserveModules ||
  10561. this.canModuleBeFacade(module, exposedVariables)) {
  10562. this.facadeModule = module;
  10563. this.facadeChunkByModule.set(module, this);
  10564. if (module.preserveSignature) {
  10565. this.strictFacade = needsStrictFacade;
  10566. this.ensureReexportsAreAvailableForModule(module);
  10567. }
  10568. this.assignFacadeName(requiredFacades.shift(), module);
  10569. }
  10570. }
  10571. for (const facadeName of requiredFacades) {
  10572. facades.push(Chunk$1.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  10573. }
  10574. }
  10575. for (const module of this.dynamicEntryModules) {
  10576. if (module.info.syntheticNamedExports)
  10577. continue;
  10578. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  10579. this.facadeModule = module;
  10580. this.facadeChunkByModule.set(module, this);
  10581. this.strictFacade = true;
  10582. this.assignFacadeName({}, module);
  10583. }
  10584. else if (this.facadeModule === module &&
  10585. !this.strictFacade &&
  10586. this.canModuleBeFacade(module, exposedVariables)) {
  10587. this.strictFacade = true;
  10588. }
  10589. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  10590. this.includedNamespaces.add(module);
  10591. this.exports.add(module.namespace);
  10592. }
  10593. }
  10594. return facades;
  10595. }
  10596. generateId(addons, options, existingNames, includeHash) {
  10597. if (this.fileName !== null) {
  10598. return this.fileName;
  10599. }
  10600. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  10601. ? [options.entryFileNames, 'output.entryFileNames']
  10602. : [options.chunkFileNames, 'output.chunkFileNames'];
  10603. return makeUnique(renderNamePattern(pattern, patternName, {
  10604. format: () => options.format,
  10605. hash: () => includeHash
  10606. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  10607. : '[hash]',
  10608. name: () => this.getChunkName()
  10609. }, this.getChunkInfo.bind(this)), existingNames);
  10610. }
  10611. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  10612. const id = this.orderedModules[0].id;
  10613. const sanitizedId = sanitizeFileName(id);
  10614. let path;
  10615. if (isAbsolute(id)) {
  10616. const extension = extname(id);
  10617. const pattern = unsetOptions.has('entryFileNames')
  10618. ? NON_ASSET_EXTENSIONS.includes(extension)
  10619. ? '[name].js'
  10620. : '[name][extname].js'
  10621. : options.entryFileNames;
  10622. const currentDir = dirname(sanitizedId);
  10623. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  10624. ext: () => extension.substr(1),
  10625. extname: () => extension,
  10626. format: () => options.format,
  10627. name: () => this.getChunkName()
  10628. }, this.getChunkInfo.bind(this));
  10629. const currentPath = `${currentDir}/${fileName}`;
  10630. const { preserveModulesRoot } = options;
  10631. if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
  10632. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  10633. }
  10634. else {
  10635. path = relative(preserveModulesRelativeDir, currentPath);
  10636. }
  10637. }
  10638. else {
  10639. path = `_virtual/${basename(sanitizedId)}`;
  10640. }
  10641. return makeUnique(normalize(path), existingNames);
  10642. }
  10643. getChunkInfo() {
  10644. const facadeModule = this.facadeModule;
  10645. const getChunkName = this.getChunkName.bind(this);
  10646. return {
  10647. exports: this.getExportNames(),
  10648. facadeModuleId: facadeModule && facadeModule.id,
  10649. isDynamicEntry: this.dynamicEntryModules.length > 0,
  10650. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  10651. isImplicitEntry: this.implicitEntryModules.length > 0,
  10652. modules: this.renderedModules,
  10653. get name() {
  10654. return getChunkName();
  10655. },
  10656. type: 'chunk'
  10657. };
  10658. }
  10659. getChunkInfoWithFileNames() {
  10660. return Object.assign(this.getChunkInfo(), {
  10661. code: undefined,
  10662. dynamicImports: Array.from(this.dynamicDependencies, getId),
  10663. fileName: this.id,
  10664. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  10665. importedBindings: this.getImportedBindingsPerDependency(),
  10666. imports: Array.from(this.dependencies, getId),
  10667. map: undefined,
  10668. referencedFiles: this.getReferencedFiles()
  10669. });
  10670. }
  10671. getChunkName() {
  10672. return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
  10673. }
  10674. getExportNames() {
  10675. return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
  10676. }
  10677. getRenderedHash() {
  10678. if (this.renderedHash)
  10679. return this.renderedHash;
  10680. const hash = createHash();
  10681. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  10682. if (pluginHash) {
  10683. augmentation += pluginHash;
  10684. }
  10685. return augmentation;
  10686. });
  10687. hash.update(hashAugmentation);
  10688. hash.update(this.renderedSource.toString());
  10689. hash.update(this.getExportNames()
  10690. .map(exportName => {
  10691. const variable = this.exportsByName[exportName];
  10692. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  10693. })
  10694. .join(','));
  10695. return (this.renderedHash = hash.digest('hex'));
  10696. }
  10697. getVariableExportName(variable) {
  10698. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  10699. return '*';
  10700. }
  10701. return this.exportNamesByVariable.get(variable)[0];
  10702. }
  10703. link() {
  10704. for (const module of this.orderedModules) {
  10705. this.addDependenciesToChunk(module.getDependenciesToBeIncluded(), this.dependencies);
  10706. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  10707. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  10708. this.setUpChunkImportsAndExportsForModule(module);
  10709. }
  10710. }
  10711. // prerender allows chunk hashes and names to be generated before finalizing
  10712. preRender(options, inputBase) {
  10713. const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
  10714. this.usedModules = [];
  10715. this.indentString = getIndentString(this.orderedModules, options);
  10716. const n = options.compact ? '' : '\n';
  10717. const _ = options.compact ? '' : ' ';
  10718. const renderOptions = {
  10719. compact: options.compact,
  10720. dynamicImportFunction: options.dynamicImportFunction,
  10721. exportNamesByVariable: this.exportNamesByVariable,
  10722. format: options.format,
  10723. freeze: options.freeze,
  10724. indent: this.indentString,
  10725. namespaceToStringTag: options.namespaceToStringTag,
  10726. outputPluginDriver: this.pluginDriver,
  10727. varOrConst: options.preferConst ? 'const' : 'var'
  10728. };
  10729. // for static and dynamic entry points, inline the execution list to avoid loading latency
  10730. if (options.hoistTransitiveImports &&
  10731. !this.outputOptions.preserveModules &&
  10732. this.facadeModule !== null) {
  10733. for (const dep of this.dependencies) {
  10734. if (dep instanceof Chunk$1)
  10735. this.inlineChunkDependencies(dep);
  10736. }
  10737. }
  10738. const sortedDependencies = [...this.dependencies];
  10739. sortByExecutionOrder(sortedDependencies);
  10740. this.dependencies = new Set(sortedDependencies);
  10741. this.prepareDynamicImportsAndImportMetas();
  10742. this.setIdentifierRenderResolutions(options);
  10743. let hoistedSource = '';
  10744. const renderedModules = this.renderedModules;
  10745. for (const module of this.orderedModules) {
  10746. let renderedLength = 0;
  10747. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  10748. const source = module.render(renderOptions).trim();
  10749. renderedLength = source.length();
  10750. if (renderedLength) {
  10751. if (options.compact && source.lastLine().indexOf('//') !== -1)
  10752. source.append('\n');
  10753. this.renderedModuleSources.set(module, source);
  10754. magicString.addSource(source);
  10755. this.usedModules.push(module);
  10756. }
  10757. const namespace = module.namespace;
  10758. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  10759. const rendered = namespace.renderBlock(renderOptions);
  10760. if (namespace.renderFirst())
  10761. hoistedSource += n + rendered;
  10762. else
  10763. magicString.addSource(new MagicString(rendered));
  10764. }
  10765. }
  10766. const { renderedExports, removedExports } = module.getRenderedExports();
  10767. renderedModules[module.id] = {
  10768. originalLength: module.originalCode.length,
  10769. removedExports,
  10770. renderedExports,
  10771. renderedLength
  10772. };
  10773. }
  10774. if (hoistedSource)
  10775. magicString.prepend(hoistedSource + n + n);
  10776. if (this.needsExportsShim) {
  10777. magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  10778. }
  10779. if (options.compact) {
  10780. this.renderedSource = magicString;
  10781. }
  10782. else {
  10783. this.renderedSource = magicString.trim();
  10784. }
  10785. this.renderedHash = undefined;
  10786. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  10787. const chunkName = this.getChunkName();
  10788. this.inputOptions.onwarn({
  10789. chunkName,
  10790. code: 'EMPTY_BUNDLE',
  10791. message: `Generated an empty chunk: "${chunkName}"`
  10792. });
  10793. }
  10794. this.setExternalRenderPaths(options, inputBase);
  10795. this.renderedDependencies = this.getChunkDependencyDeclarations(options);
  10796. this.renderedExports =
  10797. this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
  10798. }
  10799. async render(options, addons, outputChunk) {
  10800. timeStart('render format', 2);
  10801. const format = options.format;
  10802. const finalise = finalisers[format];
  10803. if (options.dynamicImportFunction && format !== 'es') {
  10804. this.inputOptions.onwarn({
  10805. code: 'INVALID_OPTION',
  10806. message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
  10807. });
  10808. }
  10809. // populate ids in the rendered declarations only here
  10810. // as chunk ids known only after prerender
  10811. for (const dependency of this.dependencies) {
  10812. const renderedDependency = this.renderedDependencies.get(dependency);
  10813. if (dependency instanceof ExternalModule) {
  10814. const originalId = dependency.renderPath;
  10815. renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
  10816. }
  10817. else {
  10818. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  10819. renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
  10820. }
  10821. }
  10822. this.finaliseDynamicImports(options);
  10823. this.finaliseImportMetas(format);
  10824. const hasExports = this.renderedExports.length !== 0 ||
  10825. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  10826. let usesTopLevelAwait = false;
  10827. const accessedGlobals = new Set();
  10828. for (const module of this.orderedModules) {
  10829. if (module.usesTopLevelAwait) {
  10830. usesTopLevelAwait = true;
  10831. }
  10832. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  10833. if (accessedGlobalVariables) {
  10834. for (const name of accessedGlobalVariables) {
  10835. accessedGlobals.add(name);
  10836. }
  10837. }
  10838. }
  10839. if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
  10840. return error({
  10841. code: 'INVALID_TLA_FORMAT',
  10842. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  10843. });
  10844. }
  10845. const magicString = finalise(this.renderedSource, {
  10846. accessedGlobals,
  10847. dependencies: [...this.renderedDependencies.values()],
  10848. exports: this.renderedExports,
  10849. hasExports,
  10850. indentString: this.indentString,
  10851. intro: addons.intro,
  10852. isEntryFacade: this.outputOptions.preserveModules ||
  10853. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  10854. isModuleFacade: this.facadeModule !== null,
  10855. namedExportsMode: this.exportMode !== 'default',
  10856. outro: addons.outro,
  10857. usesTopLevelAwait,
  10858. varOrConst: options.preferConst ? 'const' : 'var',
  10859. warn: this.inputOptions.onwarn
  10860. }, options);
  10861. if (addons.banner)
  10862. magicString.prepend(addons.banner);
  10863. if (addons.footer)
  10864. magicString.append(addons.footer);
  10865. const prevCode = magicString.toString();
  10866. timeEnd('render format', 2);
  10867. let map = null;
  10868. const chunkSourcemapChain = [];
  10869. let code = await renderChunk({
  10870. code: prevCode,
  10871. options,
  10872. outputPluginDriver: this.pluginDriver,
  10873. renderChunk: outputChunk,
  10874. sourcemapChain: chunkSourcemapChain
  10875. });
  10876. if (options.sourcemap) {
  10877. timeStart('sourcemap', 2);
  10878. let file;
  10879. if (options.file)
  10880. file = resolve(options.sourcemapFile || options.file);
  10881. else if (options.dir)
  10882. file = resolve(options.dir, this.id);
  10883. else
  10884. file = resolve(this.id);
  10885. const decodedMap = magicString.generateDecodedMap({});
  10886. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  10887. map.sources = map.sources
  10888. .map(sourcePath => {
  10889. const { sourcemapPathTransform } = options;
  10890. if (sourcemapPathTransform) {
  10891. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  10892. if (typeof newSourcePath !== 'string') {
  10893. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  10894. }
  10895. return newSourcePath;
  10896. }
  10897. return sourcePath;
  10898. })
  10899. .map(normalize);
  10900. timeEnd('sourcemap', 2);
  10901. }
  10902. if (!options.compact && code[code.length - 1] !== '\n')
  10903. code += '\n';
  10904. return { code, map };
  10905. }
  10906. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  10907. for (const module of moduleDependencies) {
  10908. if (module instanceof Module) {
  10909. const chunk = this.chunkByModule.get(module);
  10910. if (chunk && chunk !== this) {
  10911. chunkDependencies.add(chunk);
  10912. }
  10913. }
  10914. else {
  10915. chunkDependencies.add(module);
  10916. }
  10917. }
  10918. }
  10919. assignFacadeName({ fileName, name }, facadedModule) {
  10920. if (fileName) {
  10921. this.fileName = fileName;
  10922. }
  10923. else {
  10924. this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
  10925. }
  10926. }
  10927. computeContentHashWithDependencies(addons, options, existingNames) {
  10928. const hash = createHash();
  10929. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
  10930. hash.update(options.format);
  10931. const dependenciesForHashing = new Set([this]);
  10932. for (const current of dependenciesForHashing) {
  10933. if (current instanceof ExternalModule) {
  10934. hash.update(':' + current.renderPath);
  10935. }
  10936. else {
  10937. hash.update(current.getRenderedHash());
  10938. hash.update(current.generateId(addons, options, existingNames, false));
  10939. }
  10940. if (current instanceof ExternalModule)
  10941. continue;
  10942. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  10943. dependenciesForHashing.add(dependency);
  10944. }
  10945. }
  10946. return hash.digest('hex').substr(0, 8);
  10947. }
  10948. ensureReexportsAreAvailableForModule(module) {
  10949. const map = module.getExportNamesByVariable();
  10950. for (const exportedVariable of map.keys()) {
  10951. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  10952. const importedVariable = isSynthetic
  10953. ? exportedVariable.getBaseVariable()
  10954. : exportedVariable;
  10955. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  10956. const exportingModule = importedVariable.module;
  10957. if (exportingModule instanceof Module) {
  10958. const chunk = this.chunkByModule.get(exportingModule);
  10959. if (chunk && chunk !== this) {
  10960. chunk.exports.add(importedVariable);
  10961. if (isSynthetic) {
  10962. this.imports.add(importedVariable);
  10963. }
  10964. }
  10965. }
  10966. }
  10967. }
  10968. }
  10969. finaliseDynamicImports(options) {
  10970. const stripKnownJsExtensions = options.format === 'amd';
  10971. for (const [module, code] of this.renderedModuleSources) {
  10972. for (const { node, resolution } of module.dynamicImports) {
  10973. const chunk = this.chunkByModule.get(resolution);
  10974. const facadeChunk = this.facadeChunkByModule.get(resolution);
  10975. if (!resolution || !node.included || chunk === this) {
  10976. continue;
  10977. }
  10978. const renderedResolution = resolution instanceof Module
  10979. ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
  10980. : resolution instanceof ExternalModule
  10981. ? `'${resolution.renormalizeRenderPath
  10982. ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
  10983. : resolution.renderPath}'`
  10984. : resolution;
  10985. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  10986. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  10987. chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
  10988. }
  10989. }
  10990. }
  10991. finaliseImportMetas(format) {
  10992. for (const [module, code] of this.renderedModuleSources) {
  10993. for (const importMeta of module.importMetas) {
  10994. importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
  10995. }
  10996. }
  10997. }
  10998. generateVariableName() {
  10999. if (this.manualChunkAlias) {
  11000. return this.manualChunkAlias;
  11001. }
  11002. const moduleForNaming = this.entryModules[0] ||
  11003. this.implicitEntryModules[0] ||
  11004. this.dynamicEntryModules[0] ||
  11005. this.orderedModules[this.orderedModules.length - 1];
  11006. if (moduleForNaming) {
  11007. return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
  11008. }
  11009. return 'chunk';
  11010. }
  11011. getChunkDependencyDeclarations(options) {
  11012. const importSpecifiers = this.getImportSpecifiers();
  11013. const reexportSpecifiers = this.getReexportSpecifiers();
  11014. const dependencyDeclaration = new Map();
  11015. for (const dep of this.dependencies) {
  11016. const imports = importSpecifiers.get(dep) || null;
  11017. const reexports = reexportSpecifiers.get(dep) || null;
  11018. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  11019. dependencyDeclaration.set(dep, {
  11020. defaultVariableName: dep.defaultVariableName,
  11021. globalName: (dep instanceof ExternalModule &&
  11022. (options.format === 'umd' || options.format === 'iife') &&
  11023. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  11024. id: undefined,
  11025. imports,
  11026. isChunk: dep instanceof Chunk$1,
  11027. name: dep.variableName,
  11028. namedExportsMode,
  11029. namespaceVariableName: dep.namespaceVariableName,
  11030. reexports
  11031. });
  11032. }
  11033. return dependencyDeclaration;
  11034. }
  11035. getChunkExportDeclarations(format) {
  11036. const exports = [];
  11037. for (const exportName of this.getExportNames()) {
  11038. if (exportName[0] === '*')
  11039. continue;
  11040. const variable = this.exportsByName[exportName];
  11041. if (!(variable instanceof SyntheticNamedExportVariable)) {
  11042. const module = variable.module;
  11043. if (module && this.chunkByModule.get(module) !== this)
  11044. continue;
  11045. }
  11046. let expression = null;
  11047. let hoisted = false;
  11048. let uninitialized = false;
  11049. let local = variable.getName();
  11050. if (variable instanceof LocalVariable) {
  11051. if (variable.init === UNDEFINED_EXPRESSION) {
  11052. uninitialized = true;
  11053. }
  11054. for (const declaration of variable.declarations) {
  11055. if (declaration.parent instanceof FunctionDeclaration ||
  11056. (declaration instanceof ExportDefaultDeclaration &&
  11057. declaration.declaration instanceof FunctionDeclaration)) {
  11058. hoisted = true;
  11059. break;
  11060. }
  11061. }
  11062. }
  11063. else if (variable instanceof SyntheticNamedExportVariable) {
  11064. expression = local;
  11065. if (format === 'es' && exportName !== 'default') {
  11066. local = variable.renderName;
  11067. }
  11068. }
  11069. exports.push({
  11070. exported: exportName,
  11071. expression,
  11072. hoisted,
  11073. local,
  11074. uninitialized
  11075. });
  11076. }
  11077. return exports;
  11078. }
  11079. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  11080. const dependencies = new Set();
  11081. const deconflictedDefault = new Set();
  11082. const deconflictedNamespace = new Set();
  11083. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  11084. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  11085. const module = variable.module;
  11086. if (module instanceof ExternalModule) {
  11087. dependencies.add(module);
  11088. if (addNonNamespacesAndInteropHelpers) {
  11089. if (variable.name === 'default') {
  11090. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  11091. deconflictedDefault.add(module);
  11092. }
  11093. }
  11094. else if (variable.name === '*') {
  11095. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  11096. deconflictedNamespace.add(module);
  11097. }
  11098. }
  11099. }
  11100. }
  11101. else {
  11102. const chunk = this.chunkByModule.get(module);
  11103. if (chunk !== this) {
  11104. dependencies.add(chunk);
  11105. if (addNonNamespacesAndInteropHelpers &&
  11106. chunk.exportMode === 'default' &&
  11107. variable.isNamespace) {
  11108. deconflictedNamespace.add(chunk);
  11109. }
  11110. }
  11111. }
  11112. }
  11113. }
  11114. if (addDependenciesWithoutBindings) {
  11115. for (const dependency of this.dependencies) {
  11116. dependencies.add(dependency);
  11117. }
  11118. }
  11119. return { deconflictedDefault, deconflictedNamespace, dependencies };
  11120. }
  11121. getFallbackChunkName() {
  11122. if (this.manualChunkAlias) {
  11123. return this.manualChunkAlias;
  11124. }
  11125. if (this.fileName) {
  11126. return getAliasName(this.fileName);
  11127. }
  11128. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  11129. }
  11130. getImportedBindingsPerDependency() {
  11131. const importSpecifiers = {};
  11132. for (const [dependency, declaration] of this.renderedDependencies) {
  11133. const specifiers = new Set();
  11134. if (declaration.imports) {
  11135. for (const { imported } of declaration.imports) {
  11136. specifiers.add(imported);
  11137. }
  11138. }
  11139. if (declaration.reexports) {
  11140. for (const { imported } of declaration.reexports) {
  11141. specifiers.add(imported);
  11142. }
  11143. }
  11144. importSpecifiers[dependency.id] = [...specifiers];
  11145. }
  11146. return importSpecifiers;
  11147. }
  11148. getImportSpecifiers() {
  11149. const { interop } = this.outputOptions;
  11150. const importsByDependency = new Map();
  11151. for (const variable of this.imports) {
  11152. const module = variable.module;
  11153. let dependency;
  11154. let imported;
  11155. if (module instanceof ExternalModule) {
  11156. dependency = module;
  11157. imported = variable.name;
  11158. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  11159. return error(errUnexpectedNamedImport(module.id, imported, false));
  11160. }
  11161. }
  11162. else {
  11163. dependency = this.chunkByModule.get(module);
  11164. imported = dependency.getVariableExportName(variable);
  11165. }
  11166. getOrCreate(importsByDependency, dependency, () => []).push({
  11167. imported,
  11168. local: variable.getName()
  11169. });
  11170. }
  11171. return importsByDependency;
  11172. }
  11173. getReexportSpecifiers() {
  11174. const { externalLiveBindings, interop } = this.outputOptions;
  11175. const reexportSpecifiers = new Map();
  11176. for (let exportName of this.getExportNames()) {
  11177. let dependency;
  11178. let imported;
  11179. let needsLiveBinding = false;
  11180. if (exportName[0] === '*') {
  11181. const id = exportName.substr(1);
  11182. if (interop(id) === 'defaultOnly') {
  11183. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  11184. }
  11185. needsLiveBinding = externalLiveBindings;
  11186. dependency = this.modulesById.get(id);
  11187. imported = exportName = '*';
  11188. }
  11189. else {
  11190. const variable = this.exportsByName[exportName];
  11191. if (variable instanceof SyntheticNamedExportVariable)
  11192. continue;
  11193. const module = variable.module;
  11194. if (module instanceof Module) {
  11195. dependency = this.chunkByModule.get(module);
  11196. if (dependency === this)
  11197. continue;
  11198. imported = dependency.getVariableExportName(variable);
  11199. needsLiveBinding = variable.isReassigned;
  11200. }
  11201. else {
  11202. dependency = module;
  11203. imported = variable.name;
  11204. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  11205. return error(errUnexpectedNamedImport(module.id, imported, true));
  11206. }
  11207. needsLiveBinding =
  11208. externalLiveBindings &&
  11209. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  11210. }
  11211. }
  11212. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  11213. imported,
  11214. needsLiveBinding,
  11215. reexported: exportName
  11216. });
  11217. }
  11218. return reexportSpecifiers;
  11219. }
  11220. getReferencedFiles() {
  11221. const referencedFiles = [];
  11222. for (const module of this.orderedModules) {
  11223. for (const meta of module.importMetas) {
  11224. const fileName = meta.getReferencedFileName(this.pluginDriver);
  11225. if (fileName) {
  11226. referencedFiles.push(fileName);
  11227. }
  11228. }
  11229. }
  11230. return referencedFiles;
  11231. }
  11232. getRelativePath(targetPath, stripJsExtension) {
  11233. let relativePath = normalize(relative(dirname(this.id), targetPath));
  11234. if (stripJsExtension && relativePath.endsWith('.js')) {
  11235. relativePath = relativePath.slice(0, -3);
  11236. }
  11237. if (relativePath === '..')
  11238. return '../../' + basename(targetPath);
  11239. if (relativePath === '')
  11240. return '../' + basename(targetPath);
  11241. return relativePath.startsWith('../') ? relativePath : './' + relativePath;
  11242. }
  11243. inlineChunkDependencies(chunk) {
  11244. for (const dep of chunk.dependencies) {
  11245. if (this.dependencies.has(dep))
  11246. continue;
  11247. this.dependencies.add(dep);
  11248. if (dep instanceof Chunk$1) {
  11249. this.inlineChunkDependencies(dep);
  11250. }
  11251. }
  11252. }
  11253. prepareDynamicImportsAndImportMetas() {
  11254. var _a;
  11255. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  11256. for (const module of this.orderedModules) {
  11257. for (const { node, resolution } of module.dynamicImports) {
  11258. if (node.included) {
  11259. if (resolution instanceof Module) {
  11260. const chunk = this.chunkByModule.get(resolution);
  11261. if (chunk === this) {
  11262. node.setInternalResolution(resolution.namespace);
  11263. }
  11264. else {
  11265. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  11266. }
  11267. }
  11268. else {
  11269. node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  11270. }
  11271. }
  11272. }
  11273. for (const importMeta of module.importMetas) {
  11274. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  11275. }
  11276. }
  11277. }
  11278. setExternalRenderPaths(options, inputBase) {
  11279. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  11280. if (dependency instanceof ExternalModule) {
  11281. dependency.setRenderPath(options, inputBase);
  11282. }
  11283. }
  11284. }
  11285. setIdentifierRenderResolutions({ format, interop }) {
  11286. const syntheticExports = new Set();
  11287. for (const exportName of this.getExportNames()) {
  11288. const exportVariable = this.exportsByName[exportName];
  11289. if (exportVariable instanceof ExportShimVariable) {
  11290. this.needsExportsShim = true;
  11291. }
  11292. if (format !== 'es' &&
  11293. format !== 'system' &&
  11294. exportVariable.isReassigned &&
  11295. !exportVariable.isId) {
  11296. exportVariable.setRenderNames('exports', exportName);
  11297. }
  11298. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  11299. syntheticExports.add(exportVariable);
  11300. }
  11301. else {
  11302. exportVariable.setRenderNames(null, null);
  11303. }
  11304. }
  11305. const usedNames = new Set();
  11306. if (this.needsExportsShim) {
  11307. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  11308. }
  11309. switch (format) {
  11310. case 'system':
  11311. usedNames.add('module').add('exports');
  11312. break;
  11313. case 'es':
  11314. break;
  11315. case 'cjs':
  11316. usedNames.add('module').add('require').add('__filename').add('__dirname');
  11317. // fallthrough
  11318. default:
  11319. usedNames.add('exports');
  11320. for (const helper of HELPER_NAMES) {
  11321. usedNames.add(helper);
  11322. }
  11323. }
  11324. 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);
  11325. }
  11326. setUpChunkImportsAndExportsForModule(module) {
  11327. const moduleImports = new Set(module.imports);
  11328. // when we are not preserving modules, we need to make all namespace variables available for
  11329. // rendering the namespace object
  11330. if (!this.outputOptions.preserveModules) {
  11331. if (this.includedNamespaces.has(module)) {
  11332. const memberVariables = module.namespace.getMemberVariables();
  11333. for (const name of Object.keys(memberVariables)) {
  11334. moduleImports.add(memberVariables[name]);
  11335. }
  11336. }
  11337. }
  11338. for (let variable of moduleImports) {
  11339. if (variable instanceof ExportDefaultVariable) {
  11340. variable = variable.getOriginalVariable();
  11341. }
  11342. if (variable instanceof SyntheticNamedExportVariable) {
  11343. variable = variable.getBaseVariable();
  11344. }
  11345. const chunk = this.chunkByModule.get(variable.module);
  11346. if (chunk !== this) {
  11347. this.imports.add(variable);
  11348. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  11349. variable.module instanceof Module) {
  11350. chunk.exports.add(variable);
  11351. }
  11352. }
  11353. }
  11354. if (this.includedNamespaces.has(module) ||
  11355. (module.info.isEntry && module.preserveSignature !== false) ||
  11356. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  11357. this.ensureReexportsAreAvailableForModule(module);
  11358. }
  11359. for (const { node, resolution } of module.dynamicImports) {
  11360. if (node.included &&
  11361. resolution instanceof Module &&
  11362. this.chunkByModule.get(resolution) === this &&
  11363. !this.includedNamespaces.has(resolution)) {
  11364. this.includedNamespaces.add(resolution);
  11365. this.ensureReexportsAreAvailableForModule(resolution);
  11366. }
  11367. }
  11368. }
  11369. }
  11370. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  11371. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  11372. async function createAddons(options, outputPluginDriver) {
  11373. try {
  11374. let [banner, footer, intro, outro] = await Promise.all([
  11375. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  11376. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  11377. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  11378. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  11379. ]);
  11380. if (intro)
  11381. intro += '\n\n';
  11382. if (outro)
  11383. outro = `\n\n${outro}`;
  11384. if (banner.length)
  11385. banner += '\n';
  11386. if (footer.length)
  11387. footer = '\n' + footer;
  11388. return { intro, outro, banner, footer };
  11389. }
  11390. catch (err) {
  11391. return error({
  11392. code: 'ADDON_ERROR',
  11393. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  11394. \tError Message: ${err.message}`
  11395. });
  11396. }
  11397. }
  11398. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  11399. const chunkDefinitions = [];
  11400. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  11401. const manualChunkModulesByAlias = Object.create(null);
  11402. for (const [entry, alias] of manualChunkAliasByEntry) {
  11403. const chunkModules = (manualChunkModulesByAlias[alias] =
  11404. manualChunkModulesByAlias[alias] || []);
  11405. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  11406. }
  11407. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  11408. chunkDefinitions.push({ alias, modules });
  11409. }
  11410. const assignedEntryPointsByModule = new Map();
  11411. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  11412. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  11413. const staticEntries = new Set(entryModules);
  11414. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  11415. const modulesToHandle = new Set([entry]);
  11416. for (const module of modulesToHandle) {
  11417. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  11418. if (dynamicDependentEntryPoints &&
  11419. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  11420. continue;
  11421. }
  11422. else {
  11423. assignedEntryPoints.add(entry);
  11424. }
  11425. for (const dependency of module.getDependenciesToBeIncluded()) {
  11426. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  11427. modulesToHandle.add(dependency);
  11428. }
  11429. }
  11430. }
  11431. }
  11432. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  11433. const entriesToCheck = new Set(entryPoints);
  11434. for (const entry of entriesToCheck) {
  11435. if (!containedIn.has(entry)) {
  11436. if (staticEntries.has(entry))
  11437. return false;
  11438. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  11439. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  11440. entriesToCheck.add(dependentEntry);
  11441. }
  11442. }
  11443. }
  11444. return true;
  11445. }
  11446. for (const entry of entryModules) {
  11447. if (!modulesInManualChunks.has(entry)) {
  11448. assignEntryToStaticDependencies(entry, null);
  11449. }
  11450. }
  11451. for (const entry of dynamicEntryModules) {
  11452. if (!modulesInManualChunks.has(entry)) {
  11453. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  11454. }
  11455. }
  11456. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  11457. return chunkDefinitions;
  11458. }
  11459. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  11460. const modulesToHandle = new Set([entry]);
  11461. for (const module of modulesToHandle) {
  11462. modulesInManualChunks.add(module);
  11463. manualChunkModules.push(module);
  11464. for (const dependency of module.dependencies) {
  11465. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  11466. modulesToHandle.add(dependency);
  11467. }
  11468. }
  11469. }
  11470. }
  11471. function analyzeModuleGraph(entryModules) {
  11472. const dynamicEntryModules = new Set();
  11473. const dependentEntryPointsByModule = new Map();
  11474. const entriesToHandle = new Set(entryModules);
  11475. for (const currentEntry of entriesToHandle) {
  11476. const modulesToHandle = new Set([currentEntry]);
  11477. for (const module of modulesToHandle) {
  11478. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  11479. for (const dependency of module.getDependenciesToBeIncluded()) {
  11480. if (!(dependency instanceof ExternalModule)) {
  11481. modulesToHandle.add(dependency);
  11482. }
  11483. }
  11484. for (const { resolution } of module.dynamicImports) {
  11485. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  11486. dynamicEntryModules.add(resolution);
  11487. entriesToHandle.add(resolution);
  11488. }
  11489. }
  11490. for (const dependency of module.implicitlyLoadedBefore) {
  11491. dynamicEntryModules.add(dependency);
  11492. entriesToHandle.add(dependency);
  11493. }
  11494. }
  11495. }
  11496. return { dependentEntryPointsByModule, dynamicEntryModules };
  11497. }
  11498. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  11499. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  11500. for (const dynamicEntry of dynamicEntryModules) {
  11501. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  11502. for (const importer of [
  11503. ...dynamicEntry.includedDynamicImporters,
  11504. ...dynamicEntry.implicitlyLoadedAfter
  11505. ]) {
  11506. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  11507. dynamicDependentEntryPoints.add(entryPoint);
  11508. }
  11509. }
  11510. }
  11511. return dynamicallyDependentEntryPointsByDynamicEntry;
  11512. }
  11513. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  11514. const chunkModules = Object.create(null);
  11515. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  11516. let chunkSignature = '';
  11517. for (const entry of allEntryPoints) {
  11518. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  11519. }
  11520. const chunk = chunkModules[chunkSignature];
  11521. if (chunk) {
  11522. chunk.push(module);
  11523. }
  11524. else {
  11525. chunkModules[chunkSignature] = [module];
  11526. }
  11527. }
  11528. return Object.keys(chunkModules).map(chunkSignature => ({
  11529. alias: null,
  11530. modules: chunkModules[chunkSignature]
  11531. }));
  11532. }
  11533. // ported from https://github.com/substack/node-commondir
  11534. function commondir(files) {
  11535. if (files.length === 0)
  11536. return '/';
  11537. if (files.length === 1)
  11538. return dirname(files[0]);
  11539. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  11540. const pathSegements = file.split(/\/+|\\+/);
  11541. let i;
  11542. for (i = 0; commonSegments[i] === pathSegements[i] &&
  11543. i < Math.min(commonSegments.length, pathSegements.length); i++)
  11544. ;
  11545. return commonSegments.slice(0, i);
  11546. }, files[0].split(/\/+|\\+/));
  11547. // Windows correctly handles paths with forward-slashes
  11548. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  11549. }
  11550. var BuildPhase;
  11551. (function (BuildPhase) {
  11552. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11553. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11554. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11555. })(BuildPhase || (BuildPhase = {}));
  11556. function generateAssetFileName(name, source, output) {
  11557. const emittedName = name || 'asset';
  11558. return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
  11559. hash() {
  11560. const hash = createHash();
  11561. hash.update(emittedName);
  11562. hash.update(':');
  11563. hash.update(source);
  11564. return hash.digest('hex').substr(0, 8);
  11565. },
  11566. ext: () => extname(emittedName).substr(1),
  11567. extname: () => extname(emittedName),
  11568. name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length)
  11569. }, () => ({ name, source, type: 'asset' })), output.bundle);
  11570. }
  11571. function reserveFileNameInBundle(fileName, bundle, warn) {
  11572. if (fileName in bundle) {
  11573. warn(errFileNameConflict(fileName));
  11574. }
  11575. bundle[fileName] = FILE_PLACEHOLDER;
  11576. }
  11577. const FILE_PLACEHOLDER = {
  11578. type: 'placeholder'
  11579. };
  11580. function hasValidType(emittedFile) {
  11581. return (emittedFile &&
  11582. (emittedFile.type === 'asset' ||
  11583. emittedFile.type === 'chunk'));
  11584. }
  11585. function hasValidName(emittedFile) {
  11586. const validatedName = emittedFile.fileName || emittedFile.name;
  11587. return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
  11588. }
  11589. function getValidSource(source, emittedFile, fileReferenceId) {
  11590. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  11591. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  11592. 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.`));
  11593. }
  11594. return source;
  11595. }
  11596. function getAssetFileName(file, referenceId) {
  11597. if (typeof file.fileName !== 'string') {
  11598. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  11599. }
  11600. return file.fileName;
  11601. }
  11602. function getChunkFileName(file, facadeChunkByModule) {
  11603. var _a;
  11604. 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));
  11605. if (!fileName)
  11606. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  11607. return fileName;
  11608. }
  11609. class FileEmitter {
  11610. constructor(graph, options, baseFileEmitter) {
  11611. this.graph = graph;
  11612. this.options = options;
  11613. this.facadeChunkByModule = null;
  11614. this.output = null;
  11615. this.assertAssetsFinalized = () => {
  11616. for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
  11617. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  11618. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  11619. }
  11620. };
  11621. this.emitFile = (emittedFile) => {
  11622. if (!hasValidType(emittedFile)) {
  11623. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  11624. }
  11625. if (!hasValidName(emittedFile)) {
  11626. return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || emittedFile.name}".`));
  11627. }
  11628. if (emittedFile.type === 'chunk') {
  11629. return this.emitChunk(emittedFile);
  11630. }
  11631. else {
  11632. return this.emitAsset(emittedFile);
  11633. }
  11634. };
  11635. this.getFileName = (fileReferenceId) => {
  11636. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  11637. if (!emittedFile)
  11638. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  11639. if (emittedFile.type === 'chunk') {
  11640. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  11641. }
  11642. else {
  11643. return getAssetFileName(emittedFile, fileReferenceId);
  11644. }
  11645. };
  11646. this.setAssetSource = (referenceId, requestedSource) => {
  11647. const consumedFile = this.filesByReferenceId.get(referenceId);
  11648. if (!consumedFile)
  11649. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  11650. if (consumedFile.type !== 'asset') {
  11651. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  11652. }
  11653. if (consumedFile.source !== undefined) {
  11654. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  11655. }
  11656. const source = getValidSource(requestedSource, consumedFile, referenceId);
  11657. if (this.output) {
  11658. this.finalizeAsset(consumedFile, source, referenceId, this.output);
  11659. }
  11660. else {
  11661. consumedFile.source = source;
  11662. }
  11663. };
  11664. this.setOutputBundle = (outputBundle, assetFileNames, facadeChunkByModule) => {
  11665. this.output = {
  11666. assetFileNames,
  11667. bundle: outputBundle
  11668. };
  11669. this.facadeChunkByModule = facadeChunkByModule;
  11670. for (const emittedFile of this.filesByReferenceId.values()) {
  11671. if (emittedFile.fileName) {
  11672. reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.options.onwarn);
  11673. }
  11674. }
  11675. for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
  11676. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  11677. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
  11678. }
  11679. }
  11680. };
  11681. this.filesByReferenceId = baseFileEmitter
  11682. ? new Map(baseFileEmitter.filesByReferenceId)
  11683. : new Map();
  11684. }
  11685. assignReferenceId(file, idBase) {
  11686. let referenceId;
  11687. do {
  11688. const hash = createHash();
  11689. if (referenceId) {
  11690. hash.update(referenceId);
  11691. }
  11692. else {
  11693. hash.update(idBase);
  11694. }
  11695. referenceId = hash.digest('hex').substr(0, 8);
  11696. } while (this.filesByReferenceId.has(referenceId));
  11697. this.filesByReferenceId.set(referenceId, file);
  11698. return referenceId;
  11699. }
  11700. emitAsset(emittedAsset) {
  11701. const source = typeof emittedAsset.source !== 'undefined'
  11702. ? getValidSource(emittedAsset.source, emittedAsset, null)
  11703. : undefined;
  11704. const consumedAsset = {
  11705. fileName: emittedAsset.fileName,
  11706. name: emittedAsset.name,
  11707. source,
  11708. type: 'asset'
  11709. };
  11710. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  11711. if (this.output) {
  11712. if (emittedAsset.fileName) {
  11713. reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.options.onwarn);
  11714. }
  11715. if (source !== undefined) {
  11716. this.finalizeAsset(consumedAsset, source, referenceId, this.output);
  11717. }
  11718. }
  11719. return referenceId;
  11720. }
  11721. emitChunk(emittedChunk) {
  11722. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  11723. return error(errInvalidRollupPhaseForChunkEmission());
  11724. }
  11725. if (typeof emittedChunk.id !== 'string') {
  11726. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  11727. }
  11728. const consumedChunk = {
  11729. fileName: emittedChunk.fileName,
  11730. module: null,
  11731. name: emittedChunk.name || emittedChunk.id,
  11732. type: 'chunk'
  11733. };
  11734. this.graph.moduleLoader
  11735. .emitChunk(emittedChunk)
  11736. .then(module => (consumedChunk.module = module))
  11737. .catch(() => {
  11738. // Avoid unhandled Promise rejection as the error will be thrown later
  11739. // once module loading has finished
  11740. });
  11741. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  11742. }
  11743. finalizeAsset(consumedFile, source, referenceId, output) {
  11744. const fileName = consumedFile.fileName ||
  11745. findExistingAssetFileNameWithSource(output.bundle, source) ||
  11746. generateAssetFileName(consumedFile.name, source, output);
  11747. // We must not modify the original assets to avoid interaction between outputs
  11748. const assetWithFileName = { ...consumedFile, source, fileName };
  11749. this.filesByReferenceId.set(referenceId, assetWithFileName);
  11750. const options = this.options;
  11751. output.bundle[fileName] = {
  11752. fileName,
  11753. name: consumedFile.name,
  11754. get isAsset() {
  11755. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  11756. return true;
  11757. },
  11758. source,
  11759. type: 'asset'
  11760. };
  11761. }
  11762. }
  11763. function findExistingAssetFileNameWithSource(bundle, source) {
  11764. for (const fileName of Object.keys(bundle)) {
  11765. const outputFile = bundle[fileName];
  11766. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  11767. return fileName;
  11768. }
  11769. return null;
  11770. }
  11771. function areSourcesEqual(sourceA, sourceB) {
  11772. if (typeof sourceA === 'string') {
  11773. return sourceA === sourceB;
  11774. }
  11775. if (typeof sourceB === 'string') {
  11776. return false;
  11777. }
  11778. if ('equals' in sourceA) {
  11779. return sourceA.equals(sourceB);
  11780. }
  11781. if (sourceA.length !== sourceB.length) {
  11782. return false;
  11783. }
  11784. for (let index = 0; index < sourceA.length; index++) {
  11785. if (sourceA[index] !== sourceB[index]) {
  11786. return false;
  11787. }
  11788. }
  11789. return true;
  11790. }
  11791. class Bundle$1 {
  11792. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  11793. this.outputOptions = outputOptions;
  11794. this.unsetOptions = unsetOptions;
  11795. this.inputOptions = inputOptions;
  11796. this.pluginDriver = pluginDriver;
  11797. this.graph = graph;
  11798. this.facadeChunkByModule = new Map();
  11799. this.includedNamespaces = new Set();
  11800. }
  11801. async generate(isWrite) {
  11802. timeStart('GENERATE', 1);
  11803. const outputBundle = Object.create(null);
  11804. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions.assetFileNames, this.facadeChunkByModule);
  11805. try {
  11806. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  11807. timeStart('generate chunks', 2);
  11808. const chunks = await this.generateChunks();
  11809. if (chunks.length > 1) {
  11810. validateOptionsForMultiChunkOutput(this.outputOptions);
  11811. }
  11812. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  11813. timeEnd('generate chunks', 2);
  11814. timeStart('render modules', 2);
  11815. // We need to create addons before prerender because at the moment, there
  11816. // can be no async code between prerender and render due to internal state
  11817. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  11818. this.prerenderChunks(chunks, inputBase);
  11819. timeEnd('render modules', 2);
  11820. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
  11821. }
  11822. catch (error) {
  11823. await this.pluginDriver.hookParallel('renderError', [error]);
  11824. throw error;
  11825. }
  11826. await this.pluginDriver.hookSeq('generateBundle', [
  11827. this.outputOptions,
  11828. outputBundle,
  11829. isWrite
  11830. ]);
  11831. this.finaliseAssets(outputBundle);
  11832. timeEnd('GENERATE', 1);
  11833. return outputBundle;
  11834. }
  11835. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
  11836. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  11837. for (const chunk of chunks) {
  11838. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  11839. }
  11840. await Promise.all(chunks.map(async (chunk) => {
  11841. const outputChunk = outputBundle[chunk.id];
  11842. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
  11843. }));
  11844. }
  11845. async addManualChunks(manualChunks) {
  11846. const manualChunkAliasByEntry = new Map();
  11847. const chunkEntries = await Promise.all(Object.keys(manualChunks).map(async (alias) => ({
  11848. alias,
  11849. entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
  11850. })));
  11851. for (const { alias, entries } of chunkEntries) {
  11852. for (const entry of entries) {
  11853. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  11854. }
  11855. }
  11856. return manualChunkAliasByEntry;
  11857. }
  11858. assignChunkIds(chunks, inputBase, addons, bundle) {
  11859. const entryChunks = [];
  11860. const otherChunks = [];
  11861. for (const chunk of chunks) {
  11862. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  11863. ? entryChunks
  11864. : otherChunks).push(chunk);
  11865. }
  11866. // make sure entry chunk names take precedence with regard to deconflicting
  11867. const chunksForNaming = entryChunks.concat(otherChunks);
  11868. for (const chunk of chunksForNaming) {
  11869. if (this.outputOptions.file) {
  11870. chunk.id = basename(this.outputOptions.file);
  11871. }
  11872. else if (this.outputOptions.preserveModules) {
  11873. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  11874. }
  11875. else {
  11876. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  11877. }
  11878. bundle[chunk.id] = FILE_PLACEHOLDER;
  11879. }
  11880. }
  11881. assignManualChunks(getManualChunk) {
  11882. const manualChunkAliasByEntry = new Map();
  11883. const manualChunksApi = {
  11884. getModuleIds: () => this.graph.modulesById.keys(),
  11885. getModuleInfo: this.graph.getModuleInfo
  11886. };
  11887. for (const module of this.graph.modulesById.values()) {
  11888. if (module instanceof Module) {
  11889. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  11890. if (typeof manualChunkAlias === 'string') {
  11891. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  11892. }
  11893. }
  11894. }
  11895. return manualChunkAliasByEntry;
  11896. }
  11897. finaliseAssets(outputBundle) {
  11898. for (const key of Object.keys(outputBundle)) {
  11899. const file = outputBundle[key];
  11900. if (!file.type) {
  11901. 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);
  11902. file.type = 'asset';
  11903. }
  11904. }
  11905. this.pluginDriver.finaliseAssets();
  11906. }
  11907. async generateChunks() {
  11908. const { manualChunks } = this.outputOptions;
  11909. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  11910. ? await this.addManualChunks(manualChunks)
  11911. : this.assignManualChunks(manualChunks);
  11912. const chunks = [];
  11913. const chunkByModule = new Map();
  11914. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  11915. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  11916. : this.outputOptions.preserveModules
  11917. ? getIncludedModules(this.graph.modulesById).map(module => ({
  11918. alias: null,
  11919. modules: [module]
  11920. }))
  11921. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  11922. sortByExecutionOrder(modules);
  11923. const chunk = new Chunk$1(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  11924. chunks.push(chunk);
  11925. for (const module of modules) {
  11926. chunkByModule.set(module, chunk);
  11927. }
  11928. }
  11929. for (const chunk of chunks) {
  11930. chunk.link();
  11931. }
  11932. const facades = [];
  11933. for (const chunk of chunks) {
  11934. facades.push(...chunk.generateFacades());
  11935. }
  11936. return [...chunks, ...facades];
  11937. }
  11938. prerenderChunks(chunks, inputBase) {
  11939. for (const chunk of chunks) {
  11940. chunk.generateExports();
  11941. }
  11942. for (const chunk of chunks) {
  11943. chunk.preRender(this.outputOptions, inputBase);
  11944. }
  11945. }
  11946. }
  11947. function getAbsoluteEntryModulePaths(chunks) {
  11948. const absoluteEntryModulePaths = [];
  11949. for (const chunk of chunks) {
  11950. for (const entryModule of chunk.entryModules) {
  11951. if (isAbsolute(entryModule.id)) {
  11952. absoluteEntryModulePaths.push(entryModule.id);
  11953. }
  11954. }
  11955. }
  11956. return absoluteEntryModulePaths;
  11957. }
  11958. function validateOptionsForMultiChunkOutput(outputOptions) {
  11959. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  11960. return error({
  11961. code: 'INVALID_OPTION',
  11962. message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
  11963. });
  11964. if (typeof outputOptions.file === 'string')
  11965. return error({
  11966. code: 'INVALID_OPTION',
  11967. message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
  11968. 'To inline dynamic imports, set the "inlineDynamicImports" option.'
  11969. });
  11970. if (outputOptions.sourcemapFile)
  11971. return error({
  11972. code: 'INVALID_OPTION',
  11973. message: '"output.sourcemapFile" is only supported for single-file builds.'
  11974. });
  11975. }
  11976. function getIncludedModules(modulesById) {
  11977. return [...modulesById.values()].filter(module => module instanceof Module &&
  11978. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  11979. }
  11980. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  11981. const existingAlias = manualChunkAliasByEntry.get(module);
  11982. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  11983. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  11984. }
  11985. manualChunkAliasByEntry.set(module, alias);
  11986. }
  11987. // Reserved word lists for various dialects of the language
  11988. var reservedWords$1 = {
  11989. 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",
  11990. 5: "class enum extends super const export import",
  11991. 6: "enum",
  11992. strict: "implements interface let package private protected public static yield",
  11993. strictBind: "eval arguments"
  11994. };
  11995. // And the keywords
  11996. 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";
  11997. var keywords = {
  11998. 5: ecma5AndLessKeywords,
  11999. "5module": ecma5AndLessKeywords + " export import",
  12000. 6: ecma5AndLessKeywords + " const class extends export import super"
  12001. };
  12002. var keywordRelationalOperator = /^in(stanceof)?$/;
  12003. // ## Character categories
  12004. // Big ugly regular expressions that match characters in the
  12005. // whitespace, identifier, and identifier-start categories. These
  12006. // are only applied when a character is found to actually have a
  12007. // code point above 128.
  12008. // Generated by `bin/generate-identifier-regex.js`.
  12009. 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";
  12010. 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";
  12011. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  12012. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  12013. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  12014. // These are a run-length and offset encoded representation of the
  12015. // >0xffff code points that are a valid part of identifiers. The
  12016. // offset starts at 0x10000, and each pair of numbers represents an
  12017. // offset to the next range, and then a size of the range. They were
  12018. // generated by bin/generate-identifier-regex.js
  12019. // eslint-disable-next-line comma-spacing
  12020. 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];
  12021. // eslint-disable-next-line comma-spacing
  12022. 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];
  12023. // This has a complexity linear to the value of the code. The
  12024. // assumption is that looking up astral identifier characters is
  12025. // rare.
  12026. function isInAstralSet(code, set) {
  12027. var pos = 0x10000;
  12028. for (var i = 0; i < set.length; i += 2) {
  12029. pos += set[i];
  12030. if (pos > code) { return false }
  12031. pos += set[i + 1];
  12032. if (pos >= code) { return true }
  12033. }
  12034. }
  12035. // Test whether a given character code starts an identifier.
  12036. function isIdentifierStart(code, astral) {
  12037. if (code < 65) { return code === 36 }
  12038. if (code < 91) { return true }
  12039. if (code < 97) { return code === 95 }
  12040. if (code < 123) { return true }
  12041. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  12042. if (astral === false) { return false }
  12043. return isInAstralSet(code, astralIdentifierStartCodes)
  12044. }
  12045. // Test whether a given character is part of an identifier.
  12046. function isIdentifierChar(code, astral) {
  12047. if (code < 48) { return code === 36 }
  12048. if (code < 58) { return true }
  12049. if (code < 65) { return false }
  12050. if (code < 91) { return true }
  12051. if (code < 97) { return code === 95 }
  12052. if (code < 123) { return true }
  12053. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  12054. if (astral === false) { return false }
  12055. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  12056. }
  12057. // ## Token types
  12058. // The assignment of fine-grained, information-carrying type objects
  12059. // allows the tokenizer to store the information it has about a
  12060. // token in a way that is very cheap for the parser to look up.
  12061. // All token type variables start with an underscore, to make them
  12062. // easy to recognize.
  12063. // The `beforeExpr` property is used to disambiguate between regular
  12064. // expressions and divisions. It is set on all token types that can
  12065. // be followed by an expression (thus, a slash after them would be a
  12066. // regular expression).
  12067. //
  12068. // The `startsExpr` property is used to check if the token ends a
  12069. // `yield` expression. It is set on all token types that either can
  12070. // directly start an expression (like a quotation mark) or can
  12071. // continue an expression (like the body of a string).
  12072. //
  12073. // `isLoop` marks a keyword as starting a loop, which is important
  12074. // to know when parsing a label, in order to allow or disallow
  12075. // continue jumps to that label.
  12076. var TokenType = function TokenType(label, conf) {
  12077. if ( conf === void 0 ) conf = {};
  12078. this.label = label;
  12079. this.keyword = conf.keyword;
  12080. this.beforeExpr = !!conf.beforeExpr;
  12081. this.startsExpr = !!conf.startsExpr;
  12082. this.isLoop = !!conf.isLoop;
  12083. this.isAssign = !!conf.isAssign;
  12084. this.prefix = !!conf.prefix;
  12085. this.postfix = !!conf.postfix;
  12086. this.binop = conf.binop || null;
  12087. this.updateContext = null;
  12088. };
  12089. function binop(name, prec) {
  12090. return new TokenType(name, {beforeExpr: true, binop: prec})
  12091. }
  12092. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  12093. // Map keyword names to token types.
  12094. var keywords$1 = {};
  12095. // Succinct definitions of keyword token types
  12096. function kw(name, options) {
  12097. if ( options === void 0 ) options = {};
  12098. options.keyword = name;
  12099. return keywords$1[name] = new TokenType(name, options)
  12100. }
  12101. var types = {
  12102. num: new TokenType("num", startsExpr),
  12103. regexp: new TokenType("regexp", startsExpr),
  12104. string: new TokenType("string", startsExpr),
  12105. name: new TokenType("name", startsExpr),
  12106. eof: new TokenType("eof"),
  12107. // Punctuation token types.
  12108. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  12109. bracketR: new TokenType("]"),
  12110. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  12111. braceR: new TokenType("}"),
  12112. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  12113. parenR: new TokenType(")"),
  12114. comma: new TokenType(",", beforeExpr),
  12115. semi: new TokenType(";", beforeExpr),
  12116. colon: new TokenType(":", beforeExpr),
  12117. dot: new TokenType("."),
  12118. question: new TokenType("?", beforeExpr),
  12119. questionDot: new TokenType("?."),
  12120. arrow: new TokenType("=>", beforeExpr),
  12121. template: new TokenType("template"),
  12122. invalidTemplate: new TokenType("invalidTemplate"),
  12123. ellipsis: new TokenType("...", beforeExpr),
  12124. backQuote: new TokenType("`", startsExpr),
  12125. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  12126. // Operators. These carry several kinds of properties to help the
  12127. // parser use them properly (the presence of these properties is
  12128. // what categorizes them as operators).
  12129. //
  12130. // `binop`, when present, specifies that this operator is a binary
  12131. // operator, and will refer to its precedence.
  12132. //
  12133. // `prefix` and `postfix` mark the operator as a prefix or postfix
  12134. // unary operator.
  12135. //
  12136. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  12137. // binary operators with a very low precedence, that should result
  12138. // in AssignmentExpression nodes.
  12139. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  12140. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  12141. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  12142. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  12143. logicalOR: binop("||", 1),
  12144. logicalAND: binop("&&", 2),
  12145. bitwiseOR: binop("|", 3),
  12146. bitwiseXOR: binop("^", 4),
  12147. bitwiseAND: binop("&", 5),
  12148. equality: binop("==/!=/===/!==", 6),
  12149. relational: binop("</>/<=/>=", 7),
  12150. bitShift: binop("<</>>/>>>", 8),
  12151. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  12152. modulo: binop("%", 10),
  12153. star: binop("*", 10),
  12154. slash: binop("/", 10),
  12155. starstar: new TokenType("**", {beforeExpr: true}),
  12156. coalesce: binop("??", 1),
  12157. // Keyword token types.
  12158. _break: kw("break"),
  12159. _case: kw("case", beforeExpr),
  12160. _catch: kw("catch"),
  12161. _continue: kw("continue"),
  12162. _debugger: kw("debugger"),
  12163. _default: kw("default", beforeExpr),
  12164. _do: kw("do", {isLoop: true, beforeExpr: true}),
  12165. _else: kw("else", beforeExpr),
  12166. _finally: kw("finally"),
  12167. _for: kw("for", {isLoop: true}),
  12168. _function: kw("function", startsExpr),
  12169. _if: kw("if"),
  12170. _return: kw("return", beforeExpr),
  12171. _switch: kw("switch"),
  12172. _throw: kw("throw", beforeExpr),
  12173. _try: kw("try"),
  12174. _var: kw("var"),
  12175. _const: kw("const"),
  12176. _while: kw("while", {isLoop: true}),
  12177. _with: kw("with"),
  12178. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  12179. _this: kw("this", startsExpr),
  12180. _super: kw("super", startsExpr),
  12181. _class: kw("class", startsExpr),
  12182. _extends: kw("extends", beforeExpr),
  12183. _export: kw("export"),
  12184. _import: kw("import", startsExpr),
  12185. _null: kw("null", startsExpr),
  12186. _true: kw("true", startsExpr),
  12187. _false: kw("false", startsExpr),
  12188. _in: kw("in", {beforeExpr: true, binop: 7}),
  12189. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  12190. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  12191. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  12192. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  12193. };
  12194. // Matches a whole line break (where CRLF is considered a single
  12195. // line break). Used to count lines.
  12196. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  12197. var lineBreakG = new RegExp(lineBreak.source, "g");
  12198. function isNewLine(code, ecma2019String) {
  12199. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  12200. }
  12201. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  12202. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  12203. var ref = Object.prototype;
  12204. var hasOwnProperty = ref.hasOwnProperty;
  12205. var toString$1 = ref.toString;
  12206. // Checks if an object has a property.
  12207. function has(obj, propName) {
  12208. return hasOwnProperty.call(obj, propName)
  12209. }
  12210. var isArray = Array.isArray || (function (obj) { return (
  12211. toString$1.call(obj) === "[object Array]"
  12212. ); });
  12213. function wordsRegexp(words) {
  12214. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  12215. }
  12216. // These are used when `options.locations` is on, for the
  12217. // `startLoc` and `endLoc` properties.
  12218. var Position = function Position(line, col) {
  12219. this.line = line;
  12220. this.column = col;
  12221. };
  12222. Position.prototype.offset = function offset (n) {
  12223. return new Position(this.line, this.column + n)
  12224. };
  12225. var SourceLocation = function SourceLocation(p, start, end) {
  12226. this.start = start;
  12227. this.end = end;
  12228. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  12229. };
  12230. // The `getLineInfo` function is mostly useful when the
  12231. // `locations` option is off (for performance reasons) and you
  12232. // want to find the line/column position for a given character
  12233. // offset. `input` should be the code string that the offset refers
  12234. // into.
  12235. function getLineInfo(input, offset) {
  12236. for (var line = 1, cur = 0;;) {
  12237. lineBreakG.lastIndex = cur;
  12238. var match = lineBreakG.exec(input);
  12239. if (match && match.index < offset) {
  12240. ++line;
  12241. cur = match.index + match[0].length;
  12242. } else {
  12243. return new Position(line, offset - cur)
  12244. }
  12245. }
  12246. }
  12247. // A second argument must be given to configure the parser process.
  12248. // These options are recognized (only `ecmaVersion` is required):
  12249. var defaultOptions = {
  12250. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  12251. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  12252. // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version
  12253. // the library supports). This influences support for strict mode,
  12254. // the set of reserved words, and support for new syntax features.
  12255. ecmaVersion: null,
  12256. // `sourceType` indicates the mode the code should be parsed in.
  12257. // Can be either `"script"` or `"module"`. This influences global
  12258. // strict mode and parsing of `import` and `export` declarations.
  12259. sourceType: "script",
  12260. // `onInsertedSemicolon` can be a callback that will be called
  12261. // when a semicolon is automatically inserted. It will be passed
  12262. // the position of the comma as an offset, and if `locations` is
  12263. // enabled, it is given the location as a `{line, column}` object
  12264. // as second argument.
  12265. onInsertedSemicolon: null,
  12266. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  12267. // trailing commas.
  12268. onTrailingComma: null,
  12269. // By default, reserved words are only enforced if ecmaVersion >= 5.
  12270. // Set `allowReserved` to a boolean value to explicitly turn this on
  12271. // an off. When this option has the value "never", reserved words
  12272. // and keywords can also not be used as property names.
  12273. allowReserved: null,
  12274. // When enabled, a return at the top level is not considered an
  12275. // error.
  12276. allowReturnOutsideFunction: false,
  12277. // When enabled, import/export statements are not constrained to
  12278. // appearing at the top of the program.
  12279. allowImportExportEverywhere: false,
  12280. // When enabled, await identifiers are allowed to appear at the top-level scope,
  12281. // but they are still not allowed in non-async functions.
  12282. allowAwaitOutsideFunction: false,
  12283. // When enabled, hashbang directive in the beginning of file
  12284. // is allowed and treated as a line comment.
  12285. allowHashBang: false,
  12286. // When `locations` is on, `loc` properties holding objects with
  12287. // `start` and `end` properties in `{line, column}` form (with
  12288. // line being 1-based and column 0-based) will be attached to the
  12289. // nodes.
  12290. locations: false,
  12291. // A function can be passed as `onToken` option, which will
  12292. // cause Acorn to call that function with object in the same
  12293. // format as tokens returned from `tokenizer().getToken()`. Note
  12294. // that you are not allowed to call the parser from the
  12295. // callback—that will corrupt its internal state.
  12296. onToken: null,
  12297. // A function can be passed as `onComment` option, which will
  12298. // cause Acorn to call that function with `(block, text, start,
  12299. // end)` parameters whenever a comment is skipped. `block` is a
  12300. // boolean indicating whether this is a block (`/* */`) comment,
  12301. // `text` is the content of the comment, and `start` and `end` are
  12302. // character offsets that denote the start and end of the comment.
  12303. // When the `locations` option is on, two more parameters are
  12304. // passed, the full `{line, column}` locations of the start and
  12305. // end of the comments. Note that you are not allowed to call the
  12306. // parser from the callback—that will corrupt its internal state.
  12307. onComment: null,
  12308. // Nodes have their start and end characters offsets recorded in
  12309. // `start` and `end` properties (directly on the node, rather than
  12310. // the `loc` object, which holds line/column data. To also add a
  12311. // [semi-standardized][range] `range` property holding a `[start,
  12312. // end]` array with the same numbers, set the `ranges` option to
  12313. // `true`.
  12314. //
  12315. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  12316. ranges: false,
  12317. // It is possible to parse multiple files into a single AST by
  12318. // passing the tree produced by parsing the first file as
  12319. // `program` option in subsequent parses. This will add the
  12320. // toplevel forms of the parsed file to the `Program` (top) node
  12321. // of an existing parse tree.
  12322. program: null,
  12323. // When `locations` is on, you can pass this to record the source
  12324. // file in every node's `loc` object.
  12325. sourceFile: null,
  12326. // This value, if given, is stored in every node, whether
  12327. // `locations` is on or off.
  12328. directSourceFile: null,
  12329. // When enabled, parenthesized expressions are represented by
  12330. // (non-standard) ParenthesizedExpression nodes
  12331. preserveParens: false
  12332. };
  12333. // Interpret and default an options object
  12334. var warnedAboutEcmaVersion = false;
  12335. function getOptions(opts) {
  12336. var options = {};
  12337. for (var opt in defaultOptions)
  12338. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  12339. if (options.ecmaVersion === "latest") {
  12340. options.ecmaVersion = 1e8;
  12341. } else if (options.ecmaVersion == null) {
  12342. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  12343. warnedAboutEcmaVersion = true;
  12344. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  12345. }
  12346. options.ecmaVersion = 11;
  12347. } else if (options.ecmaVersion >= 2015) {
  12348. options.ecmaVersion -= 2009;
  12349. }
  12350. if (options.allowReserved == null)
  12351. { options.allowReserved = options.ecmaVersion < 5; }
  12352. if (isArray(options.onToken)) {
  12353. var tokens = options.onToken;
  12354. options.onToken = function (token) { return tokens.push(token); };
  12355. }
  12356. if (isArray(options.onComment))
  12357. { options.onComment = pushComment(options, options.onComment); }
  12358. return options
  12359. }
  12360. function pushComment(options, array) {
  12361. return function(block, text, start, end, startLoc, endLoc) {
  12362. var comment = {
  12363. type: block ? "Block" : "Line",
  12364. value: text,
  12365. start: start,
  12366. end: end
  12367. };
  12368. if (options.locations)
  12369. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  12370. if (options.ranges)
  12371. { comment.range = [start, end]; }
  12372. array.push(comment);
  12373. }
  12374. }
  12375. // Each scope gets a bitset that may contain these flags
  12376. var
  12377. SCOPE_TOP = 1,
  12378. SCOPE_FUNCTION = 2,
  12379. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  12380. SCOPE_ASYNC = 4,
  12381. SCOPE_GENERATOR = 8,
  12382. SCOPE_ARROW = 16,
  12383. SCOPE_SIMPLE_CATCH = 32,
  12384. SCOPE_SUPER = 64,
  12385. SCOPE_DIRECT_SUPER = 128;
  12386. function functionFlags(async, generator) {
  12387. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  12388. }
  12389. // Used in checkLVal* and declareName to determine the type of a binding
  12390. var
  12391. BIND_NONE = 0, // Not a binding
  12392. BIND_VAR = 1, // Var-style binding
  12393. BIND_LEXICAL = 2, // Let- or const-style binding
  12394. BIND_FUNCTION = 3, // Function declaration
  12395. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  12396. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  12397. var Parser = function Parser(options, input, startPos) {
  12398. this.options = options = getOptions(options);
  12399. this.sourceFile = options.sourceFile;
  12400. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  12401. var reserved = "";
  12402. if (options.allowReserved !== true) {
  12403. reserved = reservedWords$1[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  12404. if (options.sourceType === "module") { reserved += " await"; }
  12405. }
  12406. this.reservedWords = wordsRegexp(reserved);
  12407. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$1.strict;
  12408. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  12409. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords$1.strictBind);
  12410. this.input = String(input);
  12411. // Used to signal to callers of `readWord1` whether the word
  12412. // contained any escape sequences. This is needed because words with
  12413. // escape sequences must not be interpreted as keywords.
  12414. this.containsEsc = false;
  12415. // Set up token state
  12416. // The current position of the tokenizer in the input.
  12417. if (startPos) {
  12418. this.pos = startPos;
  12419. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  12420. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  12421. } else {
  12422. this.pos = this.lineStart = 0;
  12423. this.curLine = 1;
  12424. }
  12425. // Properties of the current token:
  12426. // Its type
  12427. this.type = types.eof;
  12428. // For tokens that include more information than their type, the value
  12429. this.value = null;
  12430. // Its start and end offset
  12431. this.start = this.end = this.pos;
  12432. // And, if locations are used, the {line, column} object
  12433. // corresponding to those offsets
  12434. this.startLoc = this.endLoc = this.curPosition();
  12435. // Position information for the previous token
  12436. this.lastTokEndLoc = this.lastTokStartLoc = null;
  12437. this.lastTokStart = this.lastTokEnd = this.pos;
  12438. // The context stack is used to superficially track syntactic
  12439. // context to predict whether a regular expression is allowed in a
  12440. // given position.
  12441. this.context = this.initialContext();
  12442. this.exprAllowed = true;
  12443. // Figure out if it's a module code.
  12444. this.inModule = options.sourceType === "module";
  12445. this.strict = this.inModule || this.strictDirective(this.pos);
  12446. // Used to signify the start of a potential arrow function
  12447. this.potentialArrowAt = -1;
  12448. // Positions to delayed-check that yield/await does not exist in default parameters.
  12449. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  12450. // Labels in scope.
  12451. this.labels = [];
  12452. // Thus-far undefined exports.
  12453. this.undefinedExports = {};
  12454. // If enabled, skip leading hashbang line.
  12455. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  12456. { this.skipLineComment(2); }
  12457. // Scope tracking for duplicate variable names (see scope.js)
  12458. this.scopeStack = [];
  12459. this.enterScope(SCOPE_TOP);
  12460. // For RegExp validation
  12461. this.regexpState = null;
  12462. };
  12463. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  12464. Parser.prototype.parse = function parse () {
  12465. var node = this.options.program || this.startNode();
  12466. this.nextToken();
  12467. return this.parseTopLevel(node)
  12468. };
  12469. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  12470. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
  12471. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
  12472. prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
  12473. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  12474. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  12475. prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
  12476. Parser.extend = function extend () {
  12477. var plugins = [], len = arguments.length;
  12478. while ( len-- ) plugins[ len ] = arguments[ len ];
  12479. var cls = this;
  12480. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  12481. return cls
  12482. };
  12483. Parser.parse = function parse (input, options) {
  12484. return new this(options, input).parse()
  12485. };
  12486. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  12487. var parser = new this(options, input, pos);
  12488. parser.nextToken();
  12489. return parser.parseExpression()
  12490. };
  12491. Parser.tokenizer = function tokenizer (input, options) {
  12492. return new this(options, input)
  12493. };
  12494. Object.defineProperties( Parser.prototype, prototypeAccessors );
  12495. var pp = Parser.prototype;
  12496. // ## Parser utilities
  12497. var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/;
  12498. pp.strictDirective = function(start) {
  12499. for (;;) {
  12500. // Try to find string literal.
  12501. skipWhiteSpace.lastIndex = start;
  12502. start += skipWhiteSpace.exec(this.input)[0].length;
  12503. var match = literal.exec(this.input.slice(start));
  12504. if (!match) { return false }
  12505. if ((match[1] || match[2]) === "use strict") {
  12506. skipWhiteSpace.lastIndex = start + match[0].length;
  12507. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  12508. var next = this.input.charAt(end);
  12509. return next === ";" || next === "}" ||
  12510. (lineBreak.test(spaceAfter[0]) &&
  12511. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  12512. }
  12513. start += match[0].length;
  12514. // Skip semicolon, if any.
  12515. skipWhiteSpace.lastIndex = start;
  12516. start += skipWhiteSpace.exec(this.input)[0].length;
  12517. if (this.input[start] === ";")
  12518. { start++; }
  12519. }
  12520. };
  12521. // Predicate that tests whether the next token is of the given
  12522. // type, and if yes, consumes it as a side effect.
  12523. pp.eat = function(type) {
  12524. if (this.type === type) {
  12525. this.next();
  12526. return true
  12527. } else {
  12528. return false
  12529. }
  12530. };
  12531. // Tests whether parsed token is a contextual keyword.
  12532. pp.isContextual = function(name) {
  12533. return this.type === types.name && this.value === name && !this.containsEsc
  12534. };
  12535. // Consumes contextual keyword if possible.
  12536. pp.eatContextual = function(name) {
  12537. if (!this.isContextual(name)) { return false }
  12538. this.next();
  12539. return true
  12540. };
  12541. // Asserts that following token is given contextual keyword.
  12542. pp.expectContextual = function(name) {
  12543. if (!this.eatContextual(name)) { this.unexpected(); }
  12544. };
  12545. // Test whether a semicolon can be inserted at the current position.
  12546. pp.canInsertSemicolon = function() {
  12547. return this.type === types.eof ||
  12548. this.type === types.braceR ||
  12549. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  12550. };
  12551. pp.insertSemicolon = function() {
  12552. if (this.canInsertSemicolon()) {
  12553. if (this.options.onInsertedSemicolon)
  12554. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  12555. return true
  12556. }
  12557. };
  12558. // Consume a semicolon, or, failing that, see if we are allowed to
  12559. // pretend that there is a semicolon at this position.
  12560. pp.semicolon = function() {
  12561. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  12562. };
  12563. pp.afterTrailingComma = function(tokType, notNext) {
  12564. if (this.type === tokType) {
  12565. if (this.options.onTrailingComma)
  12566. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  12567. if (!notNext)
  12568. { this.next(); }
  12569. return true
  12570. }
  12571. };
  12572. // Expect a token of a given type. If found, consume it, otherwise,
  12573. // raise an unexpected token error.
  12574. pp.expect = function(type) {
  12575. this.eat(type) || this.unexpected();
  12576. };
  12577. // Raise an unexpected token error.
  12578. pp.unexpected = function(pos) {
  12579. this.raise(pos != null ? pos : this.start, "Unexpected token");
  12580. };
  12581. function DestructuringErrors() {
  12582. this.shorthandAssign =
  12583. this.trailingComma =
  12584. this.parenthesizedAssign =
  12585. this.parenthesizedBind =
  12586. this.doubleProto =
  12587. -1;
  12588. }
  12589. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  12590. if (!refDestructuringErrors) { return }
  12591. if (refDestructuringErrors.trailingComma > -1)
  12592. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  12593. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  12594. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  12595. };
  12596. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  12597. if (!refDestructuringErrors) { return false }
  12598. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  12599. var doubleProto = refDestructuringErrors.doubleProto;
  12600. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  12601. if (shorthandAssign >= 0)
  12602. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  12603. if (doubleProto >= 0)
  12604. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  12605. };
  12606. pp.checkYieldAwaitInDefaultParams = function() {
  12607. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  12608. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  12609. if (this.awaitPos)
  12610. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  12611. };
  12612. pp.isSimpleAssignTarget = function(expr) {
  12613. if (expr.type === "ParenthesizedExpression")
  12614. { return this.isSimpleAssignTarget(expr.expression) }
  12615. return expr.type === "Identifier" || expr.type === "MemberExpression"
  12616. };
  12617. var pp$1 = Parser.prototype;
  12618. // ### Statement parsing
  12619. // Parse a program. Initializes the parser, reads any number of
  12620. // statements, and wraps them in a Program node. Optionally takes a
  12621. // `program` argument. If present, the statements will be appended
  12622. // to its body instead of creating a new node.
  12623. pp$1.parseTopLevel = function(node) {
  12624. var exports = {};
  12625. if (!node.body) { node.body = []; }
  12626. while (this.type !== types.eof) {
  12627. var stmt = this.parseStatement(null, true, exports);
  12628. node.body.push(stmt);
  12629. }
  12630. if (this.inModule)
  12631. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  12632. {
  12633. var name = list[i];
  12634. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  12635. } }
  12636. this.adaptDirectivePrologue(node.body);
  12637. this.next();
  12638. node.sourceType = this.options.sourceType;
  12639. return this.finishNode(node, "Program")
  12640. };
  12641. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  12642. pp$1.isLet = function(context) {
  12643. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  12644. skipWhiteSpace.lastIndex = this.pos;
  12645. var skip = skipWhiteSpace.exec(this.input);
  12646. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  12647. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  12648. // Statement) is allowed here. If context is not empty then only a Statement
  12649. // is allowed. However, `let [` is an explicit negative lookahead for
  12650. // ExpressionStatement, so special-case it first.
  12651. if (nextCh === 91) { return true } // '['
  12652. if (context) { return false }
  12653. if (nextCh === 123) { return true } // '{'
  12654. if (isIdentifierStart(nextCh, true)) {
  12655. var pos = next + 1;
  12656. while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
  12657. var ident = this.input.slice(next, pos);
  12658. if (!keywordRelationalOperator.test(ident)) { return true }
  12659. }
  12660. return false
  12661. };
  12662. // check 'async [no LineTerminator here] function'
  12663. // - 'async /*foo*/ function' is OK.
  12664. // - 'async /*\n*/ function' is invalid.
  12665. pp$1.isAsyncFunction = function() {
  12666. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  12667. { return false }
  12668. skipWhiteSpace.lastIndex = this.pos;
  12669. var skip = skipWhiteSpace.exec(this.input);
  12670. var next = this.pos + skip[0].length;
  12671. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  12672. this.input.slice(next, next + 8) === "function" &&
  12673. (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
  12674. };
  12675. // Parse a single statement.
  12676. //
  12677. // If expecting a statement and finding a slash operator, parse a
  12678. // regular expression literal. This is to handle cases like
  12679. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  12680. // does not help.
  12681. pp$1.parseStatement = function(context, topLevel, exports) {
  12682. var starttype = this.type, node = this.startNode(), kind;
  12683. if (this.isLet(context)) {
  12684. starttype = types._var;
  12685. kind = "let";
  12686. }
  12687. // Most types of statements are recognized by the keyword they
  12688. // start with. Many are trivial to parse, some require a bit of
  12689. // complexity.
  12690. switch (starttype) {
  12691. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  12692. case types._debugger: return this.parseDebuggerStatement(node)
  12693. case types._do: return this.parseDoStatement(node)
  12694. case types._for: return this.parseForStatement(node)
  12695. case types._function:
  12696. // Function as sole body of either an if statement or a labeled statement
  12697. // works, but not when it is part of a labeled statement that is the sole
  12698. // body of an if statement.
  12699. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  12700. return this.parseFunctionStatement(node, false, !context)
  12701. case types._class:
  12702. if (context) { this.unexpected(); }
  12703. return this.parseClass(node, true)
  12704. case types._if: return this.parseIfStatement(node)
  12705. case types._return: return this.parseReturnStatement(node)
  12706. case types._switch: return this.parseSwitchStatement(node)
  12707. case types._throw: return this.parseThrowStatement(node)
  12708. case types._try: return this.parseTryStatement(node)
  12709. case types._const: case types._var:
  12710. kind = kind || this.value;
  12711. if (context && kind !== "var") { this.unexpected(); }
  12712. return this.parseVarStatement(node, kind)
  12713. case types._while: return this.parseWhileStatement(node)
  12714. case types._with: return this.parseWithStatement(node)
  12715. case types.braceL: return this.parseBlock(true, node)
  12716. case types.semi: return this.parseEmptyStatement(node)
  12717. case types._export:
  12718. case types._import:
  12719. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  12720. skipWhiteSpace.lastIndex = this.pos;
  12721. var skip = skipWhiteSpace.exec(this.input);
  12722. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  12723. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  12724. { return this.parseExpressionStatement(node, this.parseExpression()) }
  12725. }
  12726. if (!this.options.allowImportExportEverywhere) {
  12727. if (!topLevel)
  12728. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  12729. if (!this.inModule)
  12730. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  12731. }
  12732. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  12733. // If the statement does not start with a statement keyword or a
  12734. // brace, it's an ExpressionStatement or LabeledStatement. We
  12735. // simply start parsing an expression, and afterwards, if the
  12736. // next token is a colon and the expression was a simple
  12737. // Identifier node, we switch to interpreting it as a label.
  12738. default:
  12739. if (this.isAsyncFunction()) {
  12740. if (context) { this.unexpected(); }
  12741. this.next();
  12742. return this.parseFunctionStatement(node, true, !context)
  12743. }
  12744. var maybeName = this.value, expr = this.parseExpression();
  12745. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  12746. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  12747. else { return this.parseExpressionStatement(node, expr) }
  12748. }
  12749. };
  12750. pp$1.parseBreakContinueStatement = function(node, keyword) {
  12751. var isBreak = keyword === "break";
  12752. this.next();
  12753. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  12754. else if (this.type !== types.name) { this.unexpected(); }
  12755. else {
  12756. node.label = this.parseIdent();
  12757. this.semicolon();
  12758. }
  12759. // Verify that there is an actual destination to break or
  12760. // continue to.
  12761. var i = 0;
  12762. for (; i < this.labels.length; ++i) {
  12763. var lab = this.labels[i];
  12764. if (node.label == null || lab.name === node.label.name) {
  12765. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  12766. if (node.label && isBreak) { break }
  12767. }
  12768. }
  12769. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  12770. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  12771. };
  12772. pp$1.parseDebuggerStatement = function(node) {
  12773. this.next();
  12774. this.semicolon();
  12775. return this.finishNode(node, "DebuggerStatement")
  12776. };
  12777. pp$1.parseDoStatement = function(node) {
  12778. this.next();
  12779. this.labels.push(loopLabel);
  12780. node.body = this.parseStatement("do");
  12781. this.labels.pop();
  12782. this.expect(types._while);
  12783. node.test = this.parseParenExpression();
  12784. if (this.options.ecmaVersion >= 6)
  12785. { this.eat(types.semi); }
  12786. else
  12787. { this.semicolon(); }
  12788. return this.finishNode(node, "DoWhileStatement")
  12789. };
  12790. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  12791. // loop is non-trivial. Basically, we have to parse the init `var`
  12792. // statement or expression, disallowing the `in` operator (see
  12793. // the second parameter to `parseExpression`), and then check
  12794. // whether the next token is `in` or `of`. When there is no init
  12795. // part (semicolon immediately after the opening parenthesis), it
  12796. // is a regular `for` loop.
  12797. pp$1.parseForStatement = function(node) {
  12798. this.next();
  12799. var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
  12800. this.labels.push(loopLabel);
  12801. this.enterScope(0);
  12802. this.expect(types.parenL);
  12803. if (this.type === types.semi) {
  12804. if (awaitAt > -1) { this.unexpected(awaitAt); }
  12805. return this.parseFor(node, null)
  12806. }
  12807. var isLet = this.isLet();
  12808. if (this.type === types._var || this.type === types._const || isLet) {
  12809. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  12810. this.next();
  12811. this.parseVar(init$1, true, kind);
  12812. this.finishNode(init$1, "VariableDeclaration");
  12813. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  12814. if (this.options.ecmaVersion >= 9) {
  12815. if (this.type === types._in) {
  12816. if (awaitAt > -1) { this.unexpected(awaitAt); }
  12817. } else { node.await = awaitAt > -1; }
  12818. }
  12819. return this.parseForIn(node, init$1)
  12820. }
  12821. if (awaitAt > -1) { this.unexpected(awaitAt); }
  12822. return this.parseFor(node, init$1)
  12823. }
  12824. var refDestructuringErrors = new DestructuringErrors;
  12825. var init = this.parseExpression(true, refDestructuringErrors);
  12826. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  12827. if (this.options.ecmaVersion >= 9) {
  12828. if (this.type === types._in) {
  12829. if (awaitAt > -1) { this.unexpected(awaitAt); }
  12830. } else { node.await = awaitAt > -1; }
  12831. }
  12832. this.toAssignable(init, false, refDestructuringErrors);
  12833. this.checkLValPattern(init);
  12834. return this.parseForIn(node, init)
  12835. } else {
  12836. this.checkExpressionErrors(refDestructuringErrors, true);
  12837. }
  12838. if (awaitAt > -1) { this.unexpected(awaitAt); }
  12839. return this.parseFor(node, init)
  12840. };
  12841. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  12842. this.next();
  12843. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  12844. };
  12845. pp$1.parseIfStatement = function(node) {
  12846. this.next();
  12847. node.test = this.parseParenExpression();
  12848. // allow function declarations in branches, but only in non-strict mode
  12849. node.consequent = this.parseStatement("if");
  12850. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  12851. return this.finishNode(node, "IfStatement")
  12852. };
  12853. pp$1.parseReturnStatement = function(node) {
  12854. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  12855. { this.raise(this.start, "'return' outside of function"); }
  12856. this.next();
  12857. // In `return` (and `break`/`continue`), the keywords with
  12858. // optional arguments, we eagerly look for a semicolon or the
  12859. // possibility to insert one.
  12860. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  12861. else { node.argument = this.parseExpression(); this.semicolon(); }
  12862. return this.finishNode(node, "ReturnStatement")
  12863. };
  12864. pp$1.parseSwitchStatement = function(node) {
  12865. this.next();
  12866. node.discriminant = this.parseParenExpression();
  12867. node.cases = [];
  12868. this.expect(types.braceL);
  12869. this.labels.push(switchLabel);
  12870. this.enterScope(0);
  12871. // Statements under must be grouped (by label) in SwitchCase
  12872. // nodes. `cur` is used to keep the node that we are currently
  12873. // adding statements to.
  12874. var cur;
  12875. for (var sawDefault = false; this.type !== types.braceR;) {
  12876. if (this.type === types._case || this.type === types._default) {
  12877. var isCase = this.type === types._case;
  12878. if (cur) { this.finishNode(cur, "SwitchCase"); }
  12879. node.cases.push(cur = this.startNode());
  12880. cur.consequent = [];
  12881. this.next();
  12882. if (isCase) {
  12883. cur.test = this.parseExpression();
  12884. } else {
  12885. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  12886. sawDefault = true;
  12887. cur.test = null;
  12888. }
  12889. this.expect(types.colon);
  12890. } else {
  12891. if (!cur) { this.unexpected(); }
  12892. cur.consequent.push(this.parseStatement(null));
  12893. }
  12894. }
  12895. this.exitScope();
  12896. if (cur) { this.finishNode(cur, "SwitchCase"); }
  12897. this.next(); // Closing brace
  12898. this.labels.pop();
  12899. return this.finishNode(node, "SwitchStatement")
  12900. };
  12901. pp$1.parseThrowStatement = function(node) {
  12902. this.next();
  12903. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  12904. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  12905. node.argument = this.parseExpression();
  12906. this.semicolon();
  12907. return this.finishNode(node, "ThrowStatement")
  12908. };
  12909. // Reused empty array added for node fields that are always empty.
  12910. var empty = [];
  12911. pp$1.parseTryStatement = function(node) {
  12912. this.next();
  12913. node.block = this.parseBlock();
  12914. node.handler = null;
  12915. if (this.type === types._catch) {
  12916. var clause = this.startNode();
  12917. this.next();
  12918. if (this.eat(types.parenL)) {
  12919. clause.param = this.parseBindingAtom();
  12920. var simple = clause.param.type === "Identifier";
  12921. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  12922. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  12923. this.expect(types.parenR);
  12924. } else {
  12925. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  12926. clause.param = null;
  12927. this.enterScope(0);
  12928. }
  12929. clause.body = this.parseBlock(false);
  12930. this.exitScope();
  12931. node.handler = this.finishNode(clause, "CatchClause");
  12932. }
  12933. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  12934. if (!node.handler && !node.finalizer)
  12935. { this.raise(node.start, "Missing catch or finally clause"); }
  12936. return this.finishNode(node, "TryStatement")
  12937. };
  12938. pp$1.parseVarStatement = function(node, kind) {
  12939. this.next();
  12940. this.parseVar(node, false, kind);
  12941. this.semicolon();
  12942. return this.finishNode(node, "VariableDeclaration")
  12943. };
  12944. pp$1.parseWhileStatement = function(node) {
  12945. this.next();
  12946. node.test = this.parseParenExpression();
  12947. this.labels.push(loopLabel);
  12948. node.body = this.parseStatement("while");
  12949. this.labels.pop();
  12950. return this.finishNode(node, "WhileStatement")
  12951. };
  12952. pp$1.parseWithStatement = function(node) {
  12953. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  12954. this.next();
  12955. node.object = this.parseParenExpression();
  12956. node.body = this.parseStatement("with");
  12957. return this.finishNode(node, "WithStatement")
  12958. };
  12959. pp$1.parseEmptyStatement = function(node) {
  12960. this.next();
  12961. return this.finishNode(node, "EmptyStatement")
  12962. };
  12963. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  12964. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  12965. {
  12966. var label = list[i$1];
  12967. if (label.name === maybeName)
  12968. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  12969. } }
  12970. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  12971. for (var i = this.labels.length - 1; i >= 0; i--) {
  12972. var label$1 = this.labels[i];
  12973. if (label$1.statementStart === node.start) {
  12974. // Update information about previous labels on this node
  12975. label$1.statementStart = this.start;
  12976. label$1.kind = kind;
  12977. } else { break }
  12978. }
  12979. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  12980. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  12981. this.labels.pop();
  12982. node.label = expr;
  12983. return this.finishNode(node, "LabeledStatement")
  12984. };
  12985. pp$1.parseExpressionStatement = function(node, expr) {
  12986. node.expression = expr;
  12987. this.semicolon();
  12988. return this.finishNode(node, "ExpressionStatement")
  12989. };
  12990. // Parse a semicolon-enclosed block of statements, handling `"use
  12991. // strict"` declarations when `allowStrict` is true (used for
  12992. // function bodies).
  12993. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  12994. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  12995. if ( node === void 0 ) node = this.startNode();
  12996. node.body = [];
  12997. this.expect(types.braceL);
  12998. if (createNewLexicalScope) { this.enterScope(0); }
  12999. while (this.type !== types.braceR) {
  13000. var stmt = this.parseStatement(null);
  13001. node.body.push(stmt);
  13002. }
  13003. if (exitStrict) { this.strict = false; }
  13004. this.next();
  13005. if (createNewLexicalScope) { this.exitScope(); }
  13006. return this.finishNode(node, "BlockStatement")
  13007. };
  13008. // Parse a regular `for` loop. The disambiguation code in
  13009. // `parseStatement` will already have parsed the init statement or
  13010. // expression.
  13011. pp$1.parseFor = function(node, init) {
  13012. node.init = init;
  13013. this.expect(types.semi);
  13014. node.test = this.type === types.semi ? null : this.parseExpression();
  13015. this.expect(types.semi);
  13016. node.update = this.type === types.parenR ? null : this.parseExpression();
  13017. this.expect(types.parenR);
  13018. node.body = this.parseStatement("for");
  13019. this.exitScope();
  13020. this.labels.pop();
  13021. return this.finishNode(node, "ForStatement")
  13022. };
  13023. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  13024. // same from parser's perspective.
  13025. pp$1.parseForIn = function(node, init) {
  13026. var isForIn = this.type === types._in;
  13027. this.next();
  13028. if (
  13029. init.type === "VariableDeclaration" &&
  13030. init.declarations[0].init != null &&
  13031. (
  13032. !isForIn ||
  13033. this.options.ecmaVersion < 8 ||
  13034. this.strict ||
  13035. init.kind !== "var" ||
  13036. init.declarations[0].id.type !== "Identifier"
  13037. )
  13038. ) {
  13039. this.raise(
  13040. init.start,
  13041. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  13042. );
  13043. }
  13044. node.left = init;
  13045. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  13046. this.expect(types.parenR);
  13047. node.body = this.parseStatement("for");
  13048. this.exitScope();
  13049. this.labels.pop();
  13050. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  13051. };
  13052. // Parse a list of variable declarations.
  13053. pp$1.parseVar = function(node, isFor, kind) {
  13054. node.declarations = [];
  13055. node.kind = kind;
  13056. for (;;) {
  13057. var decl = this.startNode();
  13058. this.parseVarId(decl, kind);
  13059. if (this.eat(types.eq)) {
  13060. decl.init = this.parseMaybeAssign(isFor);
  13061. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  13062. this.unexpected();
  13063. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  13064. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  13065. } else {
  13066. decl.init = null;
  13067. }
  13068. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  13069. if (!this.eat(types.comma)) { break }
  13070. }
  13071. return node
  13072. };
  13073. pp$1.parseVarId = function(decl, kind) {
  13074. decl.id = this.parseBindingAtom();
  13075. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  13076. };
  13077. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  13078. // Parse a function declaration or literal (depending on the
  13079. // `statement & FUNC_STATEMENT`).
  13080. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  13081. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  13082. this.initFunction(node);
  13083. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  13084. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  13085. { this.unexpected(); }
  13086. node.generator = this.eat(types.star);
  13087. }
  13088. if (this.options.ecmaVersion >= 8)
  13089. { node.async = !!isAsync; }
  13090. if (statement & FUNC_STATEMENT) {
  13091. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  13092. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  13093. // If it is a regular function declaration in sloppy mode, then it is
  13094. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  13095. // mode depends on properties of the current scope (see
  13096. // treatFunctionsAsVar).
  13097. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  13098. }
  13099. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  13100. this.yieldPos = 0;
  13101. this.awaitPos = 0;
  13102. this.awaitIdentPos = 0;
  13103. this.enterScope(functionFlags(node.async, node.generator));
  13104. if (!(statement & FUNC_STATEMENT))
  13105. { node.id = this.type === types.name ? this.parseIdent() : null; }
  13106. this.parseFunctionParams(node);
  13107. this.parseFunctionBody(node, allowExpressionBody, false);
  13108. this.yieldPos = oldYieldPos;
  13109. this.awaitPos = oldAwaitPos;
  13110. this.awaitIdentPos = oldAwaitIdentPos;
  13111. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  13112. };
  13113. pp$1.parseFunctionParams = function(node) {
  13114. this.expect(types.parenL);
  13115. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  13116. this.checkYieldAwaitInDefaultParams();
  13117. };
  13118. // Parse a class declaration or literal (depending on the
  13119. // `isStatement` parameter).
  13120. pp$1.parseClass = function(node, isStatement) {
  13121. this.next();
  13122. // ecma-262 14.6 Class Definitions
  13123. // A class definition is always strict mode code.
  13124. var oldStrict = this.strict;
  13125. this.strict = true;
  13126. this.parseClassId(node, isStatement);
  13127. this.parseClassSuper(node);
  13128. var classBody = this.startNode();
  13129. var hadConstructor = false;
  13130. classBody.body = [];
  13131. this.expect(types.braceL);
  13132. while (this.type !== types.braceR) {
  13133. var element = this.parseClassElement(node.superClass !== null);
  13134. if (element) {
  13135. classBody.body.push(element);
  13136. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  13137. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  13138. hadConstructor = true;
  13139. }
  13140. }
  13141. }
  13142. this.strict = oldStrict;
  13143. this.next();
  13144. node.body = this.finishNode(classBody, "ClassBody");
  13145. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  13146. };
  13147. pp$1.parseClassElement = function(constructorAllowsSuper) {
  13148. var this$1 = this;
  13149. if (this.eat(types.semi)) { return null }
  13150. var method = this.startNode();
  13151. var tryContextual = function (k, noLineBreak) {
  13152. if ( noLineBreak === void 0 ) noLineBreak = false;
  13153. var start = this$1.start, startLoc = this$1.startLoc;
  13154. if (!this$1.eatContextual(k)) { return false }
  13155. if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
  13156. if (method.key) { this$1.unexpected(); }
  13157. method.computed = false;
  13158. method.key = this$1.startNodeAt(start, startLoc);
  13159. method.key.name = k;
  13160. this$1.finishNode(method.key, "Identifier");
  13161. return false
  13162. };
  13163. method.kind = "method";
  13164. method.static = tryContextual("static");
  13165. var isGenerator = this.eat(types.star);
  13166. var isAsync = false;
  13167. if (!isGenerator) {
  13168. if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
  13169. isAsync = true;
  13170. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  13171. } else if (tryContextual("get")) {
  13172. method.kind = "get";
  13173. } else if (tryContextual("set")) {
  13174. method.kind = "set";
  13175. }
  13176. }
  13177. if (!method.key) { this.parsePropertyName(method); }
  13178. var key = method.key;
  13179. var allowsDirectSuper = false;
  13180. if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
  13181. key.type === "Literal" && key.value === "constructor")) {
  13182. if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
  13183. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  13184. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  13185. method.kind = "constructor";
  13186. allowsDirectSuper = constructorAllowsSuper;
  13187. } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
  13188. this.raise(key.start, "Classes may not have a static property named prototype");
  13189. }
  13190. this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
  13191. if (method.kind === "get" && method.value.params.length !== 0)
  13192. { this.raiseRecoverable(method.value.start, "getter should have no params"); }
  13193. if (method.kind === "set" && method.value.params.length !== 1)
  13194. { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
  13195. if (method.kind === "set" && method.value.params[0].type === "RestElement")
  13196. { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
  13197. return method
  13198. };
  13199. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  13200. method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  13201. return this.finishNode(method, "MethodDefinition")
  13202. };
  13203. pp$1.parseClassId = function(node, isStatement) {
  13204. if (this.type === types.name) {
  13205. node.id = this.parseIdent();
  13206. if (isStatement)
  13207. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  13208. } else {
  13209. if (isStatement === true)
  13210. { this.unexpected(); }
  13211. node.id = null;
  13212. }
  13213. };
  13214. pp$1.parseClassSuper = function(node) {
  13215. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  13216. };
  13217. // Parses module export declaration.
  13218. pp$1.parseExport = function(node, exports) {
  13219. this.next();
  13220. // export * from '...'
  13221. if (this.eat(types.star)) {
  13222. if (this.options.ecmaVersion >= 11) {
  13223. if (this.eatContextual("as")) {
  13224. node.exported = this.parseIdent(true);
  13225. this.checkExport(exports, node.exported.name, this.lastTokStart);
  13226. } else {
  13227. node.exported = null;
  13228. }
  13229. }
  13230. this.expectContextual("from");
  13231. if (this.type !== types.string) { this.unexpected(); }
  13232. node.source = this.parseExprAtom();
  13233. this.semicolon();
  13234. return this.finishNode(node, "ExportAllDeclaration")
  13235. }
  13236. if (this.eat(types._default)) { // export default ...
  13237. this.checkExport(exports, "default", this.lastTokStart);
  13238. var isAsync;
  13239. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  13240. var fNode = this.startNode();
  13241. this.next();
  13242. if (isAsync) { this.next(); }
  13243. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  13244. } else if (this.type === types._class) {
  13245. var cNode = this.startNode();
  13246. node.declaration = this.parseClass(cNode, "nullableID");
  13247. } else {
  13248. node.declaration = this.parseMaybeAssign();
  13249. this.semicolon();
  13250. }
  13251. return this.finishNode(node, "ExportDefaultDeclaration")
  13252. }
  13253. // export var|const|let|function|class ...
  13254. if (this.shouldParseExportStatement()) {
  13255. node.declaration = this.parseStatement(null);
  13256. if (node.declaration.type === "VariableDeclaration")
  13257. { this.checkVariableExport(exports, node.declaration.declarations); }
  13258. else
  13259. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  13260. node.specifiers = [];
  13261. node.source = null;
  13262. } else { // export { x, y as z } [from '...']
  13263. node.declaration = null;
  13264. node.specifiers = this.parseExportSpecifiers(exports);
  13265. if (this.eatContextual("from")) {
  13266. if (this.type !== types.string) { this.unexpected(); }
  13267. node.source = this.parseExprAtom();
  13268. } else {
  13269. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  13270. // check for keywords used as local names
  13271. var spec = list[i];
  13272. this.checkUnreserved(spec.local);
  13273. // check if export is defined
  13274. this.checkLocalExport(spec.local);
  13275. }
  13276. node.source = null;
  13277. }
  13278. this.semicolon();
  13279. }
  13280. return this.finishNode(node, "ExportNamedDeclaration")
  13281. };
  13282. pp$1.checkExport = function(exports, name, pos) {
  13283. if (!exports) { return }
  13284. if (has(exports, name))
  13285. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  13286. exports[name] = true;
  13287. };
  13288. pp$1.checkPatternExport = function(exports, pat) {
  13289. var type = pat.type;
  13290. if (type === "Identifier")
  13291. { this.checkExport(exports, pat.name, pat.start); }
  13292. else if (type === "ObjectPattern")
  13293. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  13294. {
  13295. var prop = list[i];
  13296. this.checkPatternExport(exports, prop);
  13297. } }
  13298. else if (type === "ArrayPattern")
  13299. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  13300. var elt = list$1[i$1];
  13301. if (elt) { this.checkPatternExport(exports, elt); }
  13302. } }
  13303. else if (type === "Property")
  13304. { this.checkPatternExport(exports, pat.value); }
  13305. else if (type === "AssignmentPattern")
  13306. { this.checkPatternExport(exports, pat.left); }
  13307. else if (type === "RestElement")
  13308. { this.checkPatternExport(exports, pat.argument); }
  13309. else if (type === "ParenthesizedExpression")
  13310. { this.checkPatternExport(exports, pat.expression); }
  13311. };
  13312. pp$1.checkVariableExport = function(exports, decls) {
  13313. if (!exports) { return }
  13314. for (var i = 0, list = decls; i < list.length; i += 1)
  13315. {
  13316. var decl = list[i];
  13317. this.checkPatternExport(exports, decl.id);
  13318. }
  13319. };
  13320. pp$1.shouldParseExportStatement = function() {
  13321. return this.type.keyword === "var" ||
  13322. this.type.keyword === "const" ||
  13323. this.type.keyword === "class" ||
  13324. this.type.keyword === "function" ||
  13325. this.isLet() ||
  13326. this.isAsyncFunction()
  13327. };
  13328. // Parses a comma-separated list of module exports.
  13329. pp$1.parseExportSpecifiers = function(exports) {
  13330. var nodes = [], first = true;
  13331. // export { x, y as z } [from '...']
  13332. this.expect(types.braceL);
  13333. while (!this.eat(types.braceR)) {
  13334. if (!first) {
  13335. this.expect(types.comma);
  13336. if (this.afterTrailingComma(types.braceR)) { break }
  13337. } else { first = false; }
  13338. var node = this.startNode();
  13339. node.local = this.parseIdent(true);
  13340. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  13341. this.checkExport(exports, node.exported.name, node.exported.start);
  13342. nodes.push(this.finishNode(node, "ExportSpecifier"));
  13343. }
  13344. return nodes
  13345. };
  13346. // Parses import declaration.
  13347. pp$1.parseImport = function(node) {
  13348. this.next();
  13349. // import '...'
  13350. if (this.type === types.string) {
  13351. node.specifiers = empty;
  13352. node.source = this.parseExprAtom();
  13353. } else {
  13354. node.specifiers = this.parseImportSpecifiers();
  13355. this.expectContextual("from");
  13356. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  13357. }
  13358. this.semicolon();
  13359. return this.finishNode(node, "ImportDeclaration")
  13360. };
  13361. // Parses a comma-separated list of module imports.
  13362. pp$1.parseImportSpecifiers = function() {
  13363. var nodes = [], first = true;
  13364. if (this.type === types.name) {
  13365. // import defaultObj, { x, y as z } from '...'
  13366. var node = this.startNode();
  13367. node.local = this.parseIdent();
  13368. this.checkLValSimple(node.local, BIND_LEXICAL);
  13369. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  13370. if (!this.eat(types.comma)) { return nodes }
  13371. }
  13372. if (this.type === types.star) {
  13373. var node$1 = this.startNode();
  13374. this.next();
  13375. this.expectContextual("as");
  13376. node$1.local = this.parseIdent();
  13377. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  13378. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  13379. return nodes
  13380. }
  13381. this.expect(types.braceL);
  13382. while (!this.eat(types.braceR)) {
  13383. if (!first) {
  13384. this.expect(types.comma);
  13385. if (this.afterTrailingComma(types.braceR)) { break }
  13386. } else { first = false; }
  13387. var node$2 = this.startNode();
  13388. node$2.imported = this.parseIdent(true);
  13389. if (this.eatContextual("as")) {
  13390. node$2.local = this.parseIdent();
  13391. } else {
  13392. this.checkUnreserved(node$2.imported);
  13393. node$2.local = node$2.imported;
  13394. }
  13395. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  13396. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  13397. }
  13398. return nodes
  13399. };
  13400. // Set `ExpressionStatement#directive` property for directive prologues.
  13401. pp$1.adaptDirectivePrologue = function(statements) {
  13402. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  13403. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  13404. }
  13405. };
  13406. pp$1.isDirectiveCandidate = function(statement) {
  13407. return (
  13408. statement.type === "ExpressionStatement" &&
  13409. statement.expression.type === "Literal" &&
  13410. typeof statement.expression.value === "string" &&
  13411. // Reject parenthesized strings.
  13412. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  13413. )
  13414. };
  13415. var pp$2 = Parser.prototype;
  13416. // Convert existing expression atom to assignable pattern
  13417. // if possible.
  13418. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  13419. if (this.options.ecmaVersion >= 6 && node) {
  13420. switch (node.type) {
  13421. case "Identifier":
  13422. if (this.inAsync && node.name === "await")
  13423. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  13424. break
  13425. case "ObjectPattern":
  13426. case "ArrayPattern":
  13427. case "AssignmentPattern":
  13428. case "RestElement":
  13429. break
  13430. case "ObjectExpression":
  13431. node.type = "ObjectPattern";
  13432. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13433. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  13434. var prop = list[i];
  13435. this.toAssignable(prop, isBinding);
  13436. // Early error:
  13437. // AssignmentRestProperty[Yield, Await] :
  13438. // `...` DestructuringAssignmentTarget[Yield, Await]
  13439. //
  13440. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  13441. if (
  13442. prop.type === "RestElement" &&
  13443. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  13444. ) {
  13445. this.raise(prop.argument.start, "Unexpected token");
  13446. }
  13447. }
  13448. break
  13449. case "Property":
  13450. // AssignmentProperty has type === "Property"
  13451. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  13452. this.toAssignable(node.value, isBinding);
  13453. break
  13454. case "ArrayExpression":
  13455. node.type = "ArrayPattern";
  13456. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13457. this.toAssignableList(node.elements, isBinding);
  13458. break
  13459. case "SpreadElement":
  13460. node.type = "RestElement";
  13461. this.toAssignable(node.argument, isBinding);
  13462. if (node.argument.type === "AssignmentPattern")
  13463. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  13464. break
  13465. case "AssignmentExpression":
  13466. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  13467. node.type = "AssignmentPattern";
  13468. delete node.operator;
  13469. this.toAssignable(node.left, isBinding);
  13470. break
  13471. case "ParenthesizedExpression":
  13472. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  13473. break
  13474. case "ChainExpression":
  13475. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  13476. break
  13477. case "MemberExpression":
  13478. if (!isBinding) { break }
  13479. default:
  13480. this.raise(node.start, "Assigning to rvalue");
  13481. }
  13482. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13483. return node
  13484. };
  13485. // Convert list of expression atoms to binding list.
  13486. pp$2.toAssignableList = function(exprList, isBinding) {
  13487. var end = exprList.length;
  13488. for (var i = 0; i < end; i++) {
  13489. var elt = exprList[i];
  13490. if (elt) { this.toAssignable(elt, isBinding); }
  13491. }
  13492. if (end) {
  13493. var last = exprList[end - 1];
  13494. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  13495. { this.unexpected(last.argument.start); }
  13496. }
  13497. return exprList
  13498. };
  13499. // Parses spread element.
  13500. pp$2.parseSpread = function(refDestructuringErrors) {
  13501. var node = this.startNode();
  13502. this.next();
  13503. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  13504. return this.finishNode(node, "SpreadElement")
  13505. };
  13506. pp$2.parseRestBinding = function() {
  13507. var node = this.startNode();
  13508. this.next();
  13509. // RestElement inside of a function parameter must be an identifier
  13510. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  13511. { this.unexpected(); }
  13512. node.argument = this.parseBindingAtom();
  13513. return this.finishNode(node, "RestElement")
  13514. };
  13515. // Parses lvalue (assignable) atom.
  13516. pp$2.parseBindingAtom = function() {
  13517. if (this.options.ecmaVersion >= 6) {
  13518. switch (this.type) {
  13519. case types.bracketL:
  13520. var node = this.startNode();
  13521. this.next();
  13522. node.elements = this.parseBindingList(types.bracketR, true, true);
  13523. return this.finishNode(node, "ArrayPattern")
  13524. case types.braceL:
  13525. return this.parseObj(true)
  13526. }
  13527. }
  13528. return this.parseIdent()
  13529. };
  13530. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  13531. var elts = [], first = true;
  13532. while (!this.eat(close)) {
  13533. if (first) { first = false; }
  13534. else { this.expect(types.comma); }
  13535. if (allowEmpty && this.type === types.comma) {
  13536. elts.push(null);
  13537. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  13538. break
  13539. } else if (this.type === types.ellipsis) {
  13540. var rest = this.parseRestBinding();
  13541. this.parseBindingListItem(rest);
  13542. elts.push(rest);
  13543. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  13544. this.expect(close);
  13545. break
  13546. } else {
  13547. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  13548. this.parseBindingListItem(elem);
  13549. elts.push(elem);
  13550. }
  13551. }
  13552. return elts
  13553. };
  13554. pp$2.parseBindingListItem = function(param) {
  13555. return param
  13556. };
  13557. // Parses assignment pattern around given atom if possible.
  13558. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  13559. left = left || this.parseBindingAtom();
  13560. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  13561. var node = this.startNodeAt(startPos, startLoc);
  13562. node.left = left;
  13563. node.right = this.parseMaybeAssign();
  13564. return this.finishNode(node, "AssignmentPattern")
  13565. };
  13566. // The following three functions all verify that a node is an lvalue —
  13567. // something that can be bound, or assigned to. In order to do so, they perform
  13568. // a variety of checks:
  13569. //
  13570. // - Check that none of the bound/assigned-to identifiers are reserved words.
  13571. // - Record name declarations for bindings in the appropriate scope.
  13572. // - Check duplicate argument names, if checkClashes is set.
  13573. //
  13574. // If a complex binding pattern is encountered (e.g., object and array
  13575. // destructuring), the entire pattern is recursively checked.
  13576. //
  13577. // There are three versions of checkLVal*() appropriate for different
  13578. // circumstances:
  13579. //
  13580. // - checkLValSimple() shall be used if the syntactic construct supports
  13581. // nothing other than identifiers and member expressions. Parenthesized
  13582. // expressions are also correctly handled. This is generally appropriate for
  13583. // constructs for which the spec says
  13584. //
  13585. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  13586. // > simple.
  13587. //
  13588. // It is also appropriate for checking if an identifier is valid and not
  13589. // defined elsewhere, like import declarations or function/class identifiers.
  13590. //
  13591. // Examples where this is used include:
  13592. // a += …;
  13593. // import a from '…';
  13594. // where a is the node to be checked.
  13595. //
  13596. // - checkLValPattern() shall be used if the syntactic construct supports
  13597. // anything checkLValSimple() supports, as well as object and array
  13598. // destructuring patterns. This is generally appropriate for constructs for
  13599. // which the spec says
  13600. //
  13601. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  13602. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  13603. // > simple.
  13604. //
  13605. // Examples where this is used include:
  13606. // (a = …);
  13607. // const a = …;
  13608. // try { … } catch (a) { … }
  13609. // where a is the node to be checked.
  13610. //
  13611. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  13612. // anything checkLValPattern() supports, as well as default assignment
  13613. // patterns, rest elements, and other constructs that may appear within an
  13614. // object or array destructuring pattern.
  13615. //
  13616. // As a special case, function parameters also use checkLValInnerPattern(),
  13617. // as they also support defaults and rest constructs.
  13618. //
  13619. // These functions deliberately support both assignment and binding constructs,
  13620. // as the logic for both is exceedingly similar. If the node is the target of
  13621. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  13622. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  13623. // BIND_LEXICAL.
  13624. //
  13625. // If the function is called with a non-BIND_NONE bindingType, then
  13626. // additionally a checkClashes object may be specified to allow checking for
  13627. // duplicate argument names. checkClashes is ignored if the provided construct
  13628. // is an assignment (i.e., bindingType is BIND_NONE).
  13629. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  13630. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13631. var isBind = bindingType !== BIND_NONE;
  13632. switch (expr.type) {
  13633. case "Identifier":
  13634. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  13635. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  13636. if (isBind) {
  13637. if (bindingType === BIND_LEXICAL && expr.name === "let")
  13638. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  13639. if (checkClashes) {
  13640. if (has(checkClashes, expr.name))
  13641. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  13642. checkClashes[expr.name] = true;
  13643. }
  13644. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  13645. }
  13646. break
  13647. case "ChainExpression":
  13648. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  13649. break
  13650. case "MemberExpression":
  13651. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  13652. break
  13653. case "ParenthesizedExpression":
  13654. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  13655. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  13656. default:
  13657. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  13658. }
  13659. };
  13660. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  13661. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13662. switch (expr.type) {
  13663. case "ObjectPattern":
  13664. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  13665. var prop = list[i];
  13666. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  13667. }
  13668. break
  13669. case "ArrayPattern":
  13670. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  13671. var elem = list$1[i$1];
  13672. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  13673. }
  13674. break
  13675. default:
  13676. this.checkLValSimple(expr, bindingType, checkClashes);
  13677. }
  13678. };
  13679. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  13680. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13681. switch (expr.type) {
  13682. case "Property":
  13683. // AssignmentProperty has type === "Property"
  13684. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  13685. break
  13686. case "AssignmentPattern":
  13687. this.checkLValPattern(expr.left, bindingType, checkClashes);
  13688. break
  13689. case "RestElement":
  13690. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  13691. break
  13692. default:
  13693. this.checkLValPattern(expr, bindingType, checkClashes);
  13694. }
  13695. };
  13696. // A recursive descent parser operates by defining functions for all
  13697. var pp$3 = Parser.prototype;
  13698. // Check if property name clashes with already added.
  13699. // Object/class getters and setters are not allowed to clash —
  13700. // either with each other or with an init property — and in
  13701. // strict mode, init properties are also not allowed to be repeated.
  13702. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  13703. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  13704. { return }
  13705. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  13706. { return }
  13707. var key = prop.key;
  13708. var name;
  13709. switch (key.type) {
  13710. case "Identifier": name = key.name; break
  13711. case "Literal": name = String(key.value); break
  13712. default: return
  13713. }
  13714. var kind = prop.kind;
  13715. if (this.options.ecmaVersion >= 6) {
  13716. if (name === "__proto__" && kind === "init") {
  13717. if (propHash.proto) {
  13718. if (refDestructuringErrors) {
  13719. if (refDestructuringErrors.doubleProto < 0)
  13720. { refDestructuringErrors.doubleProto = key.start; }
  13721. // Backwards-compat kludge. Can be removed in version 6.0
  13722. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  13723. }
  13724. propHash.proto = true;
  13725. }
  13726. return
  13727. }
  13728. name = "$" + name;
  13729. var other = propHash[name];
  13730. if (other) {
  13731. var redefinition;
  13732. if (kind === "init") {
  13733. redefinition = this.strict && other.init || other.get || other.set;
  13734. } else {
  13735. redefinition = other.init || other[kind];
  13736. }
  13737. if (redefinition)
  13738. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  13739. } else {
  13740. other = propHash[name] = {
  13741. init: false,
  13742. get: false,
  13743. set: false
  13744. };
  13745. }
  13746. other[kind] = true;
  13747. };
  13748. // ### Expression parsing
  13749. // These nest, from the most general expression type at the top to
  13750. // 'atomic', nondivisible expression types at the bottom. Most of
  13751. // the functions will simply let the function(s) below them parse,
  13752. // and, *if* the syntactic construct they handle is present, wrap
  13753. // the AST node that the inner parser gave them in another node.
  13754. // Parse a full expression. The optional arguments are used to
  13755. // forbid the `in` operator (in for loops initalization expressions)
  13756. // and provide reference for storing '=' operator inside shorthand
  13757. // property assignment in contexts where both object expression
  13758. // and object pattern might appear (so it's possible to raise
  13759. // delayed syntax error at correct position).
  13760. pp$3.parseExpression = function(noIn, refDestructuringErrors) {
  13761. var startPos = this.start, startLoc = this.startLoc;
  13762. var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
  13763. if (this.type === types.comma) {
  13764. var node = this.startNodeAt(startPos, startLoc);
  13765. node.expressions = [expr];
  13766. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
  13767. return this.finishNode(node, "SequenceExpression")
  13768. }
  13769. return expr
  13770. };
  13771. // Parse an assignment expression. This includes applications of
  13772. // operators like `+=`.
  13773. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  13774. if (this.isContextual("yield")) {
  13775. if (this.inGenerator) { return this.parseYield(noIn) }
  13776. // The tokenizer will assume an expression is allowed after
  13777. // `yield`, but this isn't that kind of yield
  13778. else { this.exprAllowed = false; }
  13779. }
  13780. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  13781. if (refDestructuringErrors) {
  13782. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  13783. oldTrailingComma = refDestructuringErrors.trailingComma;
  13784. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  13785. } else {
  13786. refDestructuringErrors = new DestructuringErrors;
  13787. ownDestructuringErrors = true;
  13788. }
  13789. var startPos = this.start, startLoc = this.startLoc;
  13790. if (this.type === types.parenL || this.type === types.name)
  13791. { this.potentialArrowAt = this.start; }
  13792. var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
  13793. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  13794. if (this.type.isAssign) {
  13795. var node = this.startNodeAt(startPos, startLoc);
  13796. node.operator = this.value;
  13797. if (this.type === types.eq)
  13798. { left = this.toAssignable(left, false, refDestructuringErrors); }
  13799. if (!ownDestructuringErrors) {
  13800. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  13801. }
  13802. if (refDestructuringErrors.shorthandAssign >= left.start)
  13803. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  13804. if (this.type === types.eq)
  13805. { this.checkLValPattern(left); }
  13806. else
  13807. { this.checkLValSimple(left); }
  13808. node.left = left;
  13809. this.next();
  13810. node.right = this.parseMaybeAssign(noIn);
  13811. return this.finishNode(node, "AssignmentExpression")
  13812. } else {
  13813. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  13814. }
  13815. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  13816. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  13817. return left
  13818. };
  13819. // Parse a ternary conditional (`?:`) operator.
  13820. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  13821. var startPos = this.start, startLoc = this.startLoc;
  13822. var expr = this.parseExprOps(noIn, refDestructuringErrors);
  13823. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  13824. if (this.eat(types.question)) {
  13825. var node = this.startNodeAt(startPos, startLoc);
  13826. node.test = expr;
  13827. node.consequent = this.parseMaybeAssign();
  13828. this.expect(types.colon);
  13829. node.alternate = this.parseMaybeAssign(noIn);
  13830. return this.finishNode(node, "ConditionalExpression")
  13831. }
  13832. return expr
  13833. };
  13834. // Start the precedence parser.
  13835. pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
  13836. var startPos = this.start, startLoc = this.startLoc;
  13837. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  13838. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  13839. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
  13840. };
  13841. // Parse binary operators with the operator precedence parsing
  13842. // algorithm. `left` is the left-hand side of the operator.
  13843. // `minPrec` provides context that allows the function to stop and
  13844. // defer further parser to one of its callers when it encounters an
  13845. // operator that has a lower precedence than the set it is parsing.
  13846. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  13847. var prec = this.type.binop;
  13848. if (prec != null && (!noIn || this.type !== types._in)) {
  13849. if (prec > minPrec) {
  13850. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  13851. var coalesce = this.type === types.coalesce;
  13852. if (coalesce) {
  13853. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  13854. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  13855. prec = types.logicalAND.binop;
  13856. }
  13857. var op = this.value;
  13858. this.next();
  13859. var startPos = this.start, startLoc = this.startLoc;
  13860. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
  13861. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  13862. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  13863. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  13864. }
  13865. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
  13866. }
  13867. }
  13868. return left
  13869. };
  13870. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  13871. var node = this.startNodeAt(startPos, startLoc);
  13872. node.left = left;
  13873. node.operator = op;
  13874. node.right = right;
  13875. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  13876. };
  13877. // Parse unary operators, both prefix and postfix.
  13878. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  13879. var startPos = this.start, startLoc = this.startLoc, expr;
  13880. if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
  13881. expr = this.parseAwait();
  13882. sawUnary = true;
  13883. } else if (this.type.prefix) {
  13884. var node = this.startNode(), update = this.type === types.incDec;
  13885. node.operator = this.value;
  13886. node.prefix = true;
  13887. this.next();
  13888. node.argument = this.parseMaybeUnary(null, true);
  13889. this.checkExpressionErrors(refDestructuringErrors, true);
  13890. if (update) { this.checkLValSimple(node.argument); }
  13891. else if (this.strict && node.operator === "delete" &&
  13892. node.argument.type === "Identifier")
  13893. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  13894. else { sawUnary = true; }
  13895. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  13896. } else {
  13897. expr = this.parseExprSubscripts(refDestructuringErrors);
  13898. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  13899. while (this.type.postfix && !this.canInsertSemicolon()) {
  13900. var node$1 = this.startNodeAt(startPos, startLoc);
  13901. node$1.operator = this.value;
  13902. node$1.prefix = false;
  13903. node$1.argument = expr;
  13904. this.checkLValSimple(expr);
  13905. this.next();
  13906. expr = this.finishNode(node$1, "UpdateExpression");
  13907. }
  13908. }
  13909. if (!sawUnary && this.eat(types.starstar))
  13910. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  13911. else
  13912. { return expr }
  13913. };
  13914. // Parse call, dot, and `[]`-subscript expressions.
  13915. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  13916. var startPos = this.start, startLoc = this.startLoc;
  13917. var expr = this.parseExprAtom(refDestructuringErrors);
  13918. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  13919. { return expr }
  13920. var result = this.parseSubscripts(expr, startPos, startLoc);
  13921. if (refDestructuringErrors && result.type === "MemberExpression") {
  13922. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  13923. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  13924. }
  13925. return result
  13926. };
  13927. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  13928. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  13929. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  13930. this.potentialArrowAt === base.start;
  13931. var optionalChained = false;
  13932. while (true) {
  13933. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  13934. if (element.optional) { optionalChained = true; }
  13935. if (element === base || element.type === "ArrowFunctionExpression") {
  13936. if (optionalChained) {
  13937. var chainNode = this.startNodeAt(startPos, startLoc);
  13938. chainNode.expression = element;
  13939. element = this.finishNode(chainNode, "ChainExpression");
  13940. }
  13941. return element
  13942. }
  13943. base = element;
  13944. }
  13945. };
  13946. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  13947. var optionalSupported = this.options.ecmaVersion >= 11;
  13948. var optional = optionalSupported && this.eat(types.questionDot);
  13949. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  13950. var computed = this.eat(types.bracketL);
  13951. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  13952. var node = this.startNodeAt(startPos, startLoc);
  13953. node.object = base;
  13954. node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
  13955. node.computed = !!computed;
  13956. if (computed) { this.expect(types.bracketR); }
  13957. if (optionalSupported) {
  13958. node.optional = optional;
  13959. }
  13960. base = this.finishNode(node, "MemberExpression");
  13961. } else if (!noCalls && this.eat(types.parenL)) {
  13962. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  13963. this.yieldPos = 0;
  13964. this.awaitPos = 0;
  13965. this.awaitIdentPos = 0;
  13966. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  13967. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  13968. this.checkPatternErrors(refDestructuringErrors, false);
  13969. this.checkYieldAwaitInDefaultParams();
  13970. if (this.awaitIdentPos > 0)
  13971. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  13972. this.yieldPos = oldYieldPos;
  13973. this.awaitPos = oldAwaitPos;
  13974. this.awaitIdentPos = oldAwaitIdentPos;
  13975. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  13976. }
  13977. this.checkExpressionErrors(refDestructuringErrors, true);
  13978. this.yieldPos = oldYieldPos || this.yieldPos;
  13979. this.awaitPos = oldAwaitPos || this.awaitPos;
  13980. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  13981. var node$1 = this.startNodeAt(startPos, startLoc);
  13982. node$1.callee = base;
  13983. node$1.arguments = exprList;
  13984. if (optionalSupported) {
  13985. node$1.optional = optional;
  13986. }
  13987. base = this.finishNode(node$1, "CallExpression");
  13988. } else if (this.type === types.backQuote) {
  13989. if (optional || optionalChained) {
  13990. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  13991. }
  13992. var node$2 = this.startNodeAt(startPos, startLoc);
  13993. node$2.tag = base;
  13994. node$2.quasi = this.parseTemplate({isTagged: true});
  13995. base = this.finishNode(node$2, "TaggedTemplateExpression");
  13996. }
  13997. return base
  13998. };
  13999. // Parse an atomic expression — either a single token that is an
  14000. // expression, an expression started by a keyword like `function` or
  14001. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  14002. // or `{}`.
  14003. pp$3.parseExprAtom = function(refDestructuringErrors) {
  14004. // If a division operator appears in an expression position, the
  14005. // tokenizer got confused, and we force it to read a regexp instead.
  14006. if (this.type === types.slash) { this.readRegexp(); }
  14007. var node, canBeArrow = this.potentialArrowAt === this.start;
  14008. switch (this.type) {
  14009. case types._super:
  14010. if (!this.allowSuper)
  14011. { this.raise(this.start, "'super' keyword outside a method"); }
  14012. node = this.startNode();
  14013. this.next();
  14014. if (this.type === types.parenL && !this.allowDirectSuper)
  14015. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  14016. // The `super` keyword can appear at below:
  14017. // SuperProperty:
  14018. // super [ Expression ]
  14019. // super . IdentifierName
  14020. // SuperCall:
  14021. // super ( Arguments )
  14022. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  14023. { this.unexpected(); }
  14024. return this.finishNode(node, "Super")
  14025. case types._this:
  14026. node = this.startNode();
  14027. this.next();
  14028. return this.finishNode(node, "ThisExpression")
  14029. case types.name:
  14030. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  14031. var id = this.parseIdent(false);
  14032. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  14033. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  14034. if (canBeArrow && !this.canInsertSemicolon()) {
  14035. if (this.eat(types.arrow))
  14036. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  14037. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
  14038. id = this.parseIdent(false);
  14039. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  14040. { this.unexpected(); }
  14041. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  14042. }
  14043. }
  14044. return id
  14045. case types.regexp:
  14046. var value = this.value;
  14047. node = this.parseLiteral(value.value);
  14048. node.regex = {pattern: value.pattern, flags: value.flags};
  14049. return node
  14050. case types.num: case types.string:
  14051. return this.parseLiteral(this.value)
  14052. case types._null: case types._true: case types._false:
  14053. node = this.startNode();
  14054. node.value = this.type === types._null ? null : this.type === types._true;
  14055. node.raw = this.type.keyword;
  14056. this.next();
  14057. return this.finishNode(node, "Literal")
  14058. case types.parenL:
  14059. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  14060. if (refDestructuringErrors) {
  14061. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  14062. { refDestructuringErrors.parenthesizedAssign = start; }
  14063. if (refDestructuringErrors.parenthesizedBind < 0)
  14064. { refDestructuringErrors.parenthesizedBind = start; }
  14065. }
  14066. return expr
  14067. case types.bracketL:
  14068. node = this.startNode();
  14069. this.next();
  14070. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  14071. return this.finishNode(node, "ArrayExpression")
  14072. case types.braceL:
  14073. return this.parseObj(false, refDestructuringErrors)
  14074. case types._function:
  14075. node = this.startNode();
  14076. this.next();
  14077. return this.parseFunction(node, 0)
  14078. case types._class:
  14079. return this.parseClass(this.startNode(), false)
  14080. case types._new:
  14081. return this.parseNew()
  14082. case types.backQuote:
  14083. return this.parseTemplate()
  14084. case types._import:
  14085. if (this.options.ecmaVersion >= 11) {
  14086. return this.parseExprImport()
  14087. } else {
  14088. return this.unexpected()
  14089. }
  14090. default:
  14091. this.unexpected();
  14092. }
  14093. };
  14094. pp$3.parseExprImport = function() {
  14095. var node = this.startNode();
  14096. // Consume `import` as an identifier for `import.meta`.
  14097. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  14098. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  14099. var meta = this.parseIdent(true);
  14100. switch (this.type) {
  14101. case types.parenL:
  14102. return this.parseDynamicImport(node)
  14103. case types.dot:
  14104. node.meta = meta;
  14105. return this.parseImportMeta(node)
  14106. default:
  14107. this.unexpected();
  14108. }
  14109. };
  14110. pp$3.parseDynamicImport = function(node) {
  14111. this.next(); // skip `(`
  14112. // Parse node.source.
  14113. node.source = this.parseMaybeAssign();
  14114. // Verify ending.
  14115. if (!this.eat(types.parenR)) {
  14116. var errorPos = this.start;
  14117. if (this.eat(types.comma) && this.eat(types.parenR)) {
  14118. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  14119. } else {
  14120. this.unexpected(errorPos);
  14121. }
  14122. }
  14123. return this.finishNode(node, "ImportExpression")
  14124. };
  14125. pp$3.parseImportMeta = function(node) {
  14126. this.next(); // skip `.`
  14127. var containsEsc = this.containsEsc;
  14128. node.property = this.parseIdent(true);
  14129. if (node.property.name !== "meta")
  14130. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  14131. if (containsEsc)
  14132. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  14133. if (this.options.sourceType !== "module")
  14134. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  14135. return this.finishNode(node, "MetaProperty")
  14136. };
  14137. pp$3.parseLiteral = function(value) {
  14138. var node = this.startNode();
  14139. node.value = value;
  14140. node.raw = this.input.slice(this.start, this.end);
  14141. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  14142. this.next();
  14143. return this.finishNode(node, "Literal")
  14144. };
  14145. pp$3.parseParenExpression = function() {
  14146. this.expect(types.parenL);
  14147. var val = this.parseExpression();
  14148. this.expect(types.parenR);
  14149. return val
  14150. };
  14151. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  14152. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  14153. if (this.options.ecmaVersion >= 6) {
  14154. this.next();
  14155. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  14156. var exprList = [], first = true, lastIsComma = false;
  14157. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  14158. this.yieldPos = 0;
  14159. this.awaitPos = 0;
  14160. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  14161. while (this.type !== types.parenR) {
  14162. first ? first = false : this.expect(types.comma);
  14163. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  14164. lastIsComma = true;
  14165. break
  14166. } else if (this.type === types.ellipsis) {
  14167. spreadStart = this.start;
  14168. exprList.push(this.parseParenItem(this.parseRestBinding()));
  14169. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  14170. break
  14171. } else {
  14172. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  14173. }
  14174. }
  14175. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  14176. this.expect(types.parenR);
  14177. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  14178. this.checkPatternErrors(refDestructuringErrors, false);
  14179. this.checkYieldAwaitInDefaultParams();
  14180. this.yieldPos = oldYieldPos;
  14181. this.awaitPos = oldAwaitPos;
  14182. return this.parseParenArrowList(startPos, startLoc, exprList)
  14183. }
  14184. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  14185. if (spreadStart) { this.unexpected(spreadStart); }
  14186. this.checkExpressionErrors(refDestructuringErrors, true);
  14187. this.yieldPos = oldYieldPos || this.yieldPos;
  14188. this.awaitPos = oldAwaitPos || this.awaitPos;
  14189. if (exprList.length > 1) {
  14190. val = this.startNodeAt(innerStartPos, innerStartLoc);
  14191. val.expressions = exprList;
  14192. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  14193. } else {
  14194. val = exprList[0];
  14195. }
  14196. } else {
  14197. val = this.parseParenExpression();
  14198. }
  14199. if (this.options.preserveParens) {
  14200. var par = this.startNodeAt(startPos, startLoc);
  14201. par.expression = val;
  14202. return this.finishNode(par, "ParenthesizedExpression")
  14203. } else {
  14204. return val
  14205. }
  14206. };
  14207. pp$3.parseParenItem = function(item) {
  14208. return item
  14209. };
  14210. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  14211. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  14212. };
  14213. // New's precedence is slightly tricky. It must allow its argument to
  14214. // be a `[]` or dot subscript expression, but not a call — at least,
  14215. // not without wrapping it in parentheses. Thus, it uses the noCalls
  14216. // argument to parseSubscripts to prevent it from consuming the
  14217. // argument list.
  14218. var empty$1 = [];
  14219. pp$3.parseNew = function() {
  14220. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  14221. var node = this.startNode();
  14222. var meta = this.parseIdent(true);
  14223. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  14224. node.meta = meta;
  14225. var containsEsc = this.containsEsc;
  14226. node.property = this.parseIdent(true);
  14227. if (node.property.name !== "target")
  14228. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  14229. if (containsEsc)
  14230. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  14231. if (!this.inNonArrowFunction)
  14232. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  14233. return this.finishNode(node, "MetaProperty")
  14234. }
  14235. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  14236. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  14237. if (isImport && node.callee.type === "ImportExpression") {
  14238. this.raise(startPos, "Cannot use new with import()");
  14239. }
  14240. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  14241. else { node.arguments = empty$1; }
  14242. return this.finishNode(node, "NewExpression")
  14243. };
  14244. // Parse template expression.
  14245. pp$3.parseTemplateElement = function(ref) {
  14246. var isTagged = ref.isTagged;
  14247. var elem = this.startNode();
  14248. if (this.type === types.invalidTemplate) {
  14249. if (!isTagged) {
  14250. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  14251. }
  14252. elem.value = {
  14253. raw: this.value,
  14254. cooked: null
  14255. };
  14256. } else {
  14257. elem.value = {
  14258. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  14259. cooked: this.value
  14260. };
  14261. }
  14262. this.next();
  14263. elem.tail = this.type === types.backQuote;
  14264. return this.finishNode(elem, "TemplateElement")
  14265. };
  14266. pp$3.parseTemplate = function(ref) {
  14267. if ( ref === void 0 ) ref = {};
  14268. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  14269. var node = this.startNode();
  14270. this.next();
  14271. node.expressions = [];
  14272. var curElt = this.parseTemplateElement({isTagged: isTagged});
  14273. node.quasis = [curElt];
  14274. while (!curElt.tail) {
  14275. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  14276. this.expect(types.dollarBraceL);
  14277. node.expressions.push(this.parseExpression());
  14278. this.expect(types.braceR);
  14279. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  14280. }
  14281. this.next();
  14282. return this.finishNode(node, "TemplateLiteral")
  14283. };
  14284. pp$3.isAsyncProp = function(prop) {
  14285. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  14286. (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)) &&
  14287. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  14288. };
  14289. // Parse an object literal or binding pattern.
  14290. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  14291. var node = this.startNode(), first = true, propHash = {};
  14292. node.properties = [];
  14293. this.next();
  14294. while (!this.eat(types.braceR)) {
  14295. if (!first) {
  14296. this.expect(types.comma);
  14297. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  14298. } else { first = false; }
  14299. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  14300. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  14301. node.properties.push(prop);
  14302. }
  14303. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  14304. };
  14305. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  14306. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  14307. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  14308. if (isPattern) {
  14309. prop.argument = this.parseIdent(false);
  14310. if (this.type === types.comma) {
  14311. this.raise(this.start, "Comma is not permitted after the rest element");
  14312. }
  14313. return this.finishNode(prop, "RestElement")
  14314. }
  14315. // To disallow parenthesized identifier via `this.toAssignable()`.
  14316. if (this.type === types.parenL && refDestructuringErrors) {
  14317. if (refDestructuringErrors.parenthesizedAssign < 0) {
  14318. refDestructuringErrors.parenthesizedAssign = this.start;
  14319. }
  14320. if (refDestructuringErrors.parenthesizedBind < 0) {
  14321. refDestructuringErrors.parenthesizedBind = this.start;
  14322. }
  14323. }
  14324. // Parse argument.
  14325. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  14326. // To disallow trailing comma via `this.toAssignable()`.
  14327. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  14328. refDestructuringErrors.trailingComma = this.start;
  14329. }
  14330. // Finish
  14331. return this.finishNode(prop, "SpreadElement")
  14332. }
  14333. if (this.options.ecmaVersion >= 6) {
  14334. prop.method = false;
  14335. prop.shorthand = false;
  14336. if (isPattern || refDestructuringErrors) {
  14337. startPos = this.start;
  14338. startLoc = this.startLoc;
  14339. }
  14340. if (!isPattern)
  14341. { isGenerator = this.eat(types.star); }
  14342. }
  14343. var containsEsc = this.containsEsc;
  14344. this.parsePropertyName(prop);
  14345. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  14346. isAsync = true;
  14347. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  14348. this.parsePropertyName(prop, refDestructuringErrors);
  14349. } else {
  14350. isAsync = false;
  14351. }
  14352. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  14353. return this.finishNode(prop, "Property")
  14354. };
  14355. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  14356. if ((isGenerator || isAsync) && this.type === types.colon)
  14357. { this.unexpected(); }
  14358. if (this.eat(types.colon)) {
  14359. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  14360. prop.kind = "init";
  14361. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  14362. if (isPattern) { this.unexpected(); }
  14363. prop.kind = "init";
  14364. prop.method = true;
  14365. prop.value = this.parseMethod(isGenerator, isAsync);
  14366. } else if (!isPattern && !containsEsc &&
  14367. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  14368. (prop.key.name === "get" || prop.key.name === "set") &&
  14369. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  14370. if (isGenerator || isAsync) { this.unexpected(); }
  14371. prop.kind = prop.key.name;
  14372. this.parsePropertyName(prop);
  14373. prop.value = this.parseMethod(false);
  14374. var paramCount = prop.kind === "get" ? 0 : 1;
  14375. if (prop.value.params.length !== paramCount) {
  14376. var start = prop.value.start;
  14377. if (prop.kind === "get")
  14378. { this.raiseRecoverable(start, "getter should have no params"); }
  14379. else
  14380. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  14381. } else {
  14382. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  14383. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  14384. }
  14385. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  14386. if (isGenerator || isAsync) { this.unexpected(); }
  14387. this.checkUnreserved(prop.key);
  14388. if (prop.key.name === "await" && !this.awaitIdentPos)
  14389. { this.awaitIdentPos = startPos; }
  14390. prop.kind = "init";
  14391. if (isPattern) {
  14392. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  14393. } else if (this.type === types.eq && refDestructuringErrors) {
  14394. if (refDestructuringErrors.shorthandAssign < 0)
  14395. { refDestructuringErrors.shorthandAssign = this.start; }
  14396. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  14397. } else {
  14398. prop.value = this.copyNode(prop.key);
  14399. }
  14400. prop.shorthand = true;
  14401. } else { this.unexpected(); }
  14402. };
  14403. pp$3.parsePropertyName = function(prop) {
  14404. if (this.options.ecmaVersion >= 6) {
  14405. if (this.eat(types.bracketL)) {
  14406. prop.computed = true;
  14407. prop.key = this.parseMaybeAssign();
  14408. this.expect(types.bracketR);
  14409. return prop.key
  14410. } else {
  14411. prop.computed = false;
  14412. }
  14413. }
  14414. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  14415. };
  14416. // Initialize empty function node.
  14417. pp$3.initFunction = function(node) {
  14418. node.id = null;
  14419. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  14420. if (this.options.ecmaVersion >= 8) { node.async = false; }
  14421. };
  14422. // Parse object or class method.
  14423. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  14424. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14425. this.initFunction(node);
  14426. if (this.options.ecmaVersion >= 6)
  14427. { node.generator = isGenerator; }
  14428. if (this.options.ecmaVersion >= 8)
  14429. { node.async = !!isAsync; }
  14430. this.yieldPos = 0;
  14431. this.awaitPos = 0;
  14432. this.awaitIdentPos = 0;
  14433. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  14434. this.expect(types.parenL);
  14435. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  14436. this.checkYieldAwaitInDefaultParams();
  14437. this.parseFunctionBody(node, false, true);
  14438. this.yieldPos = oldYieldPos;
  14439. this.awaitPos = oldAwaitPos;
  14440. this.awaitIdentPos = oldAwaitIdentPos;
  14441. return this.finishNode(node, "FunctionExpression")
  14442. };
  14443. // Parse arrow function expression with given parameters.
  14444. pp$3.parseArrowExpression = function(node, params, isAsync) {
  14445. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14446. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  14447. this.initFunction(node);
  14448. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  14449. this.yieldPos = 0;
  14450. this.awaitPos = 0;
  14451. this.awaitIdentPos = 0;
  14452. node.params = this.toAssignableList(params, true);
  14453. this.parseFunctionBody(node, true, false);
  14454. this.yieldPos = oldYieldPos;
  14455. this.awaitPos = oldAwaitPos;
  14456. this.awaitIdentPos = oldAwaitIdentPos;
  14457. return this.finishNode(node, "ArrowFunctionExpression")
  14458. };
  14459. // Parse function body and check parameters.
  14460. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  14461. var isExpression = isArrowFunction && this.type !== types.braceL;
  14462. var oldStrict = this.strict, useStrict = false;
  14463. if (isExpression) {
  14464. node.body = this.parseMaybeAssign();
  14465. node.expression = true;
  14466. this.checkParams(node, false);
  14467. } else {
  14468. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  14469. if (!oldStrict || nonSimple) {
  14470. useStrict = this.strictDirective(this.end);
  14471. // If this is a strict mode function, verify that argument names
  14472. // are not repeated, and it does not try to bind the words `eval`
  14473. // or `arguments`.
  14474. if (useStrict && nonSimple)
  14475. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  14476. }
  14477. // Start a new scope with regard to labels and the `inFunction`
  14478. // flag (restore them to their old value afterwards).
  14479. var oldLabels = this.labels;
  14480. this.labels = [];
  14481. if (useStrict) { this.strict = true; }
  14482. // Add the params to varDeclaredNames to ensure that an error is thrown
  14483. // if a let/const declaration in the function clashes with one of the params.
  14484. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  14485. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  14486. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  14487. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  14488. node.expression = false;
  14489. this.adaptDirectivePrologue(node.body.body);
  14490. this.labels = oldLabels;
  14491. }
  14492. this.exitScope();
  14493. };
  14494. pp$3.isSimpleParamList = function(params) {
  14495. for (var i = 0, list = params; i < list.length; i += 1)
  14496. {
  14497. var param = list[i];
  14498. if (param.type !== "Identifier") { return false
  14499. } }
  14500. return true
  14501. };
  14502. // Checks function params for various disallowed patterns such as using "eval"
  14503. // or "arguments" and duplicate parameters.
  14504. pp$3.checkParams = function(node, allowDuplicates) {
  14505. var nameHash = {};
  14506. for (var i = 0, list = node.params; i < list.length; i += 1)
  14507. {
  14508. var param = list[i];
  14509. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  14510. }
  14511. };
  14512. // Parses a comma-separated list of expressions, and returns them as
  14513. // an array. `close` is the token type that ends the list, and
  14514. // `allowEmpty` can be turned on to allow subsequent commas with
  14515. // nothing in between them to be parsed as `null` (which is needed
  14516. // for array literals).
  14517. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  14518. var elts = [], first = true;
  14519. while (!this.eat(close)) {
  14520. if (!first) {
  14521. this.expect(types.comma);
  14522. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  14523. } else { first = false; }
  14524. var elt = (void 0);
  14525. if (allowEmpty && this.type === types.comma)
  14526. { elt = null; }
  14527. else if (this.type === types.ellipsis) {
  14528. elt = this.parseSpread(refDestructuringErrors);
  14529. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  14530. { refDestructuringErrors.trailingComma = this.start; }
  14531. } else {
  14532. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  14533. }
  14534. elts.push(elt);
  14535. }
  14536. return elts
  14537. };
  14538. pp$3.checkUnreserved = function(ref) {
  14539. var start = ref.start;
  14540. var end = ref.end;
  14541. var name = ref.name;
  14542. if (this.inGenerator && name === "yield")
  14543. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  14544. if (this.inAsync && name === "await")
  14545. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  14546. if (this.keywords.test(name))
  14547. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  14548. if (this.options.ecmaVersion < 6 &&
  14549. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  14550. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  14551. if (re.test(name)) {
  14552. if (!this.inAsync && name === "await")
  14553. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  14554. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  14555. }
  14556. };
  14557. // Parse the next token as an identifier. If `liberal` is true (used
  14558. // when parsing properties), it will also convert keywords into
  14559. // identifiers.
  14560. pp$3.parseIdent = function(liberal, isBinding) {
  14561. var node = this.startNode();
  14562. if (this.type === types.name) {
  14563. node.name = this.value;
  14564. } else if (this.type.keyword) {
  14565. node.name = this.type.keyword;
  14566. // To fix https://github.com/acornjs/acorn/issues/575
  14567. // `class` and `function` keywords push new context into this.context.
  14568. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  14569. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  14570. if ((node.name === "class" || node.name === "function") &&
  14571. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  14572. this.context.pop();
  14573. }
  14574. } else {
  14575. this.unexpected();
  14576. }
  14577. this.next(!!liberal);
  14578. this.finishNode(node, "Identifier");
  14579. if (!liberal) {
  14580. this.checkUnreserved(node);
  14581. if (node.name === "await" && !this.awaitIdentPos)
  14582. { this.awaitIdentPos = node.start; }
  14583. }
  14584. return node
  14585. };
  14586. // Parses yield expression inside generator.
  14587. pp$3.parseYield = function(noIn) {
  14588. if (!this.yieldPos) { this.yieldPos = this.start; }
  14589. var node = this.startNode();
  14590. this.next();
  14591. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  14592. node.delegate = false;
  14593. node.argument = null;
  14594. } else {
  14595. node.delegate = this.eat(types.star);
  14596. node.argument = this.parseMaybeAssign(noIn);
  14597. }
  14598. return this.finishNode(node, "YieldExpression")
  14599. };
  14600. pp$3.parseAwait = function() {
  14601. if (!this.awaitPos) { this.awaitPos = this.start; }
  14602. var node = this.startNode();
  14603. this.next();
  14604. node.argument = this.parseMaybeUnary(null, false);
  14605. return this.finishNode(node, "AwaitExpression")
  14606. };
  14607. var pp$4 = Parser.prototype;
  14608. // This function is used to raise exceptions on parse errors. It
  14609. // takes an offset integer (into the current `input`) to indicate
  14610. // the location of the error, attaches the position to the end
  14611. // of the error message, and then raises a `SyntaxError` with that
  14612. // message.
  14613. pp$4.raise = function(pos, message) {
  14614. var loc = getLineInfo(this.input, pos);
  14615. message += " (" + loc.line + ":" + loc.column + ")";
  14616. var err = new SyntaxError(message);
  14617. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  14618. throw err
  14619. };
  14620. pp$4.raiseRecoverable = pp$4.raise;
  14621. pp$4.curPosition = function() {
  14622. if (this.options.locations) {
  14623. return new Position(this.curLine, this.pos - this.lineStart)
  14624. }
  14625. };
  14626. var pp$5 = Parser.prototype;
  14627. var Scope$1 = function Scope(flags) {
  14628. this.flags = flags;
  14629. // A list of var-declared names in the current lexical scope
  14630. this.var = [];
  14631. // A list of lexically-declared names in the current lexical scope
  14632. this.lexical = [];
  14633. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  14634. this.functions = [];
  14635. };
  14636. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  14637. pp$5.enterScope = function(flags) {
  14638. this.scopeStack.push(new Scope$1(flags));
  14639. };
  14640. pp$5.exitScope = function() {
  14641. this.scopeStack.pop();
  14642. };
  14643. // The spec says:
  14644. // > At the top level of a function, or script, function declarations are
  14645. // > treated like var declarations rather than like lexical declarations.
  14646. pp$5.treatFunctionsAsVarInScope = function(scope) {
  14647. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  14648. };
  14649. pp$5.declareName = function(name, bindingType, pos) {
  14650. var redeclared = false;
  14651. if (bindingType === BIND_LEXICAL) {
  14652. var scope = this.currentScope();
  14653. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  14654. scope.lexical.push(name);
  14655. if (this.inModule && (scope.flags & SCOPE_TOP))
  14656. { delete this.undefinedExports[name]; }
  14657. } else if (bindingType === BIND_SIMPLE_CATCH) {
  14658. var scope$1 = this.currentScope();
  14659. scope$1.lexical.push(name);
  14660. } else if (bindingType === BIND_FUNCTION) {
  14661. var scope$2 = this.currentScope();
  14662. if (this.treatFunctionsAsVar)
  14663. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  14664. else
  14665. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  14666. scope$2.functions.push(name);
  14667. } else {
  14668. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  14669. var scope$3 = this.scopeStack[i];
  14670. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  14671. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  14672. redeclared = true;
  14673. break
  14674. }
  14675. scope$3.var.push(name);
  14676. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  14677. { delete this.undefinedExports[name]; }
  14678. if (scope$3.flags & SCOPE_VAR) { break }
  14679. }
  14680. }
  14681. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  14682. };
  14683. pp$5.checkLocalExport = function(id) {
  14684. // scope.functions must be empty as Module code is always strict.
  14685. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  14686. this.scopeStack[0].var.indexOf(id.name) === -1) {
  14687. this.undefinedExports[id.name] = id;
  14688. }
  14689. };
  14690. pp$5.currentScope = function() {
  14691. return this.scopeStack[this.scopeStack.length - 1]
  14692. };
  14693. pp$5.currentVarScope = function() {
  14694. for (var i = this.scopeStack.length - 1;; i--) {
  14695. var scope = this.scopeStack[i];
  14696. if (scope.flags & SCOPE_VAR) { return scope }
  14697. }
  14698. };
  14699. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  14700. pp$5.currentThisScope = function() {
  14701. for (var i = this.scopeStack.length - 1;; i--) {
  14702. var scope = this.scopeStack[i];
  14703. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  14704. }
  14705. };
  14706. var Node = function Node(parser, pos, loc) {
  14707. this.type = "";
  14708. this.start = pos;
  14709. this.end = 0;
  14710. if (parser.options.locations)
  14711. { this.loc = new SourceLocation(parser, loc); }
  14712. if (parser.options.directSourceFile)
  14713. { this.sourceFile = parser.options.directSourceFile; }
  14714. if (parser.options.ranges)
  14715. { this.range = [pos, 0]; }
  14716. };
  14717. // Start an AST node, attaching a start offset.
  14718. var pp$6 = Parser.prototype;
  14719. pp$6.startNode = function() {
  14720. return new Node(this, this.start, this.startLoc)
  14721. };
  14722. pp$6.startNodeAt = function(pos, loc) {
  14723. return new Node(this, pos, loc)
  14724. };
  14725. // Finish an AST node, adding `type` and `end` properties.
  14726. function finishNodeAt(node, type, pos, loc) {
  14727. node.type = type;
  14728. node.end = pos;
  14729. if (this.options.locations)
  14730. { node.loc.end = loc; }
  14731. if (this.options.ranges)
  14732. { node.range[1] = pos; }
  14733. return node
  14734. }
  14735. pp$6.finishNode = function(node, type) {
  14736. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  14737. };
  14738. // Finish node at given position
  14739. pp$6.finishNodeAt = function(node, type, pos, loc) {
  14740. return finishNodeAt.call(this, node, type, pos, loc)
  14741. };
  14742. pp$6.copyNode = function(node) {
  14743. var newNode = new Node(this, node.start, this.startLoc);
  14744. for (var prop in node) { newNode[prop] = node[prop]; }
  14745. return newNode
  14746. };
  14747. // The algorithm used to determine whether a regexp can appear at a
  14748. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  14749. this.token = token;
  14750. this.isExpr = !!isExpr;
  14751. this.preserveSpace = !!preserveSpace;
  14752. this.override = override;
  14753. this.generator = !!generator;
  14754. };
  14755. var types$1 = {
  14756. b_stat: new TokContext("{", false),
  14757. b_expr: new TokContext("{", true),
  14758. b_tmpl: new TokContext("${", false),
  14759. p_stat: new TokContext("(", false),
  14760. p_expr: new TokContext("(", true),
  14761. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  14762. f_stat: new TokContext("function", false),
  14763. f_expr: new TokContext("function", true),
  14764. f_expr_gen: new TokContext("function", true, false, null, true),
  14765. f_gen: new TokContext("function", false, false, null, true)
  14766. };
  14767. var pp$7 = Parser.prototype;
  14768. pp$7.initialContext = function() {
  14769. return [types$1.b_stat]
  14770. };
  14771. pp$7.braceIsBlock = function(prevType) {
  14772. var parent = this.curContext();
  14773. if (parent === types$1.f_expr || parent === types$1.f_stat)
  14774. { return true }
  14775. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  14776. { return !parent.isExpr }
  14777. // The check for `tt.name && exprAllowed` detects whether we are
  14778. // after a `yield` or `of` construct. See the `updateContext` for
  14779. // `tt.name`.
  14780. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  14781. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  14782. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  14783. { return true }
  14784. if (prevType === types.braceL)
  14785. { return parent === types$1.b_stat }
  14786. if (prevType === types._var || prevType === types._const || prevType === types.name)
  14787. { return false }
  14788. return !this.exprAllowed
  14789. };
  14790. pp$7.inGeneratorContext = function() {
  14791. for (var i = this.context.length - 1; i >= 1; i--) {
  14792. var context = this.context[i];
  14793. if (context.token === "function")
  14794. { return context.generator }
  14795. }
  14796. return false
  14797. };
  14798. pp$7.updateContext = function(prevType) {
  14799. var update, type = this.type;
  14800. if (type.keyword && prevType === types.dot)
  14801. { this.exprAllowed = false; }
  14802. else if (update = type.updateContext)
  14803. { update.call(this, prevType); }
  14804. else
  14805. { this.exprAllowed = type.beforeExpr; }
  14806. };
  14807. // Token-specific context update code
  14808. types.parenR.updateContext = types.braceR.updateContext = function() {
  14809. if (this.context.length === 1) {
  14810. this.exprAllowed = true;
  14811. return
  14812. }
  14813. var out = this.context.pop();
  14814. if (out === types$1.b_stat && this.curContext().token === "function") {
  14815. out = this.context.pop();
  14816. }
  14817. this.exprAllowed = !out.isExpr;
  14818. };
  14819. types.braceL.updateContext = function(prevType) {
  14820. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  14821. this.exprAllowed = true;
  14822. };
  14823. types.dollarBraceL.updateContext = function() {
  14824. this.context.push(types$1.b_tmpl);
  14825. this.exprAllowed = true;
  14826. };
  14827. types.parenL.updateContext = function(prevType) {
  14828. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  14829. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  14830. this.exprAllowed = true;
  14831. };
  14832. types.incDec.updateContext = function() {
  14833. // tokExprAllowed stays unchanged
  14834. };
  14835. types._function.updateContext = types._class.updateContext = function(prevType) {
  14836. if (prevType.beforeExpr && prevType !== types._else &&
  14837. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  14838. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  14839. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  14840. { this.context.push(types$1.f_expr); }
  14841. else
  14842. { this.context.push(types$1.f_stat); }
  14843. this.exprAllowed = false;
  14844. };
  14845. types.backQuote.updateContext = function() {
  14846. if (this.curContext() === types$1.q_tmpl)
  14847. { this.context.pop(); }
  14848. else
  14849. { this.context.push(types$1.q_tmpl); }
  14850. this.exprAllowed = false;
  14851. };
  14852. types.star.updateContext = function(prevType) {
  14853. if (prevType === types._function) {
  14854. var index = this.context.length - 1;
  14855. if (this.context[index] === types$1.f_expr)
  14856. { this.context[index] = types$1.f_expr_gen; }
  14857. else
  14858. { this.context[index] = types$1.f_gen; }
  14859. }
  14860. this.exprAllowed = true;
  14861. };
  14862. types.name.updateContext = function(prevType) {
  14863. var allowed = false;
  14864. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  14865. if (this.value === "of" && !this.exprAllowed ||
  14866. this.value === "yield" && this.inGeneratorContext())
  14867. { allowed = true; }
  14868. }
  14869. this.exprAllowed = allowed;
  14870. };
  14871. // This file contains Unicode properties extracted from the ECMAScript
  14872. // specification. The lists are extracted like so:
  14873. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  14874. // #table-binary-unicode-properties
  14875. 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";
  14876. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  14877. var ecma11BinaryProperties = ecma10BinaryProperties;
  14878. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  14879. var unicodeBinaryProperties = {
  14880. 9: ecma9BinaryProperties,
  14881. 10: ecma10BinaryProperties,
  14882. 11: ecma11BinaryProperties,
  14883. 12: ecma12BinaryProperties
  14884. };
  14885. // #table-unicode-general-category-values
  14886. 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";
  14887. // #table-unicode-script-values
  14888. 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";
  14889. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  14890. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  14891. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  14892. var unicodeScriptValues = {
  14893. 9: ecma9ScriptValues,
  14894. 10: ecma10ScriptValues,
  14895. 11: ecma11ScriptValues,
  14896. 12: ecma12ScriptValues
  14897. };
  14898. var data = {};
  14899. function buildUnicodeData(ecmaVersion) {
  14900. var d = data[ecmaVersion] = {
  14901. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  14902. nonBinary: {
  14903. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  14904. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  14905. }
  14906. };
  14907. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  14908. d.nonBinary.gc = d.nonBinary.General_Category;
  14909. d.nonBinary.sc = d.nonBinary.Script;
  14910. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  14911. }
  14912. buildUnicodeData(9);
  14913. buildUnicodeData(10);
  14914. buildUnicodeData(11);
  14915. buildUnicodeData(12);
  14916. var pp$8 = Parser.prototype;
  14917. var RegExpValidationState = function RegExpValidationState(parser) {
  14918. this.parser = parser;
  14919. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
  14920. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  14921. this.source = "";
  14922. this.flags = "";
  14923. this.start = 0;
  14924. this.switchU = false;
  14925. this.switchN = false;
  14926. this.pos = 0;
  14927. this.lastIntValue = 0;
  14928. this.lastStringValue = "";
  14929. this.lastAssertionIsQuantifiable = false;
  14930. this.numCapturingParens = 0;
  14931. this.maxBackReference = 0;
  14932. this.groupNames = [];
  14933. this.backReferenceNames = [];
  14934. };
  14935. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  14936. var unicode = flags.indexOf("u") !== -1;
  14937. this.start = start | 0;
  14938. this.source = pattern + "";
  14939. this.flags = flags;
  14940. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  14941. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  14942. };
  14943. RegExpValidationState.prototype.raise = function raise (message) {
  14944. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  14945. };
  14946. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  14947. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  14948. RegExpValidationState.prototype.at = function at (i, forceU) {
  14949. if ( forceU === void 0 ) forceU = false;
  14950. var s = this.source;
  14951. var l = s.length;
  14952. if (i >= l) {
  14953. return -1
  14954. }
  14955. var c = s.charCodeAt(i);
  14956. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  14957. return c
  14958. }
  14959. var next = s.charCodeAt(i + 1);
  14960. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  14961. };
  14962. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  14963. if ( forceU === void 0 ) forceU = false;
  14964. var s = this.source;
  14965. var l = s.length;
  14966. if (i >= l) {
  14967. return l
  14968. }
  14969. var c = s.charCodeAt(i), next;
  14970. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  14971. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  14972. return i + 1
  14973. }
  14974. return i + 2
  14975. };
  14976. RegExpValidationState.prototype.current = function current (forceU) {
  14977. if ( forceU === void 0 ) forceU = false;
  14978. return this.at(this.pos, forceU)
  14979. };
  14980. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  14981. if ( forceU === void 0 ) forceU = false;
  14982. return this.at(this.nextIndex(this.pos, forceU), forceU)
  14983. };
  14984. RegExpValidationState.prototype.advance = function advance (forceU) {
  14985. if ( forceU === void 0 ) forceU = false;
  14986. this.pos = this.nextIndex(this.pos, forceU);
  14987. };
  14988. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  14989. if ( forceU === void 0 ) forceU = false;
  14990. if (this.current(forceU) === ch) {
  14991. this.advance(forceU);
  14992. return true
  14993. }
  14994. return false
  14995. };
  14996. function codePointToString(ch) {
  14997. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  14998. ch -= 0x10000;
  14999. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  15000. }
  15001. /**
  15002. * Validate the flags part of a given RegExpLiteral.
  15003. *
  15004. * @param {RegExpValidationState} state The state to validate RegExp.
  15005. * @returns {void}
  15006. */
  15007. pp$8.validateRegExpFlags = function(state) {
  15008. var validFlags = state.validFlags;
  15009. var flags = state.flags;
  15010. for (var i = 0; i < flags.length; i++) {
  15011. var flag = flags.charAt(i);
  15012. if (validFlags.indexOf(flag) === -1) {
  15013. this.raise(state.start, "Invalid regular expression flag");
  15014. }
  15015. if (flags.indexOf(flag, i + 1) > -1) {
  15016. this.raise(state.start, "Duplicate regular expression flag");
  15017. }
  15018. }
  15019. };
  15020. /**
  15021. * Validate the pattern part of a given RegExpLiteral.
  15022. *
  15023. * @param {RegExpValidationState} state The state to validate RegExp.
  15024. * @returns {void}
  15025. */
  15026. pp$8.validateRegExpPattern = function(state) {
  15027. this.regexp_pattern(state);
  15028. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  15029. // parsing contains a |GroupName|, reparse with the goal symbol
  15030. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  15031. // exception if _P_ did not conform to the grammar, if any elements of _P_
  15032. // were not matched by the parse, or if any Early Error conditions exist.
  15033. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  15034. state.switchN = true;
  15035. this.regexp_pattern(state);
  15036. }
  15037. };
  15038. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  15039. pp$8.regexp_pattern = function(state) {
  15040. state.pos = 0;
  15041. state.lastIntValue = 0;
  15042. state.lastStringValue = "";
  15043. state.lastAssertionIsQuantifiable = false;
  15044. state.numCapturingParens = 0;
  15045. state.maxBackReference = 0;
  15046. state.groupNames.length = 0;
  15047. state.backReferenceNames.length = 0;
  15048. this.regexp_disjunction(state);
  15049. if (state.pos !== state.source.length) {
  15050. // Make the same messages as V8.
  15051. if (state.eat(0x29 /* ) */)) {
  15052. state.raise("Unmatched ')'");
  15053. }
  15054. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  15055. state.raise("Lone quantifier brackets");
  15056. }
  15057. }
  15058. if (state.maxBackReference > state.numCapturingParens) {
  15059. state.raise("Invalid escape");
  15060. }
  15061. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  15062. var name = list[i];
  15063. if (state.groupNames.indexOf(name) === -1) {
  15064. state.raise("Invalid named capture referenced");
  15065. }
  15066. }
  15067. };
  15068. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  15069. pp$8.regexp_disjunction = function(state) {
  15070. this.regexp_alternative(state);
  15071. while (state.eat(0x7C /* | */)) {
  15072. this.regexp_alternative(state);
  15073. }
  15074. // Make the same message as V8.
  15075. if (this.regexp_eatQuantifier(state, true)) {
  15076. state.raise("Nothing to repeat");
  15077. }
  15078. if (state.eat(0x7B /* { */)) {
  15079. state.raise("Lone quantifier brackets");
  15080. }
  15081. };
  15082. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  15083. pp$8.regexp_alternative = function(state) {
  15084. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  15085. { }
  15086. };
  15087. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  15088. pp$8.regexp_eatTerm = function(state) {
  15089. if (this.regexp_eatAssertion(state)) {
  15090. // Handle `QuantifiableAssertion Quantifier` alternative.
  15091. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  15092. // is a QuantifiableAssertion.
  15093. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  15094. // Make the same message as V8.
  15095. if (state.switchU) {
  15096. state.raise("Invalid quantifier");
  15097. }
  15098. }
  15099. return true
  15100. }
  15101. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  15102. this.regexp_eatQuantifier(state);
  15103. return true
  15104. }
  15105. return false
  15106. };
  15107. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  15108. pp$8.regexp_eatAssertion = function(state) {
  15109. var start = state.pos;
  15110. state.lastAssertionIsQuantifiable = false;
  15111. // ^, $
  15112. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  15113. return true
  15114. }
  15115. // \b \B
  15116. if (state.eat(0x5C /* \ */)) {
  15117. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  15118. return true
  15119. }
  15120. state.pos = start;
  15121. }
  15122. // Lookahead / Lookbehind
  15123. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  15124. var lookbehind = false;
  15125. if (this.options.ecmaVersion >= 9) {
  15126. lookbehind = state.eat(0x3C /* < */);
  15127. }
  15128. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  15129. this.regexp_disjunction(state);
  15130. if (!state.eat(0x29 /* ) */)) {
  15131. state.raise("Unterminated group");
  15132. }
  15133. state.lastAssertionIsQuantifiable = !lookbehind;
  15134. return true
  15135. }
  15136. }
  15137. state.pos = start;
  15138. return false
  15139. };
  15140. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  15141. pp$8.regexp_eatQuantifier = function(state, noError) {
  15142. if ( noError === void 0 ) noError = false;
  15143. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  15144. state.eat(0x3F /* ? */);
  15145. return true
  15146. }
  15147. return false
  15148. };
  15149. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  15150. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  15151. return (
  15152. state.eat(0x2A /* * */) ||
  15153. state.eat(0x2B /* + */) ||
  15154. state.eat(0x3F /* ? */) ||
  15155. this.regexp_eatBracedQuantifier(state, noError)
  15156. )
  15157. };
  15158. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  15159. var start = state.pos;
  15160. if (state.eat(0x7B /* { */)) {
  15161. var min = 0, max = -1;
  15162. if (this.regexp_eatDecimalDigits(state)) {
  15163. min = state.lastIntValue;
  15164. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  15165. max = state.lastIntValue;
  15166. }
  15167. if (state.eat(0x7D /* } */)) {
  15168. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  15169. if (max !== -1 && max < min && !noError) {
  15170. state.raise("numbers out of order in {} quantifier");
  15171. }
  15172. return true
  15173. }
  15174. }
  15175. if (state.switchU && !noError) {
  15176. state.raise("Incomplete quantifier");
  15177. }
  15178. state.pos = start;
  15179. }
  15180. return false
  15181. };
  15182. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  15183. pp$8.regexp_eatAtom = function(state) {
  15184. return (
  15185. this.regexp_eatPatternCharacters(state) ||
  15186. state.eat(0x2E /* . */) ||
  15187. this.regexp_eatReverseSolidusAtomEscape(state) ||
  15188. this.regexp_eatCharacterClass(state) ||
  15189. this.regexp_eatUncapturingGroup(state) ||
  15190. this.regexp_eatCapturingGroup(state)
  15191. )
  15192. };
  15193. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  15194. var start = state.pos;
  15195. if (state.eat(0x5C /* \ */)) {
  15196. if (this.regexp_eatAtomEscape(state)) {
  15197. return true
  15198. }
  15199. state.pos = start;
  15200. }
  15201. return false
  15202. };
  15203. pp$8.regexp_eatUncapturingGroup = function(state) {
  15204. var start = state.pos;
  15205. if (state.eat(0x28 /* ( */)) {
  15206. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  15207. this.regexp_disjunction(state);
  15208. if (state.eat(0x29 /* ) */)) {
  15209. return true
  15210. }
  15211. state.raise("Unterminated group");
  15212. }
  15213. state.pos = start;
  15214. }
  15215. return false
  15216. };
  15217. pp$8.regexp_eatCapturingGroup = function(state) {
  15218. if (state.eat(0x28 /* ( */)) {
  15219. if (this.options.ecmaVersion >= 9) {
  15220. this.regexp_groupSpecifier(state);
  15221. } else if (state.current() === 0x3F /* ? */) {
  15222. state.raise("Invalid group");
  15223. }
  15224. this.regexp_disjunction(state);
  15225. if (state.eat(0x29 /* ) */)) {
  15226. state.numCapturingParens += 1;
  15227. return true
  15228. }
  15229. state.raise("Unterminated group");
  15230. }
  15231. return false
  15232. };
  15233. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  15234. pp$8.regexp_eatExtendedAtom = function(state) {
  15235. return (
  15236. state.eat(0x2E /* . */) ||
  15237. this.regexp_eatReverseSolidusAtomEscape(state) ||
  15238. this.regexp_eatCharacterClass(state) ||
  15239. this.regexp_eatUncapturingGroup(state) ||
  15240. this.regexp_eatCapturingGroup(state) ||
  15241. this.regexp_eatInvalidBracedQuantifier(state) ||
  15242. this.regexp_eatExtendedPatternCharacter(state)
  15243. )
  15244. };
  15245. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  15246. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  15247. if (this.regexp_eatBracedQuantifier(state, true)) {
  15248. state.raise("Nothing to repeat");
  15249. }
  15250. return false
  15251. };
  15252. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  15253. pp$8.regexp_eatSyntaxCharacter = function(state) {
  15254. var ch = state.current();
  15255. if (isSyntaxCharacter(ch)) {
  15256. state.lastIntValue = ch;
  15257. state.advance();
  15258. return true
  15259. }
  15260. return false
  15261. };
  15262. function isSyntaxCharacter(ch) {
  15263. return (
  15264. ch === 0x24 /* $ */ ||
  15265. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  15266. ch === 0x2E /* . */ ||
  15267. ch === 0x3F /* ? */ ||
  15268. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  15269. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  15270. )
  15271. }
  15272. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  15273. // But eat eager.
  15274. pp$8.regexp_eatPatternCharacters = function(state) {
  15275. var start = state.pos;
  15276. var ch = 0;
  15277. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  15278. state.advance();
  15279. }
  15280. return state.pos !== start
  15281. };
  15282. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  15283. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  15284. var ch = state.current();
  15285. if (
  15286. ch !== -1 &&
  15287. ch !== 0x24 /* $ */ &&
  15288. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  15289. ch !== 0x2E /* . */ &&
  15290. ch !== 0x3F /* ? */ &&
  15291. ch !== 0x5B /* [ */ &&
  15292. ch !== 0x5E /* ^ */ &&
  15293. ch !== 0x7C /* | */
  15294. ) {
  15295. state.advance();
  15296. return true
  15297. }
  15298. return false
  15299. };
  15300. // GroupSpecifier ::
  15301. // [empty]
  15302. // `?` GroupName
  15303. pp$8.regexp_groupSpecifier = function(state) {
  15304. if (state.eat(0x3F /* ? */)) {
  15305. if (this.regexp_eatGroupName(state)) {
  15306. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  15307. state.raise("Duplicate capture group name");
  15308. }
  15309. state.groupNames.push(state.lastStringValue);
  15310. return
  15311. }
  15312. state.raise("Invalid group");
  15313. }
  15314. };
  15315. // GroupName ::
  15316. // `<` RegExpIdentifierName `>`
  15317. // Note: this updates `state.lastStringValue` property with the eaten name.
  15318. pp$8.regexp_eatGroupName = function(state) {
  15319. state.lastStringValue = "";
  15320. if (state.eat(0x3C /* < */)) {
  15321. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  15322. return true
  15323. }
  15324. state.raise("Invalid capture group name");
  15325. }
  15326. return false
  15327. };
  15328. // RegExpIdentifierName ::
  15329. // RegExpIdentifierStart
  15330. // RegExpIdentifierName RegExpIdentifierPart
  15331. // Note: this updates `state.lastStringValue` property with the eaten name.
  15332. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  15333. state.lastStringValue = "";
  15334. if (this.regexp_eatRegExpIdentifierStart(state)) {
  15335. state.lastStringValue += codePointToString(state.lastIntValue);
  15336. while (this.regexp_eatRegExpIdentifierPart(state)) {
  15337. state.lastStringValue += codePointToString(state.lastIntValue);
  15338. }
  15339. return true
  15340. }
  15341. return false
  15342. };
  15343. // RegExpIdentifierStart ::
  15344. // UnicodeIDStart
  15345. // `$`
  15346. // `_`
  15347. // `\` RegExpUnicodeEscapeSequence[+U]
  15348. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  15349. var start = state.pos;
  15350. var forceU = this.options.ecmaVersion >= 11;
  15351. var ch = state.current(forceU);
  15352. state.advance(forceU);
  15353. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  15354. ch = state.lastIntValue;
  15355. }
  15356. if (isRegExpIdentifierStart(ch)) {
  15357. state.lastIntValue = ch;
  15358. return true
  15359. }
  15360. state.pos = start;
  15361. return false
  15362. };
  15363. function isRegExpIdentifierStart(ch) {
  15364. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  15365. }
  15366. // RegExpIdentifierPart ::
  15367. // UnicodeIDContinue
  15368. // `$`
  15369. // `_`
  15370. // `\` RegExpUnicodeEscapeSequence[+U]
  15371. // <ZWNJ>
  15372. // <ZWJ>
  15373. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  15374. var start = state.pos;
  15375. var forceU = this.options.ecmaVersion >= 11;
  15376. var ch = state.current(forceU);
  15377. state.advance(forceU);
  15378. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  15379. ch = state.lastIntValue;
  15380. }
  15381. if (isRegExpIdentifierPart(ch)) {
  15382. state.lastIntValue = ch;
  15383. return true
  15384. }
  15385. state.pos = start;
  15386. return false
  15387. };
  15388. function isRegExpIdentifierPart(ch) {
  15389. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  15390. }
  15391. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  15392. pp$8.regexp_eatAtomEscape = function(state) {
  15393. if (
  15394. this.regexp_eatBackReference(state) ||
  15395. this.regexp_eatCharacterClassEscape(state) ||
  15396. this.regexp_eatCharacterEscape(state) ||
  15397. (state.switchN && this.regexp_eatKGroupName(state))
  15398. ) {
  15399. return true
  15400. }
  15401. if (state.switchU) {
  15402. // Make the same message as V8.
  15403. if (state.current() === 0x63 /* c */) {
  15404. state.raise("Invalid unicode escape");
  15405. }
  15406. state.raise("Invalid escape");
  15407. }
  15408. return false
  15409. };
  15410. pp$8.regexp_eatBackReference = function(state) {
  15411. var start = state.pos;
  15412. if (this.regexp_eatDecimalEscape(state)) {
  15413. var n = state.lastIntValue;
  15414. if (state.switchU) {
  15415. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  15416. if (n > state.maxBackReference) {
  15417. state.maxBackReference = n;
  15418. }
  15419. return true
  15420. }
  15421. if (n <= state.numCapturingParens) {
  15422. return true
  15423. }
  15424. state.pos = start;
  15425. }
  15426. return false
  15427. };
  15428. pp$8.regexp_eatKGroupName = function(state) {
  15429. if (state.eat(0x6B /* k */)) {
  15430. if (this.regexp_eatGroupName(state)) {
  15431. state.backReferenceNames.push(state.lastStringValue);
  15432. return true
  15433. }
  15434. state.raise("Invalid named reference");
  15435. }
  15436. return false
  15437. };
  15438. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  15439. pp$8.regexp_eatCharacterEscape = function(state) {
  15440. return (
  15441. this.regexp_eatControlEscape(state) ||
  15442. this.regexp_eatCControlLetter(state) ||
  15443. this.regexp_eatZero(state) ||
  15444. this.regexp_eatHexEscapeSequence(state) ||
  15445. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  15446. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  15447. this.regexp_eatIdentityEscape(state)
  15448. )
  15449. };
  15450. pp$8.regexp_eatCControlLetter = function(state) {
  15451. var start = state.pos;
  15452. if (state.eat(0x63 /* c */)) {
  15453. if (this.regexp_eatControlLetter(state)) {
  15454. return true
  15455. }
  15456. state.pos = start;
  15457. }
  15458. return false
  15459. };
  15460. pp$8.regexp_eatZero = function(state) {
  15461. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  15462. state.lastIntValue = 0;
  15463. state.advance();
  15464. return true
  15465. }
  15466. return false
  15467. };
  15468. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  15469. pp$8.regexp_eatControlEscape = function(state) {
  15470. var ch = state.current();
  15471. if (ch === 0x74 /* t */) {
  15472. state.lastIntValue = 0x09; /* \t */
  15473. state.advance();
  15474. return true
  15475. }
  15476. if (ch === 0x6E /* n */) {
  15477. state.lastIntValue = 0x0A; /* \n */
  15478. state.advance();
  15479. return true
  15480. }
  15481. if (ch === 0x76 /* v */) {
  15482. state.lastIntValue = 0x0B; /* \v */
  15483. state.advance();
  15484. return true
  15485. }
  15486. if (ch === 0x66 /* f */) {
  15487. state.lastIntValue = 0x0C; /* \f */
  15488. state.advance();
  15489. return true
  15490. }
  15491. if (ch === 0x72 /* r */) {
  15492. state.lastIntValue = 0x0D; /* \r */
  15493. state.advance();
  15494. return true
  15495. }
  15496. return false
  15497. };
  15498. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  15499. pp$8.regexp_eatControlLetter = function(state) {
  15500. var ch = state.current();
  15501. if (isControlLetter(ch)) {
  15502. state.lastIntValue = ch % 0x20;
  15503. state.advance();
  15504. return true
  15505. }
  15506. return false
  15507. };
  15508. function isControlLetter(ch) {
  15509. return (
  15510. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  15511. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  15512. )
  15513. }
  15514. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  15515. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  15516. if ( forceU === void 0 ) forceU = false;
  15517. var start = state.pos;
  15518. var switchU = forceU || state.switchU;
  15519. if (state.eat(0x75 /* u */)) {
  15520. if (this.regexp_eatFixedHexDigits(state, 4)) {
  15521. var lead = state.lastIntValue;
  15522. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  15523. var leadSurrogateEnd = state.pos;
  15524. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  15525. var trail = state.lastIntValue;
  15526. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  15527. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  15528. return true
  15529. }
  15530. }
  15531. state.pos = leadSurrogateEnd;
  15532. state.lastIntValue = lead;
  15533. }
  15534. return true
  15535. }
  15536. if (
  15537. switchU &&
  15538. state.eat(0x7B /* { */) &&
  15539. this.regexp_eatHexDigits(state) &&
  15540. state.eat(0x7D /* } */) &&
  15541. isValidUnicode(state.lastIntValue)
  15542. ) {
  15543. return true
  15544. }
  15545. if (switchU) {
  15546. state.raise("Invalid unicode escape");
  15547. }
  15548. state.pos = start;
  15549. }
  15550. return false
  15551. };
  15552. function isValidUnicode(ch) {
  15553. return ch >= 0 && ch <= 0x10FFFF
  15554. }
  15555. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  15556. pp$8.regexp_eatIdentityEscape = function(state) {
  15557. if (state.switchU) {
  15558. if (this.regexp_eatSyntaxCharacter(state)) {
  15559. return true
  15560. }
  15561. if (state.eat(0x2F /* / */)) {
  15562. state.lastIntValue = 0x2F; /* / */
  15563. return true
  15564. }
  15565. return false
  15566. }
  15567. var ch = state.current();
  15568. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  15569. state.lastIntValue = ch;
  15570. state.advance();
  15571. return true
  15572. }
  15573. return false
  15574. };
  15575. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  15576. pp$8.regexp_eatDecimalEscape = function(state) {
  15577. state.lastIntValue = 0;
  15578. var ch = state.current();
  15579. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  15580. do {
  15581. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  15582. state.advance();
  15583. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  15584. return true
  15585. }
  15586. return false
  15587. };
  15588. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  15589. pp$8.regexp_eatCharacterClassEscape = function(state) {
  15590. var ch = state.current();
  15591. if (isCharacterClassEscape(ch)) {
  15592. state.lastIntValue = -1;
  15593. state.advance();
  15594. return true
  15595. }
  15596. if (
  15597. state.switchU &&
  15598. this.options.ecmaVersion >= 9 &&
  15599. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  15600. ) {
  15601. state.lastIntValue = -1;
  15602. state.advance();
  15603. if (
  15604. state.eat(0x7B /* { */) &&
  15605. this.regexp_eatUnicodePropertyValueExpression(state) &&
  15606. state.eat(0x7D /* } */)
  15607. ) {
  15608. return true
  15609. }
  15610. state.raise("Invalid property name");
  15611. }
  15612. return false
  15613. };
  15614. function isCharacterClassEscape(ch) {
  15615. return (
  15616. ch === 0x64 /* d */ ||
  15617. ch === 0x44 /* D */ ||
  15618. ch === 0x73 /* s */ ||
  15619. ch === 0x53 /* S */ ||
  15620. ch === 0x77 /* w */ ||
  15621. ch === 0x57 /* W */
  15622. )
  15623. }
  15624. // UnicodePropertyValueExpression ::
  15625. // UnicodePropertyName `=` UnicodePropertyValue
  15626. // LoneUnicodePropertyNameOrValue
  15627. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  15628. var start = state.pos;
  15629. // UnicodePropertyName `=` UnicodePropertyValue
  15630. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  15631. var name = state.lastStringValue;
  15632. if (this.regexp_eatUnicodePropertyValue(state)) {
  15633. var value = state.lastStringValue;
  15634. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  15635. return true
  15636. }
  15637. }
  15638. state.pos = start;
  15639. // LoneUnicodePropertyNameOrValue
  15640. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  15641. var nameOrValue = state.lastStringValue;
  15642. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  15643. return true
  15644. }
  15645. return false
  15646. };
  15647. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  15648. if (!has(state.unicodeProperties.nonBinary, name))
  15649. { state.raise("Invalid property name"); }
  15650. if (!state.unicodeProperties.nonBinary[name].test(value))
  15651. { state.raise("Invalid property value"); }
  15652. };
  15653. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  15654. if (!state.unicodeProperties.binary.test(nameOrValue))
  15655. { state.raise("Invalid property name"); }
  15656. };
  15657. // UnicodePropertyName ::
  15658. // UnicodePropertyNameCharacters
  15659. pp$8.regexp_eatUnicodePropertyName = function(state) {
  15660. var ch = 0;
  15661. state.lastStringValue = "";
  15662. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  15663. state.lastStringValue += codePointToString(ch);
  15664. state.advance();
  15665. }
  15666. return state.lastStringValue !== ""
  15667. };
  15668. function isUnicodePropertyNameCharacter(ch) {
  15669. return isControlLetter(ch) || ch === 0x5F /* _ */
  15670. }
  15671. // UnicodePropertyValue ::
  15672. // UnicodePropertyValueCharacters
  15673. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  15674. var ch = 0;
  15675. state.lastStringValue = "";
  15676. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  15677. state.lastStringValue += codePointToString(ch);
  15678. state.advance();
  15679. }
  15680. return state.lastStringValue !== ""
  15681. };
  15682. function isUnicodePropertyValueCharacter(ch) {
  15683. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  15684. }
  15685. // LoneUnicodePropertyNameOrValue ::
  15686. // UnicodePropertyValueCharacters
  15687. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  15688. return this.regexp_eatUnicodePropertyValue(state)
  15689. };
  15690. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  15691. pp$8.regexp_eatCharacterClass = function(state) {
  15692. if (state.eat(0x5B /* [ */)) {
  15693. state.eat(0x5E /* ^ */);
  15694. this.regexp_classRanges(state);
  15695. if (state.eat(0x5D /* ] */)) {
  15696. return true
  15697. }
  15698. // Unreachable since it threw "unterminated regular expression" error before.
  15699. state.raise("Unterminated character class");
  15700. }
  15701. return false
  15702. };
  15703. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  15704. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  15705. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  15706. pp$8.regexp_classRanges = function(state) {
  15707. while (this.regexp_eatClassAtom(state)) {
  15708. var left = state.lastIntValue;
  15709. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  15710. var right = state.lastIntValue;
  15711. if (state.switchU && (left === -1 || right === -1)) {
  15712. state.raise("Invalid character class");
  15713. }
  15714. if (left !== -1 && right !== -1 && left > right) {
  15715. state.raise("Range out of order in character class");
  15716. }
  15717. }
  15718. }
  15719. };
  15720. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  15721. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  15722. pp$8.regexp_eatClassAtom = function(state) {
  15723. var start = state.pos;
  15724. if (state.eat(0x5C /* \ */)) {
  15725. if (this.regexp_eatClassEscape(state)) {
  15726. return true
  15727. }
  15728. if (state.switchU) {
  15729. // Make the same message as V8.
  15730. var ch$1 = state.current();
  15731. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  15732. state.raise("Invalid class escape");
  15733. }
  15734. state.raise("Invalid escape");
  15735. }
  15736. state.pos = start;
  15737. }
  15738. var ch = state.current();
  15739. if (ch !== 0x5D /* ] */) {
  15740. state.lastIntValue = ch;
  15741. state.advance();
  15742. return true
  15743. }
  15744. return false
  15745. };
  15746. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  15747. pp$8.regexp_eatClassEscape = function(state) {
  15748. var start = state.pos;
  15749. if (state.eat(0x62 /* b */)) {
  15750. state.lastIntValue = 0x08; /* <BS> */
  15751. return true
  15752. }
  15753. if (state.switchU && state.eat(0x2D /* - */)) {
  15754. state.lastIntValue = 0x2D; /* - */
  15755. return true
  15756. }
  15757. if (!state.switchU && state.eat(0x63 /* c */)) {
  15758. if (this.regexp_eatClassControlLetter(state)) {
  15759. return true
  15760. }
  15761. state.pos = start;
  15762. }
  15763. return (
  15764. this.regexp_eatCharacterClassEscape(state) ||
  15765. this.regexp_eatCharacterEscape(state)
  15766. )
  15767. };
  15768. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  15769. pp$8.regexp_eatClassControlLetter = function(state) {
  15770. var ch = state.current();
  15771. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  15772. state.lastIntValue = ch % 0x20;
  15773. state.advance();
  15774. return true
  15775. }
  15776. return false
  15777. };
  15778. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  15779. pp$8.regexp_eatHexEscapeSequence = function(state) {
  15780. var start = state.pos;
  15781. if (state.eat(0x78 /* x */)) {
  15782. if (this.regexp_eatFixedHexDigits(state, 2)) {
  15783. return true
  15784. }
  15785. if (state.switchU) {
  15786. state.raise("Invalid escape");
  15787. }
  15788. state.pos = start;
  15789. }
  15790. return false
  15791. };
  15792. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  15793. pp$8.regexp_eatDecimalDigits = function(state) {
  15794. var start = state.pos;
  15795. var ch = 0;
  15796. state.lastIntValue = 0;
  15797. while (isDecimalDigit(ch = state.current())) {
  15798. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  15799. state.advance();
  15800. }
  15801. return state.pos !== start
  15802. };
  15803. function isDecimalDigit(ch) {
  15804. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  15805. }
  15806. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  15807. pp$8.regexp_eatHexDigits = function(state) {
  15808. var start = state.pos;
  15809. var ch = 0;
  15810. state.lastIntValue = 0;
  15811. while (isHexDigit(ch = state.current())) {
  15812. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  15813. state.advance();
  15814. }
  15815. return state.pos !== start
  15816. };
  15817. function isHexDigit(ch) {
  15818. return (
  15819. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  15820. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  15821. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  15822. )
  15823. }
  15824. function hexToInt(ch) {
  15825. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  15826. return 10 + (ch - 0x41 /* A */)
  15827. }
  15828. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  15829. return 10 + (ch - 0x61 /* a */)
  15830. }
  15831. return ch - 0x30 /* 0 */
  15832. }
  15833. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  15834. // Allows only 0-377(octal) i.e. 0-255(decimal).
  15835. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  15836. if (this.regexp_eatOctalDigit(state)) {
  15837. var n1 = state.lastIntValue;
  15838. if (this.regexp_eatOctalDigit(state)) {
  15839. var n2 = state.lastIntValue;
  15840. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  15841. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  15842. } else {
  15843. state.lastIntValue = n1 * 8 + n2;
  15844. }
  15845. } else {
  15846. state.lastIntValue = n1;
  15847. }
  15848. return true
  15849. }
  15850. return false
  15851. };
  15852. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  15853. pp$8.regexp_eatOctalDigit = function(state) {
  15854. var ch = state.current();
  15855. if (isOctalDigit(ch)) {
  15856. state.lastIntValue = ch - 0x30; /* 0 */
  15857. state.advance();
  15858. return true
  15859. }
  15860. state.lastIntValue = 0;
  15861. return false
  15862. };
  15863. function isOctalDigit(ch) {
  15864. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  15865. }
  15866. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  15867. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  15868. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  15869. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  15870. var start = state.pos;
  15871. state.lastIntValue = 0;
  15872. for (var i = 0; i < length; ++i) {
  15873. var ch = state.current();
  15874. if (!isHexDigit(ch)) {
  15875. state.pos = start;
  15876. return false
  15877. }
  15878. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  15879. state.advance();
  15880. }
  15881. return true
  15882. };
  15883. // Object type used to represent tokens. Note that normally, tokens
  15884. // simply exist as properties on the parser object. This is only
  15885. // used for the onToken callback and the external tokenizer.
  15886. var Token = function Token(p) {
  15887. this.type = p.type;
  15888. this.value = p.value;
  15889. this.start = p.start;
  15890. this.end = p.end;
  15891. if (p.options.locations)
  15892. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  15893. if (p.options.ranges)
  15894. { this.range = [p.start, p.end]; }
  15895. };
  15896. // ## Tokenizer
  15897. var pp$9 = Parser.prototype;
  15898. // Move to the next token
  15899. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  15900. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  15901. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  15902. if (this.options.onToken)
  15903. { this.options.onToken(new Token(this)); }
  15904. this.lastTokEnd = this.end;
  15905. this.lastTokStart = this.start;
  15906. this.lastTokEndLoc = this.endLoc;
  15907. this.lastTokStartLoc = this.startLoc;
  15908. this.nextToken();
  15909. };
  15910. pp$9.getToken = function() {
  15911. this.next();
  15912. return new Token(this)
  15913. };
  15914. // If we're in an ES6 environment, make parsers iterable
  15915. if (typeof Symbol !== "undefined")
  15916. { pp$9[Symbol.iterator] = function() {
  15917. var this$1 = this;
  15918. return {
  15919. next: function () {
  15920. var token = this$1.getToken();
  15921. return {
  15922. done: token.type === types.eof,
  15923. value: token
  15924. }
  15925. }
  15926. }
  15927. }; }
  15928. // Toggle strict mode. Re-reads the next number or string to please
  15929. // pedantic tests (`"use strict"; 010;` should fail).
  15930. pp$9.curContext = function() {
  15931. return this.context[this.context.length - 1]
  15932. };
  15933. // Read a single token, updating the parser object's token-related
  15934. // properties.
  15935. pp$9.nextToken = function() {
  15936. var curContext = this.curContext();
  15937. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  15938. this.start = this.pos;
  15939. if (this.options.locations) { this.startLoc = this.curPosition(); }
  15940. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  15941. if (curContext.override) { return curContext.override(this) }
  15942. else { this.readToken(this.fullCharCodeAtPos()); }
  15943. };
  15944. pp$9.readToken = function(code) {
  15945. // Identifier or keyword. '\uXXXX' sequences are allowed in
  15946. // identifiers, so '\' also dispatches to that.
  15947. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  15948. { return this.readWord() }
  15949. return this.getTokenFromCode(code)
  15950. };
  15951. pp$9.fullCharCodeAtPos = function() {
  15952. var code = this.input.charCodeAt(this.pos);
  15953. if (code <= 0xd7ff || code >= 0xe000) { return code }
  15954. var next = this.input.charCodeAt(this.pos + 1);
  15955. return (code << 10) + next - 0x35fdc00
  15956. };
  15957. pp$9.skipBlockComment = function() {
  15958. var startLoc = this.options.onComment && this.curPosition();
  15959. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  15960. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  15961. this.pos = end + 2;
  15962. if (this.options.locations) {
  15963. lineBreakG.lastIndex = start;
  15964. var match;
  15965. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  15966. ++this.curLine;
  15967. this.lineStart = match.index + match[0].length;
  15968. }
  15969. }
  15970. if (this.options.onComment)
  15971. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  15972. startLoc, this.curPosition()); }
  15973. };
  15974. pp$9.skipLineComment = function(startSkip) {
  15975. var start = this.pos;
  15976. var startLoc = this.options.onComment && this.curPosition();
  15977. var ch = this.input.charCodeAt(this.pos += startSkip);
  15978. while (this.pos < this.input.length && !isNewLine(ch)) {
  15979. ch = this.input.charCodeAt(++this.pos);
  15980. }
  15981. if (this.options.onComment)
  15982. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  15983. startLoc, this.curPosition()); }
  15984. };
  15985. // Called at the start of the parse and after every token. Skips
  15986. // whitespace and comments, and.
  15987. pp$9.skipSpace = function() {
  15988. loop: while (this.pos < this.input.length) {
  15989. var ch = this.input.charCodeAt(this.pos);
  15990. switch (ch) {
  15991. case 32: case 160: // ' '
  15992. ++this.pos;
  15993. break
  15994. case 13:
  15995. if (this.input.charCodeAt(this.pos + 1) === 10) {
  15996. ++this.pos;
  15997. }
  15998. case 10: case 8232: case 8233:
  15999. ++this.pos;
  16000. if (this.options.locations) {
  16001. ++this.curLine;
  16002. this.lineStart = this.pos;
  16003. }
  16004. break
  16005. case 47: // '/'
  16006. switch (this.input.charCodeAt(this.pos + 1)) {
  16007. case 42: // '*'
  16008. this.skipBlockComment();
  16009. break
  16010. case 47:
  16011. this.skipLineComment(2);
  16012. break
  16013. default:
  16014. break loop
  16015. }
  16016. break
  16017. default:
  16018. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  16019. ++this.pos;
  16020. } else {
  16021. break loop
  16022. }
  16023. }
  16024. }
  16025. };
  16026. // Called at the end of every token. Sets `end`, `val`, and
  16027. // maintains `context` and `exprAllowed`, and skips the space after
  16028. // the token, so that the next one's `start` will point at the
  16029. // right position.
  16030. pp$9.finishToken = function(type, val) {
  16031. this.end = this.pos;
  16032. if (this.options.locations) { this.endLoc = this.curPosition(); }
  16033. var prevType = this.type;
  16034. this.type = type;
  16035. this.value = val;
  16036. this.updateContext(prevType);
  16037. };
  16038. // ### Token reading
  16039. // This is the function that is called to fetch the next token. It
  16040. // is somewhat obscure, because it works in character codes rather
  16041. // than characters, and because operator parsing has been inlined
  16042. // into it.
  16043. //
  16044. // All in the name of speed.
  16045. //
  16046. pp$9.readToken_dot = function() {
  16047. var next = this.input.charCodeAt(this.pos + 1);
  16048. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  16049. var next2 = this.input.charCodeAt(this.pos + 2);
  16050. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  16051. this.pos += 3;
  16052. return this.finishToken(types.ellipsis)
  16053. } else {
  16054. ++this.pos;
  16055. return this.finishToken(types.dot)
  16056. }
  16057. };
  16058. pp$9.readToken_slash = function() { // '/'
  16059. var next = this.input.charCodeAt(this.pos + 1);
  16060. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  16061. if (next === 61) { return this.finishOp(types.assign, 2) }
  16062. return this.finishOp(types.slash, 1)
  16063. };
  16064. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  16065. var next = this.input.charCodeAt(this.pos + 1);
  16066. var size = 1;
  16067. var tokentype = code === 42 ? types.star : types.modulo;
  16068. // exponentiation operator ** and **=
  16069. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  16070. ++size;
  16071. tokentype = types.starstar;
  16072. next = this.input.charCodeAt(this.pos + 2);
  16073. }
  16074. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  16075. return this.finishOp(tokentype, size)
  16076. };
  16077. pp$9.readToken_pipe_amp = function(code) { // '|&'
  16078. var next = this.input.charCodeAt(this.pos + 1);
  16079. if (next === code) {
  16080. if (this.options.ecmaVersion >= 12) {
  16081. var next2 = this.input.charCodeAt(this.pos + 2);
  16082. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  16083. }
  16084. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  16085. }
  16086. if (next === 61) { return this.finishOp(types.assign, 2) }
  16087. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  16088. };
  16089. pp$9.readToken_caret = function() { // '^'
  16090. var next = this.input.charCodeAt(this.pos + 1);
  16091. if (next === 61) { return this.finishOp(types.assign, 2) }
  16092. return this.finishOp(types.bitwiseXOR, 1)
  16093. };
  16094. pp$9.readToken_plus_min = function(code) { // '+-'
  16095. var next = this.input.charCodeAt(this.pos + 1);
  16096. if (next === code) {
  16097. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  16098. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  16099. // A `-->` line comment
  16100. this.skipLineComment(3);
  16101. this.skipSpace();
  16102. return this.nextToken()
  16103. }
  16104. return this.finishOp(types.incDec, 2)
  16105. }
  16106. if (next === 61) { return this.finishOp(types.assign, 2) }
  16107. return this.finishOp(types.plusMin, 1)
  16108. };
  16109. pp$9.readToken_lt_gt = function(code) { // '<>'
  16110. var next = this.input.charCodeAt(this.pos + 1);
  16111. var size = 1;
  16112. if (next === code) {
  16113. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  16114. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  16115. return this.finishOp(types.bitShift, size)
  16116. }
  16117. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  16118. this.input.charCodeAt(this.pos + 3) === 45) {
  16119. // `<!--`, an XML-style comment that should be interpreted as a line comment
  16120. this.skipLineComment(4);
  16121. this.skipSpace();
  16122. return this.nextToken()
  16123. }
  16124. if (next === 61) { size = 2; }
  16125. return this.finishOp(types.relational, size)
  16126. };
  16127. pp$9.readToken_eq_excl = function(code) { // '=!'
  16128. var next = this.input.charCodeAt(this.pos + 1);
  16129. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  16130. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  16131. this.pos += 2;
  16132. return this.finishToken(types.arrow)
  16133. }
  16134. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  16135. };
  16136. pp$9.readToken_question = function() { // '?'
  16137. var ecmaVersion = this.options.ecmaVersion;
  16138. if (ecmaVersion >= 11) {
  16139. var next = this.input.charCodeAt(this.pos + 1);
  16140. if (next === 46) {
  16141. var next2 = this.input.charCodeAt(this.pos + 2);
  16142. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  16143. }
  16144. if (next === 63) {
  16145. if (ecmaVersion >= 12) {
  16146. var next2$1 = this.input.charCodeAt(this.pos + 2);
  16147. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  16148. }
  16149. return this.finishOp(types.coalesce, 2)
  16150. }
  16151. }
  16152. return this.finishOp(types.question, 1)
  16153. };
  16154. pp$9.getTokenFromCode = function(code) {
  16155. switch (code) {
  16156. // The interpretation of a dot depends on whether it is followed
  16157. // by a digit or another two dots.
  16158. case 46: // '.'
  16159. return this.readToken_dot()
  16160. // Punctuation tokens.
  16161. case 40: ++this.pos; return this.finishToken(types.parenL)
  16162. case 41: ++this.pos; return this.finishToken(types.parenR)
  16163. case 59: ++this.pos; return this.finishToken(types.semi)
  16164. case 44: ++this.pos; return this.finishToken(types.comma)
  16165. case 91: ++this.pos; return this.finishToken(types.bracketL)
  16166. case 93: ++this.pos; return this.finishToken(types.bracketR)
  16167. case 123: ++this.pos; return this.finishToken(types.braceL)
  16168. case 125: ++this.pos; return this.finishToken(types.braceR)
  16169. case 58: ++this.pos; return this.finishToken(types.colon)
  16170. case 96: // '`'
  16171. if (this.options.ecmaVersion < 6) { break }
  16172. ++this.pos;
  16173. return this.finishToken(types.backQuote)
  16174. case 48: // '0'
  16175. var next = this.input.charCodeAt(this.pos + 1);
  16176. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  16177. if (this.options.ecmaVersion >= 6) {
  16178. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  16179. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  16180. }
  16181. // Anything else beginning with a digit is an integer, octal
  16182. // number, or float.
  16183. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  16184. return this.readNumber(false)
  16185. // Quotes produce strings.
  16186. case 34: case 39: // '"', "'"
  16187. return this.readString(code)
  16188. // Operators are parsed inline in tiny state machines. '=' (61) is
  16189. // often referred to. `finishOp` simply skips the amount of
  16190. // characters it is given as second argument, and returns a token
  16191. // of the type given by its first argument.
  16192. case 47: // '/'
  16193. return this.readToken_slash()
  16194. case 37: case 42: // '%*'
  16195. return this.readToken_mult_modulo_exp(code)
  16196. case 124: case 38: // '|&'
  16197. return this.readToken_pipe_amp(code)
  16198. case 94: // '^'
  16199. return this.readToken_caret()
  16200. case 43: case 45: // '+-'
  16201. return this.readToken_plus_min(code)
  16202. case 60: case 62: // '<>'
  16203. return this.readToken_lt_gt(code)
  16204. case 61: case 33: // '=!'
  16205. return this.readToken_eq_excl(code)
  16206. case 63: // '?'
  16207. return this.readToken_question()
  16208. case 126: // '~'
  16209. return this.finishOp(types.prefix, 1)
  16210. }
  16211. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  16212. };
  16213. pp$9.finishOp = function(type, size) {
  16214. var str = this.input.slice(this.pos, this.pos + size);
  16215. this.pos += size;
  16216. return this.finishToken(type, str)
  16217. };
  16218. pp$9.readRegexp = function() {
  16219. var escaped, inClass, start = this.pos;
  16220. for (;;) {
  16221. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  16222. var ch = this.input.charAt(this.pos);
  16223. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  16224. if (!escaped) {
  16225. if (ch === "[") { inClass = true; }
  16226. else if (ch === "]" && inClass) { inClass = false; }
  16227. else if (ch === "/" && !inClass) { break }
  16228. escaped = ch === "\\";
  16229. } else { escaped = false; }
  16230. ++this.pos;
  16231. }
  16232. var pattern = this.input.slice(start, this.pos);
  16233. ++this.pos;
  16234. var flagsStart = this.pos;
  16235. var flags = this.readWord1();
  16236. if (this.containsEsc) { this.unexpected(flagsStart); }
  16237. // Validate pattern
  16238. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  16239. state.reset(start, pattern, flags);
  16240. this.validateRegExpFlags(state);
  16241. this.validateRegExpPattern(state);
  16242. // Create Literal#value property value.
  16243. var value = null;
  16244. try {
  16245. value = new RegExp(pattern, flags);
  16246. } catch (e) {
  16247. // ESTree requires null if it failed to instantiate RegExp object.
  16248. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  16249. }
  16250. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  16251. };
  16252. // Read an integer in the given radix. Return null if zero digits
  16253. // were read, the integer value otherwise. When `len` is given, this
  16254. // will return `null` unless the integer has exactly `len` digits.
  16255. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  16256. // `len` is used for character escape sequences. In that case, disallow separators.
  16257. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  16258. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  16259. // and isn't fraction part nor exponent part. In that case, if the first digit
  16260. // is zero then disallow separators.
  16261. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  16262. var start = this.pos, total = 0, lastCode = 0;
  16263. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  16264. var code = this.input.charCodeAt(this.pos), val = (void 0);
  16265. if (allowSeparators && code === 95) {
  16266. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  16267. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  16268. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  16269. lastCode = code;
  16270. continue
  16271. }
  16272. if (code >= 97) { val = code - 97 + 10; } // a
  16273. else if (code >= 65) { val = code - 65 + 10; } // A
  16274. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  16275. else { val = Infinity; }
  16276. if (val >= radix) { break }
  16277. lastCode = code;
  16278. total = total * radix + val;
  16279. }
  16280. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  16281. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  16282. return total
  16283. };
  16284. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  16285. if (isLegacyOctalNumericLiteral) {
  16286. return parseInt(str, 8)
  16287. }
  16288. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  16289. return parseFloat(str.replace(/_/g, ""))
  16290. }
  16291. function stringToBigInt(str) {
  16292. if (typeof BigInt !== "function") {
  16293. return null
  16294. }
  16295. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  16296. return BigInt(str.replace(/_/g, ""))
  16297. }
  16298. pp$9.readRadixNumber = function(radix) {
  16299. var start = this.pos;
  16300. this.pos += 2; // 0x
  16301. var val = this.readInt(radix);
  16302. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  16303. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  16304. val = stringToBigInt(this.input.slice(start, this.pos));
  16305. ++this.pos;
  16306. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16307. return this.finishToken(types.num, val)
  16308. };
  16309. // Read an integer, octal integer, or floating-point number.
  16310. pp$9.readNumber = function(startsWithDot) {
  16311. var start = this.pos;
  16312. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  16313. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  16314. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  16315. var next = this.input.charCodeAt(this.pos);
  16316. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  16317. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  16318. ++this.pos;
  16319. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16320. return this.finishToken(types.num, val$1)
  16321. }
  16322. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  16323. if (next === 46 && !octal) { // '.'
  16324. ++this.pos;
  16325. this.readInt(10);
  16326. next = this.input.charCodeAt(this.pos);
  16327. }
  16328. if ((next === 69 || next === 101) && !octal) { // 'eE'
  16329. next = this.input.charCodeAt(++this.pos);
  16330. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  16331. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  16332. }
  16333. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16334. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  16335. return this.finishToken(types.num, val)
  16336. };
  16337. // Read a string value, interpreting backslash-escapes.
  16338. pp$9.readCodePoint = function() {
  16339. var ch = this.input.charCodeAt(this.pos), code;
  16340. if (ch === 123) { // '{'
  16341. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  16342. var codePos = ++this.pos;
  16343. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  16344. ++this.pos;
  16345. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  16346. } else {
  16347. code = this.readHexChar(4);
  16348. }
  16349. return code
  16350. };
  16351. function codePointToString$1(code) {
  16352. // UTF-16 Decoding
  16353. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  16354. code -= 0x10000;
  16355. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  16356. }
  16357. pp$9.readString = function(quote) {
  16358. var out = "", chunkStart = ++this.pos;
  16359. for (;;) {
  16360. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  16361. var ch = this.input.charCodeAt(this.pos);
  16362. if (ch === quote) { break }
  16363. if (ch === 92) { // '\'
  16364. out += this.input.slice(chunkStart, this.pos);
  16365. out += this.readEscapedChar(false);
  16366. chunkStart = this.pos;
  16367. } else {
  16368. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  16369. ++this.pos;
  16370. }
  16371. }
  16372. out += this.input.slice(chunkStart, this.pos++);
  16373. return this.finishToken(types.string, out)
  16374. };
  16375. // Reads template string tokens.
  16376. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  16377. pp$9.tryReadTemplateToken = function() {
  16378. this.inTemplateElement = true;
  16379. try {
  16380. this.readTmplToken();
  16381. } catch (err) {
  16382. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  16383. this.readInvalidTemplateToken();
  16384. } else {
  16385. throw err
  16386. }
  16387. }
  16388. this.inTemplateElement = false;
  16389. };
  16390. pp$9.invalidStringToken = function(position, message) {
  16391. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  16392. throw INVALID_TEMPLATE_ESCAPE_ERROR
  16393. } else {
  16394. this.raise(position, message);
  16395. }
  16396. };
  16397. pp$9.readTmplToken = function() {
  16398. var out = "", chunkStart = this.pos;
  16399. for (;;) {
  16400. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  16401. var ch = this.input.charCodeAt(this.pos);
  16402. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  16403. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  16404. if (ch === 36) {
  16405. this.pos += 2;
  16406. return this.finishToken(types.dollarBraceL)
  16407. } else {
  16408. ++this.pos;
  16409. return this.finishToken(types.backQuote)
  16410. }
  16411. }
  16412. out += this.input.slice(chunkStart, this.pos);
  16413. return this.finishToken(types.template, out)
  16414. }
  16415. if (ch === 92) { // '\'
  16416. out += this.input.slice(chunkStart, this.pos);
  16417. out += this.readEscapedChar(true);
  16418. chunkStart = this.pos;
  16419. } else if (isNewLine(ch)) {
  16420. out += this.input.slice(chunkStart, this.pos);
  16421. ++this.pos;
  16422. switch (ch) {
  16423. case 13:
  16424. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  16425. case 10:
  16426. out += "\n";
  16427. break
  16428. default:
  16429. out += String.fromCharCode(ch);
  16430. break
  16431. }
  16432. if (this.options.locations) {
  16433. ++this.curLine;
  16434. this.lineStart = this.pos;
  16435. }
  16436. chunkStart = this.pos;
  16437. } else {
  16438. ++this.pos;
  16439. }
  16440. }
  16441. };
  16442. // Reads a template token to search for the end, without validating any escape sequences
  16443. pp$9.readInvalidTemplateToken = function() {
  16444. for (; this.pos < this.input.length; this.pos++) {
  16445. switch (this.input[this.pos]) {
  16446. case "\\":
  16447. ++this.pos;
  16448. break
  16449. case "$":
  16450. if (this.input[this.pos + 1] !== "{") {
  16451. break
  16452. }
  16453. // falls through
  16454. case "`":
  16455. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  16456. // no default
  16457. }
  16458. }
  16459. this.raise(this.start, "Unterminated template");
  16460. };
  16461. // Used to read escaped characters
  16462. pp$9.readEscapedChar = function(inTemplate) {
  16463. var ch = this.input.charCodeAt(++this.pos);
  16464. ++this.pos;
  16465. switch (ch) {
  16466. case 110: return "\n" // 'n' -> '\n'
  16467. case 114: return "\r" // 'r' -> '\r'
  16468. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  16469. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  16470. case 116: return "\t" // 't' -> '\t'
  16471. case 98: return "\b" // 'b' -> '\b'
  16472. case 118: return "\u000b" // 'v' -> '\u000b'
  16473. case 102: return "\f" // 'f' -> '\f'
  16474. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  16475. case 10: // ' \n'
  16476. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  16477. return ""
  16478. case 56:
  16479. case 57:
  16480. if (this.strict) {
  16481. this.invalidStringToken(
  16482. this.pos - 1,
  16483. "Invalid escape sequence"
  16484. );
  16485. }
  16486. if (inTemplate) {
  16487. var codePos = this.pos - 1;
  16488. this.invalidStringToken(
  16489. codePos,
  16490. "Invalid escape sequence in template string"
  16491. );
  16492. return null
  16493. }
  16494. default:
  16495. if (ch >= 48 && ch <= 55) {
  16496. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  16497. var octal = parseInt(octalStr, 8);
  16498. if (octal > 255) {
  16499. octalStr = octalStr.slice(0, -1);
  16500. octal = parseInt(octalStr, 8);
  16501. }
  16502. this.pos += octalStr.length - 1;
  16503. ch = this.input.charCodeAt(this.pos);
  16504. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  16505. this.invalidStringToken(
  16506. this.pos - 1 - octalStr.length,
  16507. inTemplate
  16508. ? "Octal literal in template string"
  16509. : "Octal literal in strict mode"
  16510. );
  16511. }
  16512. return String.fromCharCode(octal)
  16513. }
  16514. if (isNewLine(ch)) {
  16515. // Unicode new line characters after \ get removed from output in both
  16516. // template literals and strings
  16517. return ""
  16518. }
  16519. return String.fromCharCode(ch)
  16520. }
  16521. };
  16522. // Used to read character escape sequences ('\x', '\u', '\U').
  16523. pp$9.readHexChar = function(len) {
  16524. var codePos = this.pos;
  16525. var n = this.readInt(16, len);
  16526. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  16527. return n
  16528. };
  16529. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  16530. // to whether the word contained a '\u' escape.
  16531. //
  16532. // Incrementally adds only escaped chars, adding other chunks as-is
  16533. // as a micro-optimization.
  16534. pp$9.readWord1 = function() {
  16535. this.containsEsc = false;
  16536. var word = "", first = true, chunkStart = this.pos;
  16537. var astral = this.options.ecmaVersion >= 6;
  16538. while (this.pos < this.input.length) {
  16539. var ch = this.fullCharCodeAtPos();
  16540. if (isIdentifierChar(ch, astral)) {
  16541. this.pos += ch <= 0xffff ? 1 : 2;
  16542. } else if (ch === 92) { // "\"
  16543. this.containsEsc = true;
  16544. word += this.input.slice(chunkStart, this.pos);
  16545. var escStart = this.pos;
  16546. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  16547. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  16548. ++this.pos;
  16549. var esc = this.readCodePoint();
  16550. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  16551. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  16552. word += codePointToString$1(esc);
  16553. chunkStart = this.pos;
  16554. } else {
  16555. break
  16556. }
  16557. first = false;
  16558. }
  16559. return word + this.input.slice(chunkStart, this.pos)
  16560. };
  16561. // Read an identifier or keyword token. Will check for reserved
  16562. // words when necessary.
  16563. pp$9.readWord = function() {
  16564. var word = this.readWord1();
  16565. var type = types.name;
  16566. if (this.keywords.test(word)) {
  16567. type = keywords$1[word];
  16568. }
  16569. return this.finishToken(type, word)
  16570. };
  16571. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  16572. var version$1 = "8.0.3";
  16573. Parser.acorn = {
  16574. Parser: Parser,
  16575. version: version$1,
  16576. defaultOptions: defaultOptions,
  16577. Position: Position,
  16578. SourceLocation: SourceLocation,
  16579. getLineInfo: getLineInfo,
  16580. Node: Node,
  16581. TokenType: TokenType,
  16582. tokTypes: types,
  16583. keywordTypes: keywords$1,
  16584. TokContext: TokContext,
  16585. tokContexts: types$1,
  16586. isIdentifierChar: isIdentifierChar,
  16587. isIdentifierStart: isIdentifierStart,
  16588. Token: Token,
  16589. isNewLine: isNewLine,
  16590. lineBreak: lineBreak,
  16591. lineBreakG: lineBreakG,
  16592. nonASCIIwhitespace: nonASCIIwhitespace
  16593. };
  16594. // The main exported interface (under `self.acorn` when in the
  16595. // browser) is a `parse` function that takes a code string and
  16596. // returns an abstract syntax tree as specified by [Mozilla parser
  16597. // API][api].
  16598. //
  16599. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  16600. function parse(input, options) {
  16601. return Parser.parse(input, options)
  16602. }
  16603. // This function tries to parse a single expression at a given
  16604. // offset in a string. Useful for parsing mixed-language formats
  16605. // that embed JavaScript expressions.
  16606. function parseExpressionAt(input, pos, options) {
  16607. return Parser.parseExpressionAt(input, pos, options)
  16608. }
  16609. // Acorn is organized as a tokenizer and a recursive-descent parser.
  16610. // The `tokenizer` export provides an interface to the tokenizer.
  16611. function tokenizer(input, options) {
  16612. return Parser.tokenizer(input, options)
  16613. }
  16614. var acorn = {
  16615. __proto__: null,
  16616. Node: Node,
  16617. Parser: Parser,
  16618. Position: Position,
  16619. SourceLocation: SourceLocation,
  16620. TokContext: TokContext,
  16621. Token: Token,
  16622. TokenType: TokenType,
  16623. defaultOptions: defaultOptions,
  16624. getLineInfo: getLineInfo,
  16625. isIdentifierChar: isIdentifierChar,
  16626. isIdentifierStart: isIdentifierStart,
  16627. isNewLine: isNewLine,
  16628. keywordTypes: keywords$1,
  16629. lineBreak: lineBreak,
  16630. lineBreakG: lineBreakG,
  16631. nonASCIIwhitespace: nonASCIIwhitespace,
  16632. parse: parse,
  16633. parseExpressionAt: parseExpressionAt,
  16634. tokContexts: types$1,
  16635. tokTypes: types,
  16636. tokenizer: tokenizer,
  16637. version: version$1
  16638. };
  16639. class GlobalScope extends Scope {
  16640. constructor() {
  16641. super();
  16642. this.variables.set('undefined', new UndefinedVariable());
  16643. }
  16644. findVariable(name) {
  16645. let variable = this.variables.get(name);
  16646. if (!variable) {
  16647. variable = new GlobalVariable(name);
  16648. this.variables.set(name, variable);
  16649. }
  16650. return variable;
  16651. }
  16652. }
  16653. const readFile = (file) => new Promise((fulfil, reject) => readFile$1(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
  16654. function mkdirpath(path) {
  16655. const dir = dirname(path);
  16656. try {
  16657. readdirSync(dir);
  16658. }
  16659. catch (err) {
  16660. mkdirpath(dir);
  16661. try {
  16662. mkdirSync(dir);
  16663. }
  16664. catch (err2) {
  16665. if (err2.code !== 'EEXIST') {
  16666. throw err2;
  16667. }
  16668. }
  16669. }
  16670. }
  16671. function writeFile(dest, data) {
  16672. return new Promise((fulfil, reject) => {
  16673. mkdirpath(dest);
  16674. writeFile$1(dest, data, err => {
  16675. if (err) {
  16676. reject(err);
  16677. }
  16678. else {
  16679. fulfil();
  16680. }
  16681. });
  16682. });
  16683. }
  16684. async function resolveId(source, importer, preserveSymlinks, pluginDriver, skip, customOptions) {
  16685. const pluginResult = await pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], null, skip);
  16686. if (pluginResult != null)
  16687. return pluginResult;
  16688. // external modules (non-entry modules that start with neither '.' or '/')
  16689. // are skipped at this stage.
  16690. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  16691. return null;
  16692. // `resolve` processes paths from right to left, prepending them until an
  16693. // absolute path is created. Absolute importees therefore shortcircuit the
  16694. // resolve call and require no special handing on our part.
  16695. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  16696. return addJsExtensionIfNecessary(resolve(importer ? dirname(importer) : resolve(), source), preserveSymlinks);
  16697. }
  16698. function addJsExtensionIfNecessary(file, preserveSymlinks) {
  16699. let found = findFile(file, preserveSymlinks);
  16700. if (found)
  16701. return found;
  16702. found = findFile(file + '.mjs', preserveSymlinks);
  16703. if (found)
  16704. return found;
  16705. found = findFile(file + '.js', preserveSymlinks);
  16706. return found;
  16707. }
  16708. function findFile(file, preserveSymlinks) {
  16709. try {
  16710. const stats = lstatSync(file);
  16711. if (!preserveSymlinks && stats.isSymbolicLink())
  16712. return findFile(realpathSync(file), preserveSymlinks);
  16713. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  16714. // check case
  16715. const name = basename(file);
  16716. const files = readdirSync(dirname(file));
  16717. if (files.indexOf(name) !== -1)
  16718. return file;
  16719. }
  16720. }
  16721. catch (_a) {
  16722. // suppress
  16723. }
  16724. }
  16725. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  16726. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  16727. function throwPluginError(err, plugin, { hook, id } = {}) {
  16728. if (typeof err === 'string')
  16729. err = { message: err };
  16730. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  16731. err.pluginCode = err.code;
  16732. }
  16733. err.code = Errors.PLUGIN_ERROR;
  16734. err.plugin = plugin;
  16735. if (hook) {
  16736. err.hook = hook;
  16737. }
  16738. if (id) {
  16739. err.id = id;
  16740. }
  16741. return error(err);
  16742. }
  16743. const deprecatedHooks = [
  16744. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  16745. ];
  16746. function warnDeprecatedHooks(plugins, options) {
  16747. for (const { active, deprecated, replacement } of deprecatedHooks) {
  16748. for (const plugin of plugins) {
  16749. if (deprecated in plugin) {
  16750. warnDeprecation({
  16751. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  16752. plugin: plugin.name
  16753. }, active, options);
  16754. }
  16755. }
  16756. }
  16757. }
  16758. function createPluginCache(cache) {
  16759. return {
  16760. has(id) {
  16761. const item = cache[id];
  16762. if (!item)
  16763. return false;
  16764. item[0] = 0;
  16765. return true;
  16766. },
  16767. get(id) {
  16768. const item = cache[id];
  16769. if (!item)
  16770. return undefined;
  16771. item[0] = 0;
  16772. return item[1];
  16773. },
  16774. set(id, value) {
  16775. cache[id] = [0, value];
  16776. },
  16777. delete(id) {
  16778. return delete cache[id];
  16779. }
  16780. };
  16781. }
  16782. function getTrackedPluginCache(pluginCache, onUse) {
  16783. return {
  16784. has(id) {
  16785. onUse();
  16786. return pluginCache.has(id);
  16787. },
  16788. get(id) {
  16789. onUse();
  16790. return pluginCache.get(id);
  16791. },
  16792. set(id, value) {
  16793. onUse();
  16794. return pluginCache.set(id, value);
  16795. },
  16796. delete(id) {
  16797. onUse();
  16798. return pluginCache.delete(id);
  16799. }
  16800. };
  16801. }
  16802. const NO_CACHE = {
  16803. has() {
  16804. return false;
  16805. },
  16806. get() {
  16807. return undefined;
  16808. },
  16809. set() { },
  16810. delete() {
  16811. return false;
  16812. }
  16813. };
  16814. function uncacheablePluginError(pluginName) {
  16815. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  16816. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  16817. return error({
  16818. code: 'ANONYMOUS_PLUGIN_CACHE',
  16819. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  16820. });
  16821. }
  16822. return error({
  16823. code: 'DUPLICATE_PLUGIN_NAME',
  16824. 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).`
  16825. });
  16826. }
  16827. function getCacheForUncacheablePlugin(pluginName) {
  16828. return {
  16829. has() {
  16830. return uncacheablePluginError(pluginName);
  16831. },
  16832. get() {
  16833. return uncacheablePluginError(pluginName);
  16834. },
  16835. set() {
  16836. return uncacheablePluginError(pluginName);
  16837. },
  16838. delete() {
  16839. return uncacheablePluginError(pluginName);
  16840. }
  16841. };
  16842. }
  16843. function transform(source, module, pluginDriver, warn) {
  16844. const id = module.id;
  16845. const sourcemapChain = [];
  16846. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  16847. const originalCode = source.code;
  16848. let ast = source.ast;
  16849. const transformDependencies = [];
  16850. const emittedFiles = [];
  16851. let customTransformCache = false;
  16852. const useCustomTransformCache = () => (customTransformCache = true);
  16853. let curPlugin;
  16854. const curSource = source.code;
  16855. function transformReducer(previousCode, result, plugin) {
  16856. let code;
  16857. let map;
  16858. if (typeof result === 'string') {
  16859. code = result;
  16860. }
  16861. else if (result && typeof result === 'object') {
  16862. module.updateOptions(result);
  16863. if (result.code == null) {
  16864. if (result.map || result.ast) {
  16865. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  16866. }
  16867. return previousCode;
  16868. }
  16869. ({ code, map, ast } = result);
  16870. }
  16871. else {
  16872. return previousCode;
  16873. }
  16874. // strict null check allows 'null' maps to not be pushed to the chain,
  16875. // while 'undefined' gets the missing map warning
  16876. if (map !== null) {
  16877. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  16878. missing: true,
  16879. plugin: plugin.name
  16880. });
  16881. }
  16882. return code;
  16883. }
  16884. return pluginDriver
  16885. .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  16886. curPlugin = plugin;
  16887. return {
  16888. ...pluginContext,
  16889. cache: customTransformCache
  16890. ? pluginContext.cache
  16891. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  16892. warn(warning, pos) {
  16893. if (typeof warning === 'string')
  16894. warning = { message: warning };
  16895. if (pos)
  16896. augmentCodeLocation(warning, pos, curSource, id);
  16897. warning.id = id;
  16898. warning.hook = 'transform';
  16899. pluginContext.warn(warning);
  16900. },
  16901. error(err, pos) {
  16902. if (typeof err === 'string')
  16903. err = { message: err };
  16904. if (pos)
  16905. augmentCodeLocation(err, pos, curSource, id);
  16906. err.id = id;
  16907. err.hook = 'transform';
  16908. return pluginContext.error(err);
  16909. },
  16910. emitAsset(name, source) {
  16911. emittedFiles.push({ type: 'asset', name, source });
  16912. return pluginContext.emitAsset(name, source);
  16913. },
  16914. emitChunk(id, options) {
  16915. emittedFiles.push({ type: 'chunk', id, name: options && options.name });
  16916. return pluginContext.emitChunk(id, options);
  16917. },
  16918. emitFile(emittedFile) {
  16919. emittedFiles.push(emittedFile);
  16920. return pluginDriver.emitFile(emittedFile);
  16921. },
  16922. addWatchFile(id) {
  16923. transformDependencies.push(id);
  16924. pluginContext.addWatchFile(id);
  16925. },
  16926. setAssetSource() {
  16927. return this.error({
  16928. code: 'INVALID_SETASSETSOURCE',
  16929. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  16930. });
  16931. },
  16932. getCombinedSourcemap() {
  16933. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  16934. if (!combinedMap) {
  16935. const magicString = new MagicString(originalCode);
  16936. return magicString.generateMap({ includeContent: true, hires: true, source: id });
  16937. }
  16938. if (originalSourcemap !== combinedMap) {
  16939. originalSourcemap = combinedMap;
  16940. sourcemapChain.length = 0;
  16941. }
  16942. return new SourceMap({
  16943. ...combinedMap,
  16944. file: null,
  16945. sourcesContent: combinedMap.sourcesContent
  16946. });
  16947. }
  16948. };
  16949. })
  16950. .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
  16951. .then(code => {
  16952. if (!customTransformCache) {
  16953. // files emitted by a transform hook need to be emitted again if the hook is skipped
  16954. if (emittedFiles.length)
  16955. module.transformFiles = emittedFiles;
  16956. }
  16957. return {
  16958. ast,
  16959. code,
  16960. customTransformCache,
  16961. meta: module.info.meta,
  16962. originalCode,
  16963. originalSourcemap,
  16964. sourcemapChain,
  16965. transformDependencies
  16966. };
  16967. });
  16968. }
  16969. class ModuleLoader {
  16970. constructor(graph, modulesById, options, pluginDriver) {
  16971. this.graph = graph;
  16972. this.modulesById = modulesById;
  16973. this.options = options;
  16974. this.pluginDriver = pluginDriver;
  16975. this.implicitEntryModules = new Set();
  16976. this.indexedEntryModules = [];
  16977. this.latestLoadModulesPromise = Promise.resolve();
  16978. this.nextEntryModuleIndex = 0;
  16979. this.hasModuleSideEffects = options.treeshake
  16980. ? options.treeshake.moduleSideEffects
  16981. : () => true;
  16982. }
  16983. async addAdditionalModules(unresolvedModules) {
  16984. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  16985. await this.awaitLoadModulesPromise();
  16986. return result;
  16987. }
  16988. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  16989. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  16990. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  16991. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  16992. let moduleIndex = firstEntryModuleIndex;
  16993. for (let index = 0; index < entryModules.length; index++) {
  16994. const entryModule = entryModules[index];
  16995. entryModule.isUserDefinedEntryPoint =
  16996. entryModule.isUserDefinedEntryPoint || isUserDefined;
  16997. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
  16998. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  16999. if (!existingIndexedModule) {
  17000. this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
  17001. }
  17002. else {
  17003. existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
  17004. }
  17005. moduleIndex++;
  17006. }
  17007. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  17008. return entryModules;
  17009. }));
  17010. await this.awaitLoadModulesPromise();
  17011. return {
  17012. entryModules: this.indexedEntryModules.map(({ module }) => module),
  17013. implicitEntryModules: [...this.implicitEntryModules],
  17014. newEntryModules
  17015. };
  17016. }
  17017. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  17018. const unresolvedModule = {
  17019. fileName: fileName || null,
  17020. id,
  17021. importer,
  17022. name: name || null
  17023. };
  17024. const module = implicitlyLoadedAfterOneOf
  17025. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  17026. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  17027. if (preserveSignature != null) {
  17028. module.preserveSignature = preserveSignature;
  17029. }
  17030. return module;
  17031. }
  17032. async resolveId(source, importer, customOptions, skip = null) {
  17033. return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  17034. ? false
  17035. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, skip, customOptions), importer, source));
  17036. }
  17037. addDefaultsToResolvedId(resolvedId) {
  17038. var _a, _b;
  17039. if (!resolvedId) {
  17040. return null;
  17041. }
  17042. const external = resolvedId.external || false;
  17043. return {
  17044. external,
  17045. id: resolvedId.id,
  17046. meta: resolvedId.meta || EMPTY_OBJECT,
  17047. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, external),
  17048. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  17049. };
  17050. }
  17051. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  17052. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  17053. addChunkNamesToModule(entryModule, unresolvedModule, false);
  17054. if (!entryModule.info.isEntry) {
  17055. this.implicitEntryModules.add(entryModule);
  17056. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  17057. for (const module of implicitlyLoadedAfterModules) {
  17058. entryModule.implicitlyLoadedAfter.add(module);
  17059. }
  17060. for (const dependant of entryModule.implicitlyLoadedAfter) {
  17061. dependant.implicitlyLoadedBefore.add(entryModule);
  17062. }
  17063. }
  17064. return entryModule;
  17065. }));
  17066. }
  17067. async addModuleSource(id, importer, module) {
  17068. var _a;
  17069. timeStart('load modules', 3);
  17070. let source;
  17071. try {
  17072. source = (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id));
  17073. }
  17074. catch (err) {
  17075. timeEnd('load modules', 3);
  17076. let msg = `Could not load ${id}`;
  17077. if (importer)
  17078. msg += ` (imported by ${relativeId(importer)})`;
  17079. msg += `: ${err.message}`;
  17080. err.message = msg;
  17081. throw err;
  17082. }
  17083. timeEnd('load modules', 3);
  17084. const sourceDescription = typeof source === 'string'
  17085. ? { code: source }
  17086. : typeof source === 'object' && typeof source.code === 'string'
  17087. ? source
  17088. : error(errBadLoader(id));
  17089. const cachedModule = this.graph.cachedModules.get(id);
  17090. if (cachedModule &&
  17091. !cachedModule.customTransformCache &&
  17092. cachedModule.originalCode === sourceDescription.code) {
  17093. if (cachedModule.transformFiles) {
  17094. for (const emittedFile of cachedModule.transformFiles)
  17095. this.pluginDriver.emitFile(emittedFile);
  17096. }
  17097. module.setSource(cachedModule);
  17098. }
  17099. else {
  17100. module.updateOptions(sourceDescription);
  17101. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  17102. }
  17103. }
  17104. async awaitLoadModulesPromise() {
  17105. let startingPromise;
  17106. do {
  17107. startingPromise = this.latestLoadModulesPromise;
  17108. await startingPromise;
  17109. } while (startingPromise !== this.latestLoadModulesPromise);
  17110. }
  17111. extendLoadModulesPromise(loadNewModulesPromise) {
  17112. this.latestLoadModulesPromise = Promise.all([
  17113. loadNewModulesPromise,
  17114. this.latestLoadModulesPromise
  17115. ]);
  17116. this.latestLoadModulesPromise.catch(() => {
  17117. /* Avoid unhandled Promise rejections */
  17118. });
  17119. return loadNewModulesPromise;
  17120. }
  17121. async fetchDynamicDependencies(module) {
  17122. const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
  17123. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  17124. ? dynamicImport.argument
  17125. : dynamicImport.argument.esTreeNode, module.id);
  17126. if (resolvedId === null)
  17127. return null;
  17128. if (typeof resolvedId === 'string') {
  17129. dynamicImport.resolution = resolvedId;
  17130. return null;
  17131. }
  17132. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  17133. }));
  17134. for (const dependency of dependencies) {
  17135. if (dependency) {
  17136. module.dynamicDependencies.add(dependency);
  17137. dependency.dynamicImporters.push(module.id);
  17138. }
  17139. }
  17140. }
  17141. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
  17142. const existingModule = this.modulesById.get(id);
  17143. if (existingModule instanceof Module) {
  17144. if (isEntry) {
  17145. existingModule.info.isEntry = true;
  17146. this.implicitEntryModules.delete(existingModule);
  17147. for (const dependant of existingModule.implicitlyLoadedAfter) {
  17148. dependant.implicitlyLoadedBefore.delete(existingModule);
  17149. }
  17150. existingModule.implicitlyLoadedAfter.clear();
  17151. }
  17152. return existingModule;
  17153. }
  17154. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  17155. this.modulesById.set(id, module);
  17156. this.graph.watchFiles[id] = true;
  17157. await this.addModuleSource(id, importer, module);
  17158. await this.pluginDriver.hookParallel('moduleParsed', [module.info]);
  17159. await Promise.all([
  17160. this.fetchStaticDependencies(module),
  17161. this.fetchDynamicDependencies(module)
  17162. ]);
  17163. module.linkImports();
  17164. return module;
  17165. }
  17166. fetchResolvedDependency(source, importer, resolvedId) {
  17167. if (resolvedId.external) {
  17168. if (!this.modulesById.has(resolvedId.id)) {
  17169. this.modulesById.set(resolvedId.id, new ExternalModule(this.options, resolvedId.id, resolvedId.moduleSideEffects, resolvedId.meta));
  17170. }
  17171. const externalModule = this.modulesById.get(resolvedId.id);
  17172. if (!(externalModule instanceof ExternalModule)) {
  17173. return error(errInternalIdCannotBeExternal(source, importer));
  17174. }
  17175. return Promise.resolve(externalModule);
  17176. }
  17177. else {
  17178. return this.fetchModule(resolvedId, importer, false);
  17179. }
  17180. }
  17181. async fetchStaticDependencies(module) {
  17182. for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
  17183. module.resolvedIds[source] ||
  17184. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
  17185. module.dependencies.add(dependency);
  17186. dependency.importers.push(module.id);
  17187. }
  17188. }
  17189. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  17190. if (resolveIdResult) {
  17191. if (typeof resolveIdResult === 'object') {
  17192. return {
  17193. ...resolveIdResult,
  17194. external: resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true)
  17195. };
  17196. }
  17197. const external = this.options.external(resolveIdResult, importer, true);
  17198. return {
  17199. external,
  17200. id: external ? normalizeRelativeExternalId(resolveIdResult, importer) : resolveIdResult
  17201. };
  17202. }
  17203. const id = normalizeRelativeExternalId(source, importer);
  17204. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  17205. return null;
  17206. }
  17207. return {
  17208. external: true,
  17209. id
  17210. };
  17211. }
  17212. handleResolveId(resolvedId, source, importer) {
  17213. if (resolvedId === null) {
  17214. if (isRelative(source)) {
  17215. return error(errUnresolvedImport(source, importer));
  17216. }
  17217. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  17218. return {
  17219. external: true,
  17220. id: source,
  17221. meta: EMPTY_OBJECT,
  17222. moduleSideEffects: this.hasModuleSideEffects(source, true),
  17223. syntheticNamedExports: false
  17224. };
  17225. }
  17226. else {
  17227. if (resolvedId.external && resolvedId.syntheticNamedExports) {
  17228. this.options.onwarn(errExternalSyntheticExports(source, importer));
  17229. }
  17230. }
  17231. return resolvedId;
  17232. }
  17233. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  17234. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, null, EMPTY_OBJECT);
  17235. if (resolveIdResult == null) {
  17236. return error(implicitlyLoadedBefore === null
  17237. ? errUnresolvedEntry(unresolvedId)
  17238. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  17239. }
  17240. if (resolveIdResult === false ||
  17241. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  17242. return error(implicitlyLoadedBefore === null
  17243. ? errEntryCannotBeExternal(unresolvedId)
  17244. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  17245. }
  17246. return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object' ? resolveIdResult : { id: resolveIdResult }), undefined, isEntry);
  17247. }
  17248. async resolveDynamicImport(module, specifier, importer) {
  17249. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  17250. specifier,
  17251. importer
  17252. ]);
  17253. if (typeof specifier !== 'string') {
  17254. if (typeof resolution === 'string') {
  17255. return resolution;
  17256. }
  17257. if (!resolution) {
  17258. return null;
  17259. }
  17260. return {
  17261. external: false,
  17262. moduleSideEffects: true,
  17263. ...resolution
  17264. };
  17265. }
  17266. if (resolution == null) {
  17267. return (module.resolvedIds[specifier] =
  17268. module.resolvedIds[specifier] ||
  17269. this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
  17270. }
  17271. return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  17272. }
  17273. }
  17274. function normalizeRelativeExternalId(source, importer) {
  17275. return isRelative(source)
  17276. ? importer
  17277. ? resolve(importer, '..', source)
  17278. : resolve(source)
  17279. : source;
  17280. }
  17281. function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
  17282. if (fileName !== null) {
  17283. module.chunkFileNames.add(fileName);
  17284. }
  17285. else if (name !== null) {
  17286. if (module.chunkName === null) {
  17287. module.chunkName = name;
  17288. }
  17289. if (isUserDefined) {
  17290. module.userChunkNames.add(name);
  17291. }
  17292. }
  17293. }
  17294. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  17295. let deprecationWarningShown = false;
  17296. return ((...args) => {
  17297. if (!deprecationWarningShown) {
  17298. deprecationWarningShown = true;
  17299. warnDeprecation({
  17300. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  17301. plugin: pluginName
  17302. }, activeDeprecation, options);
  17303. }
  17304. return handler(...args);
  17305. });
  17306. }
  17307. function getPluginContexts(pluginCache, graph, options, fileEmitter) {
  17308. const existingPluginNames = new Set();
  17309. return (plugin, pidx) => {
  17310. let cacheable = true;
  17311. if (typeof plugin.cacheKey !== 'string') {
  17312. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  17313. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  17314. existingPluginNames.has(plugin.name)) {
  17315. cacheable = false;
  17316. }
  17317. else {
  17318. existingPluginNames.add(plugin.name);
  17319. }
  17320. }
  17321. let cacheInstance;
  17322. if (!pluginCache) {
  17323. cacheInstance = NO_CACHE;
  17324. }
  17325. else if (cacheable) {
  17326. const cacheKey = plugin.cacheKey || plugin.name;
  17327. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  17328. }
  17329. else {
  17330. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  17331. }
  17332. const context = {
  17333. addWatchFile(id) {
  17334. if (graph.phase >= BuildPhase.GENERATE) {
  17335. return this.error(errInvalidRollupPhaseForAddWatchFile());
  17336. }
  17337. graph.watchFiles[id] = true;
  17338. },
  17339. cache: cacheInstance,
  17340. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, true, options),
  17341. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, true, options),
  17342. emitFile: fileEmitter.emitFile,
  17343. error(err) {
  17344. return throwPluginError(err, plugin.name);
  17345. },
  17346. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  17347. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  17348. getFileName: fileEmitter.getFileName,
  17349. getModuleIds: () => graph.modulesById.keys(),
  17350. getModuleInfo: graph.getModuleInfo,
  17351. getWatchFiles: () => Object.keys(graph.watchFiles),
  17352. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  17353. meta: {
  17354. rollupVersion: version,
  17355. watchMode: graph.watchMode
  17356. },
  17357. get moduleIds() {
  17358. function* wrappedModuleIds() {
  17359. warnDeprecation({
  17360. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  17361. plugin: plugin.name
  17362. }, false, options);
  17363. yield* moduleIds;
  17364. }
  17365. const moduleIds = graph.modulesById.keys();
  17366. return wrappedModuleIds();
  17367. },
  17368. parse: graph.contextParse,
  17369. resolve(source, importer, { custom, skipSelf } = BLANK) {
  17370. return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null);
  17371. },
  17372. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  17373. .resolveId(source, importer, BLANK)
  17374. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  17375. setAssetSource: fileEmitter.setAssetSource,
  17376. warn(warning) {
  17377. if (typeof warning === 'string')
  17378. warning = { message: warning };
  17379. if (warning.code)
  17380. warning.pluginCode = warning.code;
  17381. warning.code = 'PLUGIN_WARNING';
  17382. warning.plugin = plugin.name;
  17383. options.onwarn(warning);
  17384. }
  17385. };
  17386. return context;
  17387. };
  17388. }
  17389. const inputHookNames = {
  17390. buildEnd: 1,
  17391. buildStart: 1,
  17392. closeWatcher: 1,
  17393. load: 1,
  17394. moduleParsed: 1,
  17395. options: 1,
  17396. resolveDynamicImport: 1,
  17397. resolveId: 1,
  17398. transform: 1,
  17399. watchChange: 1
  17400. };
  17401. const inputHooks = Object.keys(inputHookNames);
  17402. function throwInvalidHookError(hookName, pluginName) {
  17403. return error({
  17404. code: 'INVALID_PLUGIN_HOOK',
  17405. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  17406. });
  17407. }
  17408. class PluginDriver {
  17409. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  17410. this.graph = graph;
  17411. this.options = options;
  17412. warnDeprecatedHooks(userPlugins, options);
  17413. this.pluginCache = pluginCache;
  17414. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  17415. this.emitFile = this.fileEmitter.emitFile;
  17416. this.getFileName = this.fileEmitter.getFileName;
  17417. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
  17418. this.setOutputBundle = this.fileEmitter.setOutputBundle;
  17419. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  17420. this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, options, this.fileEmitter));
  17421. if (basePluginDriver) {
  17422. for (const plugin of userPlugins) {
  17423. for (const hook of inputHooks) {
  17424. if (hook in plugin) {
  17425. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  17426. }
  17427. }
  17428. }
  17429. }
  17430. }
  17431. createOutputPluginDriver(plugins) {
  17432. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  17433. }
  17434. // chains, first non-null result stops and returns
  17435. hookFirst(hookName, args, replaceContext, skip) {
  17436. let promise = Promise.resolve(undefined);
  17437. for (let i = 0; i < this.plugins.length; i++) {
  17438. if (skip === i)
  17439. continue;
  17440. promise = promise.then(result => {
  17441. if (result != null)
  17442. return result;
  17443. return this.runHook(hookName, args, i, false, replaceContext);
  17444. });
  17445. }
  17446. return promise;
  17447. }
  17448. // chains synchronously, first non-null result stops and returns
  17449. hookFirstSync(hookName, args, replaceContext) {
  17450. for (let i = 0; i < this.plugins.length; i++) {
  17451. const result = this.runHookSync(hookName, args, i, replaceContext);
  17452. if (result != null)
  17453. return result;
  17454. }
  17455. return null;
  17456. }
  17457. // parallel, ignores returns
  17458. hookParallel(hookName, args, replaceContext) {
  17459. const promises = [];
  17460. for (let i = 0; i < this.plugins.length; i++) {
  17461. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  17462. if (!hookPromise)
  17463. continue;
  17464. promises.push(hookPromise);
  17465. }
  17466. return Promise.all(promises).then(() => { });
  17467. }
  17468. // chains, reduces returned value, handling the reduced value as the first hook argument
  17469. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  17470. let promise = Promise.resolve(arg0);
  17471. for (let i = 0; i < this.plugins.length; i++) {
  17472. promise = promise.then(arg0 => {
  17473. const args = [arg0, ...rest];
  17474. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  17475. if (!hookPromise)
  17476. return arg0;
  17477. return hookPromise.then(result => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
  17478. });
  17479. }
  17480. return promise;
  17481. }
  17482. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  17483. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  17484. for (let i = 0; i < this.plugins.length; i++) {
  17485. const args = [arg0, ...rest];
  17486. const result = this.runHookSync(hookName, args, i, replaceContext);
  17487. arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
  17488. }
  17489. return arg0;
  17490. }
  17491. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  17492. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  17493. let promise = Promise.resolve(initialValue);
  17494. for (let i = 0; i < this.plugins.length; i++) {
  17495. promise = promise.then(value => {
  17496. const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
  17497. if (!hookPromise)
  17498. return value;
  17499. return hookPromise.then(result => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
  17500. });
  17501. }
  17502. return promise;
  17503. }
  17504. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  17505. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  17506. let acc = initialValue;
  17507. for (let i = 0; i < this.plugins.length; i++) {
  17508. const result = this.runHookSync(hookName, args, i, replaceContext);
  17509. acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
  17510. }
  17511. return acc;
  17512. }
  17513. // chains, ignores returns
  17514. hookSeq(hookName, args, replaceContext) {
  17515. let promise = Promise.resolve();
  17516. for (let i = 0; i < this.plugins.length; i++) {
  17517. promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
  17518. }
  17519. return promise;
  17520. }
  17521. // chains synchronously, ignores returns
  17522. hookSeqSync(hookName, args, replaceContext) {
  17523. for (let i = 0; i < this.plugins.length; i++) {
  17524. this.runHookSync(hookName, args, i, replaceContext);
  17525. }
  17526. }
  17527. runHook(hookName, args, pluginIndex, permitValues, hookContext) {
  17528. const plugin = this.plugins[pluginIndex];
  17529. const hook = plugin[hookName];
  17530. if (!hook)
  17531. return undefined;
  17532. let context = this.pluginContexts[pluginIndex];
  17533. if (hookContext) {
  17534. context = hookContext(context, plugin);
  17535. }
  17536. return Promise.resolve()
  17537. .then(() => {
  17538. // permit values allows values to be returned instead of a functional hook
  17539. if (typeof hook !== 'function') {
  17540. if (permitValues)
  17541. return hook;
  17542. return throwInvalidHookError(hookName, plugin.name);
  17543. }
  17544. return hook.apply(context, args);
  17545. })
  17546. .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
  17547. }
  17548. /**
  17549. * Run a sync plugin hook and return the result.
  17550. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  17551. * @param args Arguments passed to the plugin hook.
  17552. * @param pluginIndex Index of the plugin inside `this.plugins[]`.
  17553. * @param hookContext When passed, the plugin context can be overridden.
  17554. */
  17555. runHookSync(hookName, args, pluginIndex, hookContext) {
  17556. const plugin = this.plugins[pluginIndex];
  17557. const hook = plugin[hookName];
  17558. if (!hook)
  17559. return undefined;
  17560. let context = this.pluginContexts[pluginIndex];
  17561. if (hookContext) {
  17562. context = hookContext(context, plugin);
  17563. }
  17564. try {
  17565. // permit values allows values to be returned instead of a functional hook
  17566. if (typeof hook !== 'function') {
  17567. return throwInvalidHookError(hookName, plugin.name);
  17568. }
  17569. return hook.apply(context, args);
  17570. }
  17571. catch (err) {
  17572. return throwPluginError(err, plugin.name, { hook: hookName });
  17573. }
  17574. }
  17575. }
  17576. function normalizeEntryModules(entryModules) {
  17577. if (Array.isArray(entryModules)) {
  17578. return entryModules.map(id => ({
  17579. fileName: null,
  17580. id,
  17581. implicitlyLoadedAfter: [],
  17582. importer: undefined,
  17583. name: null
  17584. }));
  17585. }
  17586. return Object.keys(entryModules).map(name => ({
  17587. fileName: null,
  17588. id: entryModules[name],
  17589. implicitlyLoadedAfter: [],
  17590. importer: undefined,
  17591. name
  17592. }));
  17593. }
  17594. class Graph {
  17595. constructor(options, watcher) {
  17596. var _a, _b;
  17597. this.options = options;
  17598. this.entryModules = [];
  17599. this.modulesById = new Map();
  17600. this.needsTreeshakingPass = false;
  17601. this.phase = BuildPhase.LOAD_AND_PARSE;
  17602. this.watchFiles = Object.create(null);
  17603. this.watchMode = false;
  17604. this.externalModules = [];
  17605. this.implicitEntryModules = [];
  17606. this.modules = [];
  17607. this.getModuleInfo = (moduleId) => {
  17608. const foundModule = this.modulesById.get(moduleId);
  17609. if (!foundModule)
  17610. return null;
  17611. return foundModule.info;
  17612. };
  17613. this.deoptimizationTracker = new PathTracker();
  17614. this.cachedModules = new Map();
  17615. if (options.cache !== false) {
  17616. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  17617. for (const module of options.cache.modules)
  17618. this.cachedModules.set(module.id, module);
  17619. }
  17620. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  17621. // increment access counter
  17622. for (const name in this.pluginCache) {
  17623. const cache = this.pluginCache[name];
  17624. for (const key of Object.keys(cache))
  17625. cache[key][0]++;
  17626. }
  17627. }
  17628. this.contextParse = (code, options = {}) => this.acornParser.parse(code, {
  17629. ...this.options.acorn,
  17630. ...options
  17631. });
  17632. if (watcher) {
  17633. this.watchMode = true;
  17634. const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
  17635. const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
  17636. watcher.on('change', handleChange);
  17637. watcher.on('close', handleClose);
  17638. watcher.once('restart', () => {
  17639. watcher.removeListener('change', handleChange);
  17640. watcher.removeListener('close', handleClose);
  17641. });
  17642. }
  17643. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  17644. this.scope = new GlobalScope();
  17645. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  17646. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  17647. }
  17648. async build() {
  17649. timeStart('generate module graph', 2);
  17650. await this.generateModuleGraph();
  17651. timeEnd('generate module graph', 2);
  17652. timeStart('sort modules', 2);
  17653. this.phase = BuildPhase.ANALYSE;
  17654. this.sortModules();
  17655. timeEnd('sort modules', 2);
  17656. timeStart('mark included statements', 2);
  17657. this.includeStatements();
  17658. timeEnd('mark included statements', 2);
  17659. this.phase = BuildPhase.GENERATE;
  17660. }
  17661. getCache() {
  17662. // handle plugin cache eviction
  17663. for (const name in this.pluginCache) {
  17664. const cache = this.pluginCache[name];
  17665. let allDeleted = true;
  17666. for (const key of Object.keys(cache)) {
  17667. if (cache[key][0] >= this.options.experimentalCacheExpiry)
  17668. delete cache[key];
  17669. else
  17670. allDeleted = false;
  17671. }
  17672. if (allDeleted)
  17673. delete this.pluginCache[name];
  17674. }
  17675. return {
  17676. modules: this.modules.map(module => module.toJSON()),
  17677. plugins: this.pluginCache
  17678. };
  17679. }
  17680. async generateModuleGraph() {
  17681. ({
  17682. entryModules: this.entryModules,
  17683. implicitEntryModules: this.implicitEntryModules
  17684. } = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  17685. if (this.entryModules.length === 0) {
  17686. throw new Error('You must supply options.input to rollup');
  17687. }
  17688. for (const module of this.modulesById.values()) {
  17689. if (module instanceof Module) {
  17690. this.modules.push(module);
  17691. }
  17692. else {
  17693. this.externalModules.push(module);
  17694. }
  17695. }
  17696. }
  17697. includeStatements() {
  17698. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  17699. if (module.preserveSignature !== false) {
  17700. module.includeAllExports(false);
  17701. }
  17702. else {
  17703. markModuleAndImpureDependenciesAsExecuted(module);
  17704. }
  17705. }
  17706. if (this.options.treeshake) {
  17707. let treeshakingPass = 1;
  17708. do {
  17709. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  17710. this.needsTreeshakingPass = false;
  17711. for (const module of this.modules) {
  17712. if (module.isExecuted) {
  17713. if (module.info.hasModuleSideEffects === 'no-treeshake') {
  17714. module.includeAllInBundle();
  17715. }
  17716. else {
  17717. module.include();
  17718. }
  17719. }
  17720. }
  17721. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  17722. } while (this.needsTreeshakingPass);
  17723. }
  17724. else {
  17725. for (const module of this.modules)
  17726. module.includeAllInBundle();
  17727. }
  17728. for (const externalModule of this.externalModules)
  17729. externalModule.warnUnusedImports();
  17730. for (const module of this.implicitEntryModules) {
  17731. for (const dependant of module.implicitlyLoadedAfter) {
  17732. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  17733. error(errImplicitDependantIsNotIncluded(dependant));
  17734. }
  17735. }
  17736. }
  17737. }
  17738. sortModules() {
  17739. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  17740. for (const cyclePath of cyclePaths) {
  17741. this.options.onwarn({
  17742. code: 'CIRCULAR_DEPENDENCY',
  17743. cycle: cyclePath,
  17744. importer: cyclePath[0],
  17745. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  17746. });
  17747. }
  17748. this.modules = orderedModules;
  17749. for (const module of this.modules) {
  17750. module.bindReferences();
  17751. }
  17752. this.warnForMissingExports();
  17753. }
  17754. warnForMissingExports() {
  17755. for (const module of this.modules) {
  17756. for (const importName of Object.keys(module.importDescriptions)) {
  17757. const importDescription = module.importDescriptions[importName];
  17758. if (importDescription.name !== '*' &&
  17759. !importDescription.module.getVariableForExportName(importDescription.name)) {
  17760. module.warn({
  17761. code: 'NON_EXISTENT_EXPORT',
  17762. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  17763. name: importDescription.name,
  17764. source: importDescription.module.id
  17765. }, importDescription.start);
  17766. }
  17767. }
  17768. }
  17769. }
  17770. }
  17771. function ensureArray(items) {
  17772. if (Array.isArray(items)) {
  17773. return items.filter(Boolean);
  17774. }
  17775. if (items) {
  17776. return [items];
  17777. }
  17778. return [];
  17779. }
  17780. function createCommonjsModule(fn, basedir, module) {
  17781. return module = {
  17782. path: basedir,
  17783. exports: {},
  17784. require: function (path, base) {
  17785. return commonjsRequire();
  17786. }
  17787. }, fn(module, module.exports), module.exports;
  17788. }
  17789. function getAugmentedNamespace(n) {
  17790. if (n.__esModule) return n;
  17791. var a = Object.defineProperty({}, '__esModule', {value: true});
  17792. Object.keys(n).forEach(function (k) {
  17793. var d = Object.getOwnPropertyDescriptor(n, k);
  17794. Object.defineProperty(a, k, d.get ? d : {
  17795. enumerable: true,
  17796. get: function () {
  17797. return n[k];
  17798. }
  17799. });
  17800. });
  17801. return a;
  17802. }
  17803. function commonjsRequire () {
  17804. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  17805. }
  17806. var require$$0 = /*@__PURE__*/getAugmentedNamespace(acorn);
  17807. const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
  17808. const getAcorn = Parser => {
  17809. if (Parser.acorn) return Parser.acorn
  17810. const acorn = require$$0;
  17811. if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
  17812. throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
  17813. }
  17814. // Make sure `Parser` comes from the same acorn as we `require`d,
  17815. // otherwise the comparisons fail.
  17816. for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
  17817. if (cur !== acorn.Parser) {
  17818. throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
  17819. }
  17820. }
  17821. return acorn
  17822. };
  17823. var acornPrivateClassElements = function(Parser) {
  17824. // Only load this plugin once.
  17825. if (Parser.prototype.parsePrivateName) {
  17826. return Parser
  17827. }
  17828. const acorn = getAcorn(Parser);
  17829. Parser = class extends Parser {
  17830. _branch() {
  17831. this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
  17832. this.__branch.end = this.end;
  17833. this.__branch.pos = this.pos;
  17834. this.__branch.type = this.type;
  17835. this.__branch.value = this.value;
  17836. this.__branch.containsEsc = this.containsEsc;
  17837. return this.__branch
  17838. }
  17839. parsePrivateClassElementName(element) {
  17840. element.computed = false;
  17841. element.key = this.parsePrivateName();
  17842. if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
  17843. const accept = {get: "set", set: "get"}[element.kind];
  17844. const privateBoundNames = this._privateBoundNames;
  17845. if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
  17846. this.raise(element.start, "Duplicate private element");
  17847. }
  17848. privateBoundNames[element.key.name] = element.kind || true;
  17849. delete this._unresolvedPrivateNames[element.key.name];
  17850. return element.key
  17851. }
  17852. parsePrivateName() {
  17853. const node = this.startNode();
  17854. node.name = this.value;
  17855. this.next();
  17856. this.finishNode(node, "PrivateName");
  17857. if (this.options.allowReserved == "never") this.checkUnreserved(node);
  17858. return node
  17859. }
  17860. // Parse # token
  17861. getTokenFromCode(code) {
  17862. if (code === 35) {
  17863. ++this.pos;
  17864. const word = this.readWord1();
  17865. return this.finishToken(this.privateNameToken, word)
  17866. }
  17867. return super.getTokenFromCode(code)
  17868. }
  17869. // Manage stacks and check for undeclared private names
  17870. parseClass(node, isStatement) {
  17871. const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
  17872. this._outerPrivateBoundNames = this._privateBoundNames;
  17873. this._privateBoundNames = Object.create(this._privateBoundNames || null);
  17874. const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  17875. this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
  17876. this._unresolvedPrivateNames = Object.create(null);
  17877. const _return = super.parseClass(node, isStatement);
  17878. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  17879. this._privateBoundNames = this._outerPrivateBoundNames;
  17880. this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
  17881. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  17882. this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
  17883. if (!this._unresolvedPrivateNames) {
  17884. const names = Object.keys(unresolvedPrivateNames);
  17885. if (names.length) {
  17886. names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
  17887. this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
  17888. }
  17889. } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
  17890. return _return
  17891. }
  17892. // Class heritage is evaluated with outer private environment
  17893. parseClassSuper(node) {
  17894. const privateBoundNames = this._privateBoundNames;
  17895. this._privateBoundNames = this._outerPrivateBoundNames;
  17896. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  17897. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  17898. const _return = super.parseClassSuper(node);
  17899. this._privateBoundNames = privateBoundNames;
  17900. this._unresolvedPrivateNames = unresolvedPrivateNames;
  17901. return _return
  17902. }
  17903. // Parse private element access
  17904. parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
  17905. const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
  17906. const branch = this._branch();
  17907. if (!(
  17908. (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
  17909. branch.type == this.privateNameToken
  17910. )) {
  17911. return super.parseSubscript.apply(this, arguments)
  17912. }
  17913. let optional = false;
  17914. if (!this.eat(acorn.tokTypes.dot)) {
  17915. this.expect(acorn.tokTypes.questionDot);
  17916. optional = true;
  17917. }
  17918. let node = this.startNodeAt(startPos, startLoc);
  17919. node.object = base;
  17920. node.computed = false;
  17921. if (optionalSupported) {
  17922. node.optional = optional;
  17923. }
  17924. if (this.type == this.privateNameToken) {
  17925. if (base.type == "Super") {
  17926. this.raise(this.start, "Cannot access private element on super");
  17927. }
  17928. node.property = this.parsePrivateName();
  17929. if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
  17930. if (!this._unresolvedPrivateNames) {
  17931. this.raise(node.property.start, "Usage of undeclared private name");
  17932. }
  17933. this._unresolvedPrivateNames[node.property.name] = node.property.start;
  17934. }
  17935. } else {
  17936. node.property = this.parseIdent(true);
  17937. }
  17938. return this.finishNode(node, "MemberExpression")
  17939. }
  17940. // Prohibit delete of private class elements
  17941. parseMaybeUnary(refDestructuringErrors, sawUnary) {
  17942. const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
  17943. if (_return.operator == "delete") {
  17944. if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateName") {
  17945. this.raise(_return.start, "Private elements may not be deleted");
  17946. }
  17947. }
  17948. return _return
  17949. }
  17950. };
  17951. Parser.prototype.privateNameToken = new acorn.TokenType("privateName");
  17952. return Parser
  17953. };
  17954. var acornClassFields = function(Parser) {
  17955. const acorn = Parser.acorn || require$$0;
  17956. const tt = acorn.tokTypes;
  17957. Parser = acornPrivateClassElements(Parser);
  17958. return class extends Parser {
  17959. _maybeParseFieldValue(field) {
  17960. if (this.eat(tt.eq)) {
  17961. const oldInFieldValue = this._inFieldValue;
  17962. this._inFieldValue = true;
  17963. if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
  17964. field.value = this.parseAwait();
  17965. } else field.value = this.parseExpression();
  17966. this._inFieldValue = oldInFieldValue;
  17967. } else field.value = null;
  17968. }
  17969. // Parse fields
  17970. parseClassElement(_constructorAllowsSuper) {
  17971. if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateNameToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
  17972. const branch = this._branch();
  17973. if (branch.type == tt.bracketL) {
  17974. let count = 0;
  17975. do {
  17976. if (branch.eat(tt.bracketL)) ++count;
  17977. else if (branch.eat(tt.bracketR)) --count;
  17978. else branch.next();
  17979. } while (count > 0)
  17980. } else branch.next(true);
  17981. let isField = branch.type == tt.eq || branch.type == tt.semi;
  17982. if (!isField && branch.canInsertSemicolon()) {
  17983. isField = branch.type != tt.parenL;
  17984. }
  17985. if (isField) {
  17986. const node = this.startNode();
  17987. if (this.type == this.privateNameToken) {
  17988. this.parsePrivateClassElementName(node);
  17989. } else {
  17990. this.parsePropertyName(node);
  17991. }
  17992. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  17993. (node.key.type === "Literal" && node.key.value === "constructor")) {
  17994. this.raise(node.key.start, "Classes may not have a field called constructor");
  17995. }
  17996. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  17997. this._maybeParseFieldValue(node);
  17998. this.exitScope();
  17999. this.finishNode(node, "FieldDefinition");
  18000. this.semicolon();
  18001. return node
  18002. }
  18003. }
  18004. return super.parseClassElement.apply(this, arguments)
  18005. }
  18006. // Prohibit arguments in class field initializers
  18007. parseIdent(liberal, isBinding) {
  18008. const ident = super.parseIdent(liberal, isBinding);
  18009. if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
  18010. return ident
  18011. }
  18012. }
  18013. };
  18014. function withoutAcornBigInt(acorn, Parser) {
  18015. return class extends Parser {
  18016. readInt(radix, len) {
  18017. // Hack: len is only != null for unicode escape sequences,
  18018. // where numeric separators are not allowed
  18019. if (len != null) return super.readInt(radix, len)
  18020. let start = this.pos, total = 0, acceptUnderscore = false;
  18021. for (;;) {
  18022. let code = this.input.charCodeAt(this.pos), val;
  18023. if (code >= 97) val = code - 97 + 10; // a
  18024. else if (code == 95) {
  18025. if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
  18026. ++this.pos;
  18027. acceptUnderscore = false;
  18028. continue
  18029. } else if (code >= 65) val = code - 65 + 10; // A
  18030. else if (code >= 48 && code <= 57) val = code - 48; // 0-9
  18031. else val = Infinity;
  18032. if (val >= radix) break
  18033. ++this.pos;
  18034. total = total * radix + val;
  18035. acceptUnderscore = true;
  18036. }
  18037. if (this.pos === start) return null
  18038. if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
  18039. return total
  18040. }
  18041. readNumber(startsWithDot) {
  18042. const token = super.readNumber(startsWithDot);
  18043. let octal = this.end - this.start >= 2 && this.input.charCodeAt(this.start) === 48;
  18044. const stripped = this.getNumberInput(this.start, this.end);
  18045. if (stripped.length < this.end - this.start) {
  18046. if (octal) this.raise(this.start, "Invalid number");
  18047. this.value = parseFloat(stripped);
  18048. }
  18049. return token
  18050. }
  18051. // This is used by acorn-bigint
  18052. getNumberInput(start, end) {
  18053. return this.input.slice(start, end).replace(/_/g, "")
  18054. }
  18055. }
  18056. }
  18057. function withAcornBigInt(acorn, Parser) {
  18058. return class extends Parser {
  18059. readInt(radix, len) {
  18060. // Hack: len is only != null for unicode escape sequences,
  18061. // where numeric separators are not allowed
  18062. if (len != null) return super.readInt(radix, len)
  18063. let start = this.pos, total = 0, acceptUnderscore = false;
  18064. for (;;) {
  18065. let code = this.input.charCodeAt(this.pos), val;
  18066. if (code >= 97) val = code - 97 + 10; // a
  18067. else if (code == 95) {
  18068. if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
  18069. ++this.pos;
  18070. acceptUnderscore = false;
  18071. continue
  18072. } else if (code >= 65) val = code - 65 + 10; // A
  18073. else if (code >= 48 && code <= 57) val = code - 48; // 0-9
  18074. else val = Infinity;
  18075. if (val >= radix) break
  18076. ++this.pos;
  18077. total = total * radix + val;
  18078. acceptUnderscore = true;
  18079. }
  18080. if (this.pos === start) return null
  18081. if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
  18082. return total
  18083. }
  18084. readNumber(startsWithDot) {
  18085. let start = this.pos;
  18086. if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
  18087. let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  18088. let octalLike = false;
  18089. if (octal && this.strict) this.raise(start, "Invalid number");
  18090. let next = this.input.charCodeAt(this.pos);
  18091. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  18092. let str = this.getNumberInput(start, this.pos);
  18093. // eslint-disable-next-line node/no-unsupported-features/es-builtins
  18094. let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
  18095. ++this.pos;
  18096. if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
  18097. return this.finishToken(acorn.tokTypes.num, val)
  18098. }
  18099. if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
  18100. octal = false;
  18101. octalLike = true;
  18102. }
  18103. if (next === 46 && !octal) { // '.'
  18104. ++this.pos;
  18105. this.readInt(10);
  18106. next = this.input.charCodeAt(this.pos);
  18107. }
  18108. if ((next === 69 || next === 101) && !octal) { // 'eE'
  18109. next = this.input.charCodeAt(++this.pos);
  18110. if (next === 43 || next === 45) ++this.pos; // '+-'
  18111. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  18112. }
  18113. if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
  18114. let str = this.getNumberInput(start, this.pos);
  18115. if ((octal || octalLike) && str.length < this.pos - start) {
  18116. this.raise(start, "Invalid number");
  18117. }
  18118. let val = octal ? parseInt(str, 8) : parseFloat(str);
  18119. return this.finishToken(acorn.tokTypes.num, val)
  18120. }
  18121. parseLiteral(value) {
  18122. const ret = super.parseLiteral(value);
  18123. if (ret.bigint) ret.bigint = ret.bigint.replace(/_/g, "");
  18124. return ret
  18125. }
  18126. readRadixNumber(radix) {
  18127. let start = this.pos;
  18128. this.pos += 2; // 0x
  18129. let val = this.readInt(radix);
  18130. if (val == null) { this.raise(this.start + 2, `Expected number in radix ${radix}`); }
  18131. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  18132. let str = this.getNumberInput(start, this.pos);
  18133. // eslint-disable-next-line node/no-unsupported-features/es-builtins
  18134. val = typeof BigInt !== "undefined" ? BigInt(str) : null;
  18135. ++this.pos;
  18136. } else if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  18137. return this.finishToken(acorn.tokTypes.num, val)
  18138. }
  18139. // This is used by acorn-bigint, which theoretically could be used with acorn@6.2 || acorn@7
  18140. getNumberInput(start, end) {
  18141. return this.input.slice(start, end).replace(/_/g, "")
  18142. }
  18143. }
  18144. }
  18145. // eslint-disable-next-line node/no-unsupported-features/es-syntax
  18146. function numericSeparator(Parser) {
  18147. const acorn = Parser.acorn || require$$0;
  18148. const withAcornBigIntSupport = (acorn.version.startsWith("6.") && !(acorn.version.startsWith("6.0.") || acorn.version.startsWith("6.1."))) || acorn.version.startsWith("7.");
  18149. return withAcornBigIntSupport ? withAcornBigInt(acorn, Parser) : withoutAcornBigInt(acorn, Parser)
  18150. }
  18151. var acornNumericSeparator = numericSeparator;
  18152. var acornStaticClassFeatures = function(Parser) {
  18153. const ExtendedParser = acornPrivateClassElements(Parser);
  18154. const acorn = Parser.acorn || require$$0;
  18155. const tt = acorn.tokTypes;
  18156. return class extends ExtendedParser {
  18157. _maybeParseFieldValue(field) {
  18158. if (this.eat(tt.eq)) {
  18159. const oldInFieldValue = this._inStaticFieldScope;
  18160. this._inStaticFieldScope = this.currentThisScope();
  18161. field.value = this.parseExpression();
  18162. this._inStaticFieldScope = oldInFieldValue;
  18163. } else field.value = null;
  18164. }
  18165. // Parse fields
  18166. parseClassElement(_constructorAllowsSuper) {
  18167. if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
  18168. return super.parseClassElement.apply(this, arguments)
  18169. }
  18170. const branch = this._branch();
  18171. branch.next();
  18172. if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateNameToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
  18173. return super.parseClassElement.apply(this, arguments)
  18174. }
  18175. if (branch.type == tt.bracketL) {
  18176. let count = 0;
  18177. do {
  18178. if (branch.eat(tt.bracketL)) ++count;
  18179. else if (branch.eat(tt.bracketR)) --count;
  18180. else branch.next();
  18181. } while (count > 0)
  18182. } else branch.next();
  18183. if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
  18184. return super.parseClassElement.apply(this, arguments)
  18185. }
  18186. const node = this.startNode();
  18187. node.static = this.eatContextual("static");
  18188. if (this.type == this.privateNameToken) {
  18189. this.parsePrivateClassElementName(node);
  18190. } else {
  18191. this.parsePropertyName(node);
  18192. }
  18193. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  18194. (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
  18195. this.raise(node.key.start, "Classes may not have a field called constructor");
  18196. }
  18197. if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
  18198. this.raise(node.key.start, "Classes may not have a static property named prototype");
  18199. }
  18200. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  18201. this._maybeParseFieldValue(node);
  18202. this.exitScope();
  18203. this.finishNode(node, "FieldDefinition");
  18204. this.semicolon();
  18205. return node
  18206. }
  18207. // Parse private static methods
  18208. parsePropertyName(prop) {
  18209. if (prop.static && this.type == this.privateNameToken) {
  18210. this.parsePrivateClassElementName(prop);
  18211. } else {
  18212. super.parsePropertyName(prop);
  18213. }
  18214. }
  18215. // Prohibit arguments in class field initializers
  18216. parseIdent(liberal, isBinding) {
  18217. const ident = super.parseIdent(liberal, isBinding);
  18218. if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
  18219. this.raise(ident.start, "A static class field initializer may not contain arguments");
  18220. }
  18221. return ident
  18222. }
  18223. }
  18224. };
  18225. const defaultOnWarn = warning => console.warn(warning.message || warning);
  18226. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  18227. const validOptionSet = new Set(validOptions);
  18228. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  18229. if (unknownOptions.length > 0) {
  18230. warn({
  18231. code: 'UNKNOWN_OPTION',
  18232. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  18233. ...validOptionSet
  18234. ]
  18235. .sort()
  18236. .join(', ')}`
  18237. });
  18238. }
  18239. }
  18240. function normalizeInputOptions(config) {
  18241. var _a, _b;
  18242. // These are options that may trigger special warnings or behaviour later
  18243. // if the user did not select an explicit value
  18244. const unsetOptions = new Set();
  18245. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  18246. const onwarn = getOnwarn(config);
  18247. const strictDeprecations = config.strictDeprecations || false;
  18248. const options = {
  18249. acorn: getAcorn$1(config),
  18250. acornInjectPlugins: getAcornInjectPlugins(config),
  18251. cache: getCache(config),
  18252. context,
  18253. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  18254. external: getIdMatcher(config.external),
  18255. inlineDynamicImports: getInlineDynamicImports(config, onwarn, strictDeprecations),
  18256. input: getInput(config),
  18257. manualChunks: getManualChunks(config, onwarn, strictDeprecations),
  18258. moduleContext: getModuleContext(config, context),
  18259. onwarn,
  18260. perf: config.perf || false,
  18261. plugins: ensureArray(config.plugins),
  18262. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  18263. preserveModules: getPreserveModules(config, onwarn, strictDeprecations),
  18264. preserveSymlinks: config.preserveSymlinks || false,
  18265. shimMissingExports: config.shimMissingExports || false,
  18266. strictDeprecations,
  18267. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  18268. };
  18269. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  18270. return { options, unsetOptions };
  18271. }
  18272. const getOnwarn = (config) => {
  18273. return config.onwarn
  18274. ? warning => {
  18275. warning.toString = () => {
  18276. let str = '';
  18277. if (warning.plugin)
  18278. str += `(${warning.plugin} plugin) `;
  18279. if (warning.loc)
  18280. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  18281. str += warning.message;
  18282. return str;
  18283. };
  18284. config.onwarn(warning, defaultOnWarn);
  18285. }
  18286. : defaultOnWarn;
  18287. };
  18288. const getAcorn$1 = (config) => ({
  18289. allowAwaitOutsideFunction: true,
  18290. ecmaVersion: 'latest',
  18291. preserveParens: false,
  18292. sourceType: 'module',
  18293. ...config.acorn
  18294. });
  18295. const getAcornInjectPlugins = (config) => [
  18296. acornClassFields,
  18297. acornStaticClassFeatures,
  18298. acornNumericSeparator,
  18299. ...ensureArray(config.acornInjectPlugins)
  18300. ];
  18301. const getCache = (config) => {
  18302. var _a;
  18303. return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache;
  18304. };
  18305. const getIdMatcher = (option) => {
  18306. if (option === true) {
  18307. return () => true;
  18308. }
  18309. if (typeof option === 'function') {
  18310. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  18311. }
  18312. if (option) {
  18313. const ids = new Set();
  18314. const matchers = [];
  18315. for (const value of ensureArray(option)) {
  18316. if (value instanceof RegExp) {
  18317. matchers.push(value);
  18318. }
  18319. else {
  18320. ids.add(value);
  18321. }
  18322. }
  18323. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  18324. }
  18325. return () => false;
  18326. };
  18327. const getInlineDynamicImports = (config, warn, strictDeprecations) => {
  18328. const configInlineDynamicImports = config.inlineDynamicImports;
  18329. if (configInlineDynamicImports) {
  18330. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  18331. }
  18332. return configInlineDynamicImports;
  18333. };
  18334. const getInput = (config) => {
  18335. const configInput = config.input;
  18336. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  18337. };
  18338. const getManualChunks = (config, warn, strictDeprecations) => {
  18339. const configManualChunks = config.manualChunks;
  18340. if (configManualChunks) {
  18341. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  18342. }
  18343. return configManualChunks;
  18344. };
  18345. const getModuleContext = (config, context) => {
  18346. const configModuleContext = config.moduleContext;
  18347. if (typeof configModuleContext === 'function') {
  18348. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  18349. }
  18350. if (configModuleContext) {
  18351. const contextByModuleId = Object.create(null);
  18352. for (const key of Object.keys(configModuleContext)) {
  18353. contextByModuleId[resolve(key)] = configModuleContext[key];
  18354. }
  18355. return id => contextByModuleId[id] || context;
  18356. }
  18357. return () => context;
  18358. };
  18359. const getPreserveEntrySignatures = (config, unsetOptions) => {
  18360. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  18361. if (configPreserveEntrySignatures == null) {
  18362. unsetOptions.add('preserveEntrySignatures');
  18363. }
  18364. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  18365. };
  18366. const getPreserveModules = (config, warn, strictDeprecations) => {
  18367. const configPreserveModules = config.preserveModules;
  18368. if (configPreserveModules) {
  18369. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  18370. }
  18371. return configPreserveModules;
  18372. };
  18373. const getTreeshake = (config, warn, strictDeprecations) => {
  18374. const configTreeshake = config.treeshake;
  18375. if (configTreeshake === false) {
  18376. return false;
  18377. }
  18378. if (configTreeshake && configTreeshake !== true) {
  18379. if (typeof configTreeshake.pureExternalModules !== 'undefined') {
  18380. 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);
  18381. }
  18382. return {
  18383. annotations: configTreeshake.annotations !== false,
  18384. moduleSideEffects: getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules, warn),
  18385. propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
  18386. tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
  18387. unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
  18388. };
  18389. }
  18390. return {
  18391. annotations: true,
  18392. moduleSideEffects: () => true,
  18393. propertyReadSideEffects: true,
  18394. tryCatchDeoptimization: true,
  18395. unknownGlobalSideEffects: true
  18396. };
  18397. };
  18398. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules, warn) => {
  18399. if (typeof moduleSideEffectsOption === 'boolean') {
  18400. return () => moduleSideEffectsOption;
  18401. }
  18402. if (moduleSideEffectsOption === 'no-external') {
  18403. return (_id, external) => !external;
  18404. }
  18405. if (typeof moduleSideEffectsOption === 'function') {
  18406. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  18407. }
  18408. if (Array.isArray(moduleSideEffectsOption)) {
  18409. const ids = new Set(moduleSideEffectsOption);
  18410. return id => ids.has(id);
  18411. }
  18412. if (moduleSideEffectsOption) {
  18413. warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
  18414. }
  18415. const isPureExternalModule = getIdMatcher(pureExternalModules);
  18416. return (id, external) => !(external && isPureExternalModule(id));
  18417. };
  18418. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  18419. var _a, _b, _c, _d, _e, _f, _g;
  18420. // These are options that may trigger special warnings or behaviour later
  18421. // if the user did not select an explicit value
  18422. const unsetOptions = new Set(unsetInputOptions);
  18423. const compact = config.compact || false;
  18424. const format = getFormat(config);
  18425. const inlineDynamicImports = getInlineDynamicImports$1(config, inputOptions);
  18426. const preserveModules = getPreserveModules$1(config, inlineDynamicImports, inputOptions);
  18427. const file = getFile(config, preserveModules, inputOptions);
  18428. const outputOptions = {
  18429. amd: getAmd(config),
  18430. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  18431. banner: getAddon(config, 'banner'),
  18432. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  18433. compact,
  18434. dir: getDir(config, file),
  18435. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  18436. entryFileNames: getEntryFileNames(config, unsetOptions),
  18437. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  18438. exports: getExports(config, unsetOptions),
  18439. extend: config.extend || false,
  18440. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  18441. file,
  18442. footer: getAddon(config, 'footer'),
  18443. format,
  18444. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  18445. globals: config.globals || {},
  18446. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  18447. indent: getIndent(config, compact),
  18448. inlineDynamicImports,
  18449. interop: getInterop(config, inputOptions),
  18450. intro: getAddon(config, 'intro'),
  18451. manualChunks: getManualChunks$1(config, inlineDynamicImports, preserveModules, inputOptions),
  18452. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  18453. name: config.name,
  18454. namespaceToStringTag: config.namespaceToStringTag || false,
  18455. noConflict: config.noConflict || false,
  18456. outro: getAddon(config, 'outro'),
  18457. paths: config.paths || {},
  18458. plugins: ensureArray(config.plugins),
  18459. preferConst: config.preferConst || false,
  18460. preserveModules,
  18461. preserveModulesRoot: getPreserveModulesRoot(config),
  18462. sourcemap: config.sourcemap || false,
  18463. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  18464. sourcemapFile: config.sourcemapFile,
  18465. sourcemapPathTransform: config.sourcemapPathTransform,
  18466. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  18467. systemNullSetters: config.systemNullSetters || false
  18468. };
  18469. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  18470. return { options: outputOptions, unsetOptions };
  18471. }
  18472. const getFile = (config, preserveModules, inputOptions) => {
  18473. const file = config.file;
  18474. if (typeof file === 'string') {
  18475. if (preserveModules) {
  18476. return error({
  18477. code: 'INVALID_OPTION',
  18478. message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
  18479. });
  18480. }
  18481. if (!Array.isArray(inputOptions.input))
  18482. return error({
  18483. code: 'INVALID_OPTION',
  18484. message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
  18485. });
  18486. }
  18487. return file;
  18488. };
  18489. const getFormat = (config) => {
  18490. const configFormat = config.format;
  18491. switch (configFormat) {
  18492. case undefined:
  18493. case 'es':
  18494. case 'esm':
  18495. case 'module':
  18496. return 'es';
  18497. case 'cjs':
  18498. case 'commonjs':
  18499. return 'cjs';
  18500. case 'system':
  18501. case 'systemjs':
  18502. return 'system';
  18503. case 'amd':
  18504. case 'iife':
  18505. case 'umd':
  18506. return configFormat;
  18507. default:
  18508. return error({
  18509. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  18510. url: `https://rollupjs.org/guide/en/#outputformat`
  18511. });
  18512. }
  18513. };
  18514. const getInlineDynamicImports$1 = (config, inputOptions) => {
  18515. var _a;
  18516. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) ||
  18517. false;
  18518. const { input } = inputOptions;
  18519. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  18520. return error({
  18521. code: 'INVALID_OPTION',
  18522. message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
  18523. });
  18524. }
  18525. return inlineDynamicImports;
  18526. };
  18527. const getPreserveModules$1 = (config, inlineDynamicImports, inputOptions) => {
  18528. var _a;
  18529. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  18530. if (preserveModules) {
  18531. if (inlineDynamicImports) {
  18532. return error({
  18533. code: 'INVALID_OPTION',
  18534. message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
  18535. });
  18536. }
  18537. if (inputOptions.preserveEntrySignatures === false) {
  18538. return error({
  18539. code: 'INVALID_OPTION',
  18540. message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
  18541. });
  18542. }
  18543. }
  18544. return preserveModules;
  18545. };
  18546. const getPreserveModulesRoot = (config) => {
  18547. const preserveModulesRoot = config.preserveModulesRoot;
  18548. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  18549. return undefined;
  18550. }
  18551. return resolve(preserveModulesRoot);
  18552. };
  18553. const getAmd = (config) => ({
  18554. define: 'define',
  18555. ...config.amd
  18556. });
  18557. const getAddon = (config, name) => {
  18558. const configAddon = config[name];
  18559. if (typeof configAddon === 'function') {
  18560. return configAddon;
  18561. }
  18562. return () => configAddon || '';
  18563. };
  18564. const getDir = (config, file) => {
  18565. const dir = config.dir;
  18566. if (typeof dir === 'string' && typeof file === 'string') {
  18567. return error({
  18568. code: 'INVALID_OPTION',
  18569. message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
  18570. });
  18571. }
  18572. return dir;
  18573. };
  18574. const getDynamicImportFunction = (config, inputOptions) => {
  18575. const configDynamicImportFunction = config.dynamicImportFunction;
  18576. if (configDynamicImportFunction) {
  18577. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  18578. }
  18579. return configDynamicImportFunction;
  18580. };
  18581. const getEntryFileNames = (config, unsetOptions) => {
  18582. const configEntryFileNames = config.entryFileNames;
  18583. if (configEntryFileNames == null) {
  18584. unsetOptions.add('entryFileNames');
  18585. }
  18586. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  18587. };
  18588. function getExports(config, unsetOptions) {
  18589. const configExports = config.exports;
  18590. if (configExports == null) {
  18591. unsetOptions.add('exports');
  18592. }
  18593. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  18594. return error(errInvalidExportOptionValue(configExports));
  18595. }
  18596. return configExports || 'auto';
  18597. }
  18598. const getIndent = (config, compact) => {
  18599. if (compact) {
  18600. return '';
  18601. }
  18602. const configIndent = config.indent;
  18603. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  18604. };
  18605. const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
  18606. const getInterop = (config, inputOptions) => {
  18607. const configInterop = config.interop;
  18608. const validatedInteropTypes = new Set();
  18609. const validateInterop = (interop) => {
  18610. if (!validatedInteropTypes.has(interop)) {
  18611. validatedInteropTypes.add(interop);
  18612. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  18613. return error({
  18614. code: 'INVALID_OPTION',
  18615. 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.`,
  18616. url: 'https://rollupjs.org/guide/en/#outputinterop'
  18617. });
  18618. }
  18619. if (typeof interop === 'boolean') {
  18620. warnDeprecation({
  18621. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  18622. url: 'https://rollupjs.org/guide/en/#outputinterop'
  18623. }, false, inputOptions);
  18624. }
  18625. }
  18626. return interop;
  18627. };
  18628. if (typeof configInterop === 'function') {
  18629. const interopPerId = Object.create(null);
  18630. let defaultInterop = null;
  18631. return id => id === null
  18632. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  18633. : id in interopPerId
  18634. ? interopPerId[id]
  18635. : validateInterop((interopPerId[id] = configInterop(id)));
  18636. }
  18637. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  18638. };
  18639. const getManualChunks$1 = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  18640. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  18641. if (configManualChunks) {
  18642. if (inlineDynamicImports) {
  18643. return error({
  18644. code: 'INVALID_OPTION',
  18645. message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
  18646. });
  18647. }
  18648. if (preserveModules) {
  18649. return error({
  18650. code: 'INVALID_OPTION',
  18651. message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
  18652. });
  18653. }
  18654. }
  18655. return configManualChunks || {};
  18656. };
  18657. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  18658. function rollup(rawInputOptions) {
  18659. return rollupInternal(rawInputOptions, null);
  18660. }
  18661. async function rollupInternal(rawInputOptions, watcher) {
  18662. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  18663. initialiseTimers(inputOptions);
  18664. const graph = new Graph(inputOptions, watcher);
  18665. // remove the cache option from the memory after graph creation (cache is not used anymore)
  18666. const useCache = rawInputOptions.cache !== false;
  18667. delete inputOptions.cache;
  18668. delete rawInputOptions.cache;
  18669. timeStart('BUILD', 1);
  18670. try {
  18671. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  18672. await graph.build();
  18673. }
  18674. catch (err) {
  18675. const watchFiles = Object.keys(graph.watchFiles);
  18676. if (watchFiles.length > 0) {
  18677. err.watchFiles = watchFiles;
  18678. }
  18679. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  18680. throw err;
  18681. }
  18682. await graph.pluginDriver.hookParallel('buildEnd', []);
  18683. timeEnd('BUILD', 1);
  18684. const result = {
  18685. cache: useCache ? graph.getCache() : undefined,
  18686. async generate(rawOutputOptions) {
  18687. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  18688. },
  18689. watchFiles: Object.keys(graph.watchFiles),
  18690. async write(rawOutputOptions) {
  18691. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  18692. }
  18693. };
  18694. if (inputOptions.perf)
  18695. result.getTimings = getTimings;
  18696. return result;
  18697. }
  18698. async function getInputOptions(rawInputOptions, watchMode) {
  18699. if (!rawInputOptions) {
  18700. throw new Error('You must supply an options object to rollup');
  18701. }
  18702. const rawPlugins = ensureArray(rawInputOptions.plugins);
  18703. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  18704. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  18705. return { options, unsetOptions };
  18706. }
  18707. function applyOptionHook(watchMode) {
  18708. return async (inputOptions, plugin) => {
  18709. if (plugin.options)
  18710. return (plugin.options.call({ meta: { rollupVersion: version, watchMode } }, await inputOptions) || inputOptions);
  18711. return inputOptions;
  18712. };
  18713. }
  18714. function normalizePlugins(plugins, anonymousPrefix) {
  18715. for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
  18716. const plugin = plugins[pluginIndex];
  18717. if (!plugin.name) {
  18718. plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
  18719. }
  18720. }
  18721. }
  18722. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  18723. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  18724. const bundle = new Bundle$1(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  18725. const generated = await bundle.generate(isWrite);
  18726. if (isWrite) {
  18727. if (!outputOptions.dir && !outputOptions.file) {
  18728. return error({
  18729. code: 'MISSING_OPTION',
  18730. message: 'You must specify "output.file" or "output.dir" for the build.'
  18731. });
  18732. }
  18733. await Promise.all(Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions)));
  18734. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  18735. }
  18736. return createOutput(generated);
  18737. }
  18738. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  18739. if (!rawOutputOptions) {
  18740. throw new Error('You must supply an options object');
  18741. }
  18742. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  18743. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  18744. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  18745. return {
  18746. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  18747. outputPluginDriver
  18748. };
  18749. }
  18750. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  18751. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  18752. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  18753. return {
  18754. ...pluginContext,
  18755. emitFile: emitError,
  18756. setAssetSource: emitError
  18757. };
  18758. }), inputOptions, unsetInputOptions);
  18759. }
  18760. function createOutput(outputBundle) {
  18761. return {
  18762. output: Object.keys(outputBundle)
  18763. .map(fileName => outputBundle[fileName])
  18764. .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  18765. const fileTypeA = getSortingFileType(outputFileA);
  18766. const fileTypeB = getSortingFileType(outputFileB);
  18767. if (fileTypeA === fileTypeB)
  18768. return 0;
  18769. return fileTypeA < fileTypeB ? -1 : 1;
  18770. })
  18771. };
  18772. }
  18773. var SortingFileType;
  18774. (function (SortingFileType) {
  18775. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  18776. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  18777. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  18778. })(SortingFileType || (SortingFileType = {}));
  18779. function getSortingFileType(file) {
  18780. if (file.type === 'asset') {
  18781. return SortingFileType.ASSET;
  18782. }
  18783. if (file.isEntry) {
  18784. return SortingFileType.ENTRY_CHUNK;
  18785. }
  18786. return SortingFileType.SECONDARY_CHUNK;
  18787. }
  18788. function writeOutputFile(outputFile, outputOptions) {
  18789. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  18790. let writeSourceMapPromise;
  18791. let source;
  18792. if (outputFile.type === 'asset') {
  18793. source = outputFile.source;
  18794. }
  18795. else {
  18796. source = outputFile.code;
  18797. if (outputOptions.sourcemap && outputFile.map) {
  18798. let url;
  18799. if (outputOptions.sourcemap === 'inline') {
  18800. url = outputFile.map.toUrl();
  18801. }
  18802. else {
  18803. url = `${basename(outputFile.fileName)}.map`;
  18804. writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
  18805. }
  18806. if (outputOptions.sourcemap !== 'hidden') {
  18807. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  18808. }
  18809. }
  18810. }
  18811. return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
  18812. }
  18813. let fsEvents;
  18814. let fsEventsImportError;
  18815. function loadFsEvents() {
  18816. return import('fsevents')
  18817. .then(namespace => {
  18818. fsEvents = namespace.default;
  18819. })
  18820. .catch(err => {
  18821. fsEventsImportError = err;
  18822. });
  18823. }
  18824. // A call to this function will be injected into the chokidar code
  18825. function getFsEvents() {
  18826. if (fsEventsImportError)
  18827. throw fsEventsImportError;
  18828. return fsEvents;
  18829. }
  18830. var fseventsImporter = {
  18831. __proto__: null,
  18832. loadFsEvents: loadFsEvents,
  18833. getFsEvents: getFsEvents
  18834. };
  18835. class WatchEmitter extends EventEmitter {
  18836. constructor() {
  18837. super();
  18838. // Allows more than 10 bundles to be watched without
  18839. // showing the `MaxListenersExceededWarning` to the user.
  18840. this.setMaxListeners(Infinity);
  18841. }
  18842. close() { }
  18843. }
  18844. function watch(configs) {
  18845. const emitter = new WatchEmitter();
  18846. const configArray = ensureArray(configs);
  18847. const watchConfigs = configArray.filter(config => config.watch !== false);
  18848. if (watchConfigs.length === 0) {
  18849. throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
  18850. }
  18851. loadFsEvents()
  18852. .then(() => import('./watch.js'))
  18853. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  18854. return emitter;
  18855. }
  18856. export { createCommonjsModule, defaultOnWarn, ensureArray, fseventsImporter, getAugmentedNamespace, rollup, rollupInternal, version, warnUnknownOptions, watch };