rollup.js 739 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231
  1. /*
  2. @license
  3. Rollup.js v2.40.0
  4. Fri, 26 Feb 2021 14:39:44 GMT - commit 0a0958ff926554abe9916178f56762ba71301ddd
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { relative as relative$1, resolve, extname, basename, dirname } 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$1 = "2.40.0";
  13. var charToInteger = {};
  14. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15. for (var i = 0; i < chars$1.length; i++) {
  16. charToInteger[chars$1.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$1[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$1 = 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$1.prototype.appendLeft = function appendLeft (content) {
  159. this.outro += content;
  160. };
  161. Chunk$1.prototype.appendRight = function appendRight (content) {
  162. this.intro = this.intro + content;
  163. };
  164. Chunk$1.prototype.clone = function clone () {
  165. var chunk = new Chunk$1(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$1.prototype.contains = function contains (index) {
  174. return this.start < index && index < this.end;
  175. };
  176. Chunk$1.prototype.eachNext = function eachNext (fn) {
  177. var chunk = this;
  178. while (chunk) {
  179. fn(chunk);
  180. chunk = chunk.next;
  181. }
  182. };
  183. Chunk$1.prototype.eachPrevious = function eachPrevious (fn) {
  184. var chunk = this;
  185. while (chunk) {
  186. fn(chunk);
  187. chunk = chunk.previous;
  188. }
  189. };
  190. Chunk$1.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$1.prototype.prependLeft = function prependLeft (content) {
  201. this.outro = content + this.outro;
  202. };
  203. Chunk$1.prototype.prependRight = function prependRight (content) {
  204. this.intro = content + this.intro;
  205. };
  206. Chunk$1.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$1(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$1.prototype.toString = function toString () {
  229. return this.intro + this.content + this.outro;
  230. };
  231. Chunk$1.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$1.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$1 = Object.prototype.toString;
  319. function isObject(thing) {
  320. return toString$1.call(thing) === '[object Object]';
  321. }
  322. function getLocator$1(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$1(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$1(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$1(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$1(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$1 = 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$1.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$1.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$1.prototype.clone = function clone () {
  970. var bundle = new Bundle$1({
  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$1.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$1(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$1.prototype.generateMap = function generateMap (options) {
  1048. return new SourceMap(this.generateDecodedMap(options));
  1049. };
  1050. Bundle$1.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$1.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$1.prototype.prepend = function prepend (str) {
  1090. this.intro = str + this.intro;
  1091. return this;
  1092. };
  1093. Bundle$1.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$1.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$1.prototype.length = function length () {
  1112. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  1113. };
  1114. Bundle$1.prototype.trimLines = function trimLines () {
  1115. return this.trim('[\\r\\n]');
  1116. };
  1117. Bundle$1.prototype.trim = function trim (charType) {
  1118. return this.trimStart(charType).trimEnd(charType);
  1119. };
  1120. Bundle$1.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$1.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$1 = 'ArrowFunctionExpression';
  1169. const BlockStatement$1 = 'BlockStatement';
  1170. const CallExpression$1 = 'CallExpression';
  1171. const ExpressionStatement$1 = 'ExpressionStatement';
  1172. const Identifier$1 = 'Identifier';
  1173. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  1174. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  1175. const NewExpression$1 = 'NewExpression';
  1176. const Program$1 = 'Program';
  1177. const Property$1 = 'Property';
  1178. const ReturnStatement$1 = '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$1) {
  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 NON_WHITESPACE = /\S/g;
  1224. function findNonWhiteSpace(code, index) {
  1225. NON_WHITESPACE.lastIndex = index;
  1226. const result = NON_WHITESPACE.exec(code);
  1227. return result.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 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  1365. const base$1 = 64;
  1366. function toBase64(num) {
  1367. let outStr = '';
  1368. do {
  1369. const curDigit = num % base$1;
  1370. num = Math.floor(num / base$1);
  1371. outStr = chars[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. const BROKEN_FLOW_NONE = 0;
  1880. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  1881. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  1882. function createInclusionContext() {
  1883. return {
  1884. brokenFlow: BROKEN_FLOW_NONE,
  1885. includedCallArguments: new Set(),
  1886. includedLabels: new Set()
  1887. };
  1888. }
  1889. function createHasEffectsContext() {
  1890. return {
  1891. accessed: new PathTracker(),
  1892. assigned: new PathTracker(),
  1893. brokenFlow: BROKEN_FLOW_NONE,
  1894. called: new DiscriminatedPathTracker(),
  1895. ignore: {
  1896. breaks: false,
  1897. continues: false,
  1898. labels: new Set(),
  1899. returnAwaitYield: false
  1900. },
  1901. includedLabels: new Set(),
  1902. instantiated: new DiscriminatedPathTracker(),
  1903. replacedVariableInits: new Map()
  1904. };
  1905. }
  1906. class Variable {
  1907. constructor(name) {
  1908. this.alwaysRendered = false;
  1909. this.included = false;
  1910. this.isId = false;
  1911. this.isReassigned = false;
  1912. this.renderBaseName = null;
  1913. this.renderName = null;
  1914. this.name = name;
  1915. }
  1916. /**
  1917. * Binds identifiers that reference this variable to this variable.
  1918. * Necessary to be able to change variable names.
  1919. */
  1920. addReference(_identifier) { }
  1921. deoptimizePath(_path) { }
  1922. getBaseVariableName() {
  1923. return this.renderBaseName || this.renderName || this.name;
  1924. }
  1925. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1926. return UnknownValue;
  1927. }
  1928. getName() {
  1929. const name = this.renderName || this.name;
  1930. return this.renderBaseName
  1931. ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
  1932. : name;
  1933. }
  1934. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  1935. return UNKNOWN_EXPRESSION;
  1936. }
  1937. hasEffectsWhenAccessedAtPath(path, _context) {
  1938. return path.length > 0;
  1939. }
  1940. hasEffectsWhenAssignedAtPath(_path, _context) {
  1941. return true;
  1942. }
  1943. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  1944. return true;
  1945. }
  1946. /**
  1947. * Marks this variable as being part of the bundle, which is usually the case when one of
  1948. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1949. * previously.
  1950. * Once a variable is included, it should take care all its declarations are included.
  1951. */
  1952. include() {
  1953. this.included = true;
  1954. }
  1955. includeCallArguments(context, args) {
  1956. for (const arg of args) {
  1957. arg.include(context, false);
  1958. }
  1959. }
  1960. markCalledFromTryStatement() { }
  1961. setRenderNames(baseName, name) {
  1962. this.renderBaseName = baseName;
  1963. this.renderName = name;
  1964. }
  1965. }
  1966. // To avoid infinite recursions
  1967. const MAX_PATH_DEPTH = 7;
  1968. class LocalVariable extends Variable {
  1969. constructor(name, declarator, init, context) {
  1970. super(name);
  1971. this.additionalInitializers = null;
  1972. this.calledFromTryStatement = false;
  1973. this.expressionsToBeDeoptimized = [];
  1974. this.declarations = declarator ? [declarator] : [];
  1975. this.init = init;
  1976. this.deoptimizationTracker = context.deoptimizationTracker;
  1977. this.module = context.module;
  1978. }
  1979. addDeclaration(identifier, init) {
  1980. this.declarations.push(identifier);
  1981. if (this.additionalInitializers === null) {
  1982. this.additionalInitializers = this.init === null ? [] : [this.init];
  1983. this.init = UNKNOWN_EXPRESSION;
  1984. this.isReassigned = true;
  1985. }
  1986. if (init !== null) {
  1987. this.additionalInitializers.push(init);
  1988. }
  1989. }
  1990. consolidateInitializers() {
  1991. if (this.additionalInitializers !== null) {
  1992. for (const initializer of this.additionalInitializers) {
  1993. initializer.deoptimizePath(UNKNOWN_PATH);
  1994. }
  1995. this.additionalInitializers = null;
  1996. }
  1997. }
  1998. deoptimizePath(path) {
  1999. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2000. return;
  2001. const trackedEntities = this.deoptimizationTracker.getEntities(path);
  2002. if (trackedEntities.has(this))
  2003. return;
  2004. trackedEntities.add(this);
  2005. if (path.length === 0) {
  2006. if (!this.isReassigned) {
  2007. this.isReassigned = true;
  2008. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  2009. this.expressionsToBeDeoptimized = [];
  2010. for (const expression of expressionsToBeDeoptimized) {
  2011. expression.deoptimizeCache();
  2012. }
  2013. if (this.init) {
  2014. this.init.deoptimizePath(UNKNOWN_PATH);
  2015. }
  2016. }
  2017. }
  2018. else if (this.init) {
  2019. this.init.deoptimizePath(path);
  2020. }
  2021. }
  2022. getLiteralValueAtPath(path, recursionTracker, origin) {
  2023. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2024. return UnknownValue;
  2025. }
  2026. const trackedEntities = recursionTracker.getEntities(path);
  2027. if (trackedEntities.has(this.init)) {
  2028. return UnknownValue;
  2029. }
  2030. this.expressionsToBeDeoptimized.push(origin);
  2031. trackedEntities.add(this.init);
  2032. const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  2033. trackedEntities.delete(this.init);
  2034. return value;
  2035. }
  2036. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  2037. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2038. return UNKNOWN_EXPRESSION;
  2039. }
  2040. const trackedEntities = recursionTracker.getEntities(path);
  2041. if (trackedEntities.has(this.init)) {
  2042. return UNKNOWN_EXPRESSION;
  2043. }
  2044. this.expressionsToBeDeoptimized.push(origin);
  2045. trackedEntities.add(this.init);
  2046. const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  2047. trackedEntities.delete(this.init);
  2048. return value;
  2049. }
  2050. hasEffectsWhenAccessedAtPath(path, context) {
  2051. if (path.length === 0)
  2052. return false;
  2053. if (this.isReassigned || path.length > MAX_PATH_DEPTH)
  2054. return true;
  2055. const trackedExpressions = context.accessed.getEntities(path);
  2056. if (trackedExpressions.has(this))
  2057. return false;
  2058. trackedExpressions.add(this);
  2059. return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
  2060. }
  2061. hasEffectsWhenAssignedAtPath(path, context) {
  2062. if (this.included || path.length > MAX_PATH_DEPTH)
  2063. return true;
  2064. if (path.length === 0)
  2065. return false;
  2066. if (this.isReassigned)
  2067. return true;
  2068. const trackedExpressions = context.assigned.getEntities(path);
  2069. if (trackedExpressions.has(this))
  2070. return false;
  2071. trackedExpressions.add(this);
  2072. return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
  2073. }
  2074. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2075. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2076. return true;
  2077. const trackedExpressions = (callOptions.withNew
  2078. ? context.instantiated
  2079. : context.called).getEntities(path, callOptions);
  2080. if (trackedExpressions.has(this))
  2081. return false;
  2082. trackedExpressions.add(this);
  2083. return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2084. }
  2085. include() {
  2086. if (!this.included) {
  2087. this.included = true;
  2088. for (const declaration of this.declarations) {
  2089. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  2090. if (!declaration.included)
  2091. declaration.include(createInclusionContext(), false);
  2092. let node = declaration.parent;
  2093. while (!node.included) {
  2094. // We do not want to properly include parents in case they are part of a dead branch
  2095. // in which case .include() might pull in more dead code
  2096. node.included = true;
  2097. if (node.type === Program$1)
  2098. break;
  2099. node = node.parent;
  2100. }
  2101. }
  2102. }
  2103. }
  2104. includeCallArguments(context, args) {
  2105. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  2106. for (const arg of args) {
  2107. arg.include(context, false);
  2108. }
  2109. }
  2110. else if (this.init) {
  2111. context.includedCallArguments.add(this.init);
  2112. this.init.includeCallArguments(context, args);
  2113. context.includedCallArguments.delete(this.init);
  2114. }
  2115. }
  2116. markCalledFromTryStatement() {
  2117. this.calledFromTryStatement = true;
  2118. }
  2119. }
  2120. class Scope$1 {
  2121. constructor() {
  2122. this.children = [];
  2123. this.variables = new Map();
  2124. }
  2125. addDeclaration(identifier, context, init, _isHoisted) {
  2126. const name = identifier.name;
  2127. let variable = this.variables.get(name);
  2128. if (variable) {
  2129. variable.addDeclaration(identifier, init);
  2130. }
  2131. else {
  2132. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  2133. this.variables.set(name, variable);
  2134. }
  2135. return variable;
  2136. }
  2137. contains(name) {
  2138. return this.variables.has(name);
  2139. }
  2140. findVariable(_name) {
  2141. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  2142. }
  2143. }
  2144. class ChildScope extends Scope$1 {
  2145. constructor(parent) {
  2146. super();
  2147. this.accessedOutsideVariables = new Map();
  2148. this.parent = parent;
  2149. parent.children.push(this);
  2150. }
  2151. addAccessedDynamicImport(importExpression) {
  2152. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  2153. if (this.parent instanceof ChildScope) {
  2154. this.parent.addAccessedDynamicImport(importExpression);
  2155. }
  2156. }
  2157. addAccessedGlobals(globals, accessedGlobalsByScope) {
  2158. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  2159. for (const name of globals) {
  2160. accessedGlobals.add(name);
  2161. }
  2162. accessedGlobalsByScope.set(this, accessedGlobals);
  2163. if (this.parent instanceof ChildScope) {
  2164. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  2165. }
  2166. }
  2167. addNamespaceMemberAccess(name, variable) {
  2168. this.accessedOutsideVariables.set(name, variable);
  2169. this.parent.addNamespaceMemberAccess(name, variable);
  2170. }
  2171. addReturnExpression(expression) {
  2172. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  2173. }
  2174. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  2175. for (const variable of this.accessedOutsideVariables.values()) {
  2176. if (variable.included) {
  2177. usedNames.add(variable.getBaseVariableName());
  2178. if (format === 'system' && exportNamesByVariable.has(variable)) {
  2179. usedNames.add('exports');
  2180. }
  2181. }
  2182. }
  2183. const accessedGlobals = accessedGlobalsByScope.get(this);
  2184. if (accessedGlobals) {
  2185. for (const name of accessedGlobals) {
  2186. usedNames.add(name);
  2187. }
  2188. }
  2189. }
  2190. contains(name) {
  2191. return this.variables.has(name) || this.parent.contains(name);
  2192. }
  2193. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  2194. const usedNames = new Set();
  2195. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  2196. if (this.accessedDynamicImports) {
  2197. for (const importExpression of this.accessedDynamicImports) {
  2198. if (importExpression.inlineNamespace) {
  2199. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  2200. }
  2201. }
  2202. }
  2203. for (const [name, variable] of this.variables) {
  2204. if (variable.included || variable.alwaysRendered) {
  2205. variable.setRenderNames(null, getSafeName(name, usedNames));
  2206. }
  2207. }
  2208. for (const scope of this.children) {
  2209. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  2210. }
  2211. }
  2212. findLexicalBoundary() {
  2213. return this.parent.findLexicalBoundary();
  2214. }
  2215. findVariable(name) {
  2216. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  2217. if (knownVariable) {
  2218. return knownVariable;
  2219. }
  2220. const variable = this.parent.findVariable(name);
  2221. this.accessedOutsideVariables.set(name, variable);
  2222. return variable;
  2223. }
  2224. }
  2225. function getLocator(source, options) {
  2226. if (options === void 0) { options = {}; }
  2227. var offsetLine = options.offsetLine || 0;
  2228. var offsetColumn = options.offsetColumn || 0;
  2229. var originalLines = source.split('\n');
  2230. var start = 0;
  2231. var lineRanges = originalLines.map(function (line, i) {
  2232. var end = start + line.length + 1;
  2233. var range = { start: start, end: end, line: i };
  2234. start = end;
  2235. return range;
  2236. });
  2237. var i = 0;
  2238. function rangeContains(range, index) {
  2239. return range.start <= index && index < range.end;
  2240. }
  2241. function getLocation(range, index) {
  2242. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  2243. }
  2244. function locate(search, startIndex) {
  2245. if (typeof search === 'string') {
  2246. search = source.indexOf(search, startIndex || 0);
  2247. }
  2248. var range = lineRanges[i];
  2249. var d = search >= range.end ? 1 : -1;
  2250. while (range) {
  2251. if (rangeContains(range, search))
  2252. return getLocation(range, search);
  2253. i += d;
  2254. range = lineRanges[i];
  2255. }
  2256. }
  2257. return locate;
  2258. }
  2259. function locate(source, search, options) {
  2260. if (typeof options === 'number') {
  2261. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  2262. }
  2263. return getLocator(source, options)(search, options && options.startIndex);
  2264. }
  2265. const keys = {
  2266. Literal: [],
  2267. Program: ['body']
  2268. };
  2269. function getAndCreateKeys(esTreeNode) {
  2270. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
  2271. return keys[esTreeNode.type];
  2272. }
  2273. const INCLUDE_PARAMETERS = 'variables';
  2274. class NodeBase {
  2275. constructor(esTreeNode, parent, parentScope) {
  2276. this.included = false;
  2277. this.esTreeNode = esTreeNode;
  2278. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  2279. this.parent = parent;
  2280. this.context = parent.context;
  2281. this.createScope(parentScope);
  2282. this.parseNode(esTreeNode);
  2283. this.initialise();
  2284. this.context.magicString.addSourcemapLocation(this.start);
  2285. this.context.magicString.addSourcemapLocation(this.end);
  2286. }
  2287. addExportedVariables(_variables, _exportNamesByVariable) { }
  2288. /**
  2289. * Override this to bind assignments to variables and do any initialisations that
  2290. * require the scopes to be populated with variables.
  2291. */
  2292. bind() {
  2293. for (const key of this.keys) {
  2294. const value = this[key];
  2295. if (value === null || key === 'annotations')
  2296. continue;
  2297. if (Array.isArray(value)) {
  2298. for (const child of value) {
  2299. if (child !== null)
  2300. child.bind();
  2301. }
  2302. }
  2303. else {
  2304. value.bind();
  2305. }
  2306. }
  2307. }
  2308. /**
  2309. * Override if this node should receive a different scope than the parent scope.
  2310. */
  2311. createScope(parentScope) {
  2312. this.scope = parentScope;
  2313. }
  2314. deoptimizePath(_path) { }
  2315. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2316. return UnknownValue;
  2317. }
  2318. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  2319. return UNKNOWN_EXPRESSION;
  2320. }
  2321. hasEffects(context) {
  2322. for (const key of this.keys) {
  2323. const value = this[key];
  2324. if (value === null || key === 'annotations')
  2325. continue;
  2326. if (Array.isArray(value)) {
  2327. for (const child of value) {
  2328. if (child !== null && child.hasEffects(context))
  2329. return true;
  2330. }
  2331. }
  2332. else if (value.hasEffects(context))
  2333. return true;
  2334. }
  2335. return false;
  2336. }
  2337. hasEffectsWhenAccessedAtPath(path, _context) {
  2338. return path.length > 0;
  2339. }
  2340. hasEffectsWhenAssignedAtPath(_path, _context) {
  2341. return true;
  2342. }
  2343. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  2344. return true;
  2345. }
  2346. include(context, includeChildrenRecursively) {
  2347. this.included = true;
  2348. for (const key of this.keys) {
  2349. const value = this[key];
  2350. if (value === null || key === 'annotations')
  2351. continue;
  2352. if (Array.isArray(value)) {
  2353. for (const child of value) {
  2354. if (child !== null)
  2355. child.include(context, includeChildrenRecursively);
  2356. }
  2357. }
  2358. else {
  2359. value.include(context, includeChildrenRecursively);
  2360. }
  2361. }
  2362. }
  2363. includeAsSingleStatement(context, includeChildrenRecursively) {
  2364. this.include(context, includeChildrenRecursively);
  2365. }
  2366. includeCallArguments(context, args) {
  2367. for (const arg of args) {
  2368. arg.include(context, false);
  2369. }
  2370. }
  2371. /**
  2372. * Override to perform special initialisation steps after the scope is initialised
  2373. */
  2374. initialise() { }
  2375. insertSemicolon(code) {
  2376. if (code.original[this.end - 1] !== ';') {
  2377. code.appendLeft(this.end, ';');
  2378. }
  2379. }
  2380. parseNode(esTreeNode) {
  2381. for (const key of Object.keys(esTreeNode)) {
  2382. // That way, we can override this function to add custom initialisation and then call super.parseNode
  2383. if (this.hasOwnProperty(key))
  2384. continue;
  2385. const value = esTreeNode[key];
  2386. if (typeof value !== 'object' || value === null || key === 'annotations') {
  2387. this[key] = value;
  2388. }
  2389. else if (Array.isArray(value)) {
  2390. this[key] = [];
  2391. for (const child of value) {
  2392. this[key].push(child === null
  2393. ? null
  2394. : new (this.context.nodeConstructors[child.type] ||
  2395. this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
  2396. }
  2397. }
  2398. else {
  2399. this[key] = new (this.context.nodeConstructors[value.type] ||
  2400. this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
  2401. }
  2402. }
  2403. }
  2404. render(code, options) {
  2405. for (const key of this.keys) {
  2406. const value = this[key];
  2407. if (value === null || key === 'annotations')
  2408. continue;
  2409. if (Array.isArray(value)) {
  2410. for (const child of value) {
  2411. if (child !== null)
  2412. child.render(code, options);
  2413. }
  2414. }
  2415. else {
  2416. value.render(code, options);
  2417. }
  2418. }
  2419. }
  2420. shouldBeIncluded(context) {
  2421. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2422. }
  2423. }
  2424. class ClassNode extends NodeBase {
  2425. createScope(parentScope) {
  2426. this.scope = new ChildScope(parentScope);
  2427. }
  2428. hasEffectsWhenAccessedAtPath(path) {
  2429. if (path.length <= 1)
  2430. return false;
  2431. return path.length > 2 || path[0] !== 'prototype';
  2432. }
  2433. hasEffectsWhenAssignedAtPath(path) {
  2434. if (path.length <= 1)
  2435. return false;
  2436. return path.length > 2 || path[0] !== 'prototype';
  2437. }
  2438. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2439. if (!callOptions.withNew)
  2440. return true;
  2441. return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  2442. (this.superClass !== null &&
  2443. this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
  2444. }
  2445. initialise() {
  2446. if (this.id !== null) {
  2447. this.id.declare('class', this);
  2448. }
  2449. }
  2450. }
  2451. class ClassDeclaration extends ClassNode {
  2452. initialise() {
  2453. super.initialise();
  2454. if (this.id !== null) {
  2455. this.id.variable.isId = true;
  2456. }
  2457. }
  2458. parseNode(esTreeNode) {
  2459. if (esTreeNode.id !== null) {
  2460. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  2461. }
  2462. super.parseNode(esTreeNode);
  2463. }
  2464. render(code, options) {
  2465. if (options.format === 'system' &&
  2466. this.id &&
  2467. options.exportNamesByVariable.has(this.id.variable)) {
  2468. code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
  2469. }
  2470. super.render(code, options);
  2471. }
  2472. }
  2473. class ArgumentsVariable extends LocalVariable {
  2474. constructor(context) {
  2475. super('arguments', null, UNKNOWN_EXPRESSION, context);
  2476. }
  2477. hasEffectsWhenAccessedAtPath(path) {
  2478. return path.length > 1;
  2479. }
  2480. hasEffectsWhenAssignedAtPath() {
  2481. return true;
  2482. }
  2483. hasEffectsWhenCalledAtPath() {
  2484. return true;
  2485. }
  2486. }
  2487. class ThisVariable extends LocalVariable {
  2488. constructor(context) {
  2489. super('this', null, null, context);
  2490. }
  2491. getLiteralValueAtPath() {
  2492. return UnknownValue;
  2493. }
  2494. hasEffectsWhenAccessedAtPath(path, context) {
  2495. return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
  2496. super.hasEffectsWhenAccessedAtPath(path, context));
  2497. }
  2498. hasEffectsWhenAssignedAtPath(path, context) {
  2499. return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
  2500. super.hasEffectsWhenAssignedAtPath(path, context));
  2501. }
  2502. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2503. return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  2504. super.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2505. }
  2506. getInit(context) {
  2507. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  2508. }
  2509. }
  2510. class SpreadElement extends NodeBase {
  2511. bind() {
  2512. super.bind();
  2513. // Only properties of properties of the argument could become subject to reassignment
  2514. // This will also reassign the return values of iterators
  2515. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  2516. }
  2517. }
  2518. class ParameterScope extends ChildScope {
  2519. constructor(parent, context) {
  2520. super(parent);
  2521. this.parameters = [];
  2522. this.hasRest = false;
  2523. this.context = context;
  2524. this.hoistedBodyVarScope = new ChildScope(this);
  2525. }
  2526. /**
  2527. * Adds a parameter to this scope. Parameters must be added in the correct
  2528. * order, e.g. from left to right.
  2529. */
  2530. addParameterDeclaration(identifier) {
  2531. const name = identifier.name;
  2532. let variable = this.hoistedBodyVarScope.variables.get(name);
  2533. if (variable) {
  2534. variable.addDeclaration(identifier, null);
  2535. }
  2536. else {
  2537. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  2538. }
  2539. this.variables.set(name, variable);
  2540. return variable;
  2541. }
  2542. addParameterVariables(parameters, hasRest) {
  2543. this.parameters = parameters;
  2544. for (const parameterList of parameters) {
  2545. for (const parameter of parameterList) {
  2546. parameter.alwaysRendered = true;
  2547. }
  2548. }
  2549. this.hasRest = hasRest;
  2550. }
  2551. includeCallArguments(context, args) {
  2552. let calledFromTryStatement = false;
  2553. let argIncluded = false;
  2554. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  2555. for (const checkedArg of args) {
  2556. if (checkedArg instanceof SpreadElement) {
  2557. for (const arg of args) {
  2558. arg.include(context, false);
  2559. }
  2560. break;
  2561. }
  2562. }
  2563. for (let index = args.length - 1; index >= 0; index--) {
  2564. const paramVars = this.parameters[index] || restParam;
  2565. const arg = args[index];
  2566. if (paramVars) {
  2567. calledFromTryStatement = false;
  2568. for (const variable of paramVars) {
  2569. if (variable.included) {
  2570. argIncluded = true;
  2571. }
  2572. if (variable.calledFromTryStatement) {
  2573. calledFromTryStatement = true;
  2574. }
  2575. }
  2576. }
  2577. if (!argIncluded && arg.shouldBeIncluded(context)) {
  2578. argIncluded = true;
  2579. }
  2580. if (argIncluded) {
  2581. arg.include(context, calledFromTryStatement);
  2582. }
  2583. }
  2584. }
  2585. }
  2586. class ReturnValueScope extends ParameterScope {
  2587. constructor() {
  2588. super(...arguments);
  2589. this.returnExpression = null;
  2590. this.returnExpressions = [];
  2591. }
  2592. addReturnExpression(expression) {
  2593. this.returnExpressions.push(expression);
  2594. }
  2595. getReturnExpression() {
  2596. if (this.returnExpression === null)
  2597. this.updateReturnExpression();
  2598. return this.returnExpression;
  2599. }
  2600. updateReturnExpression() {
  2601. if (this.returnExpressions.length === 1) {
  2602. this.returnExpression = this.returnExpressions[0];
  2603. }
  2604. else {
  2605. this.returnExpression = UNKNOWN_EXPRESSION;
  2606. for (const expression of this.returnExpressions) {
  2607. expression.deoptimizePath(UNKNOWN_PATH);
  2608. }
  2609. }
  2610. }
  2611. }
  2612. class FunctionScope extends ReturnValueScope {
  2613. constructor(parent, context) {
  2614. super(parent, context);
  2615. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  2616. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  2617. }
  2618. findLexicalBoundary() {
  2619. return this;
  2620. }
  2621. includeCallArguments(context, args) {
  2622. super.includeCallArguments(context, args);
  2623. if (this.argumentsVariable.included) {
  2624. for (const arg of args) {
  2625. if (!arg.included) {
  2626. arg.include(context, false);
  2627. }
  2628. }
  2629. }
  2630. }
  2631. }
  2632. //@ts-check
  2633. /** @typedef { import('estree').Node} Node */
  2634. /** @typedef {Node | {
  2635. * type: 'PropertyDefinition';
  2636. * computed: boolean;
  2637. * value: Node
  2638. * }} NodeWithPropertyDefinition */
  2639. /**
  2640. *
  2641. * @param {NodeWithPropertyDefinition} node
  2642. * @param {NodeWithPropertyDefinition} parent
  2643. * @returns boolean
  2644. */
  2645. function is_reference (node, parent) {
  2646. if (node.type === 'MemberExpression') {
  2647. return !node.computed && is_reference(node.object, node);
  2648. }
  2649. if (node.type === 'Identifier') {
  2650. if (!parent) return true;
  2651. switch (parent.type) {
  2652. // disregard `bar` in `foo.bar`
  2653. case 'MemberExpression': return parent.computed || node === parent.object;
  2654. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  2655. case 'MethodDefinition': return parent.computed;
  2656. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  2657. case 'PropertyDefinition': return parent.computed || node === parent.value;
  2658. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  2659. case 'Property': return parent.computed || node === parent.value;
  2660. // disregard the `bar` in `export { foo as bar }` or
  2661. // the foo in `import { foo as bar }`
  2662. case 'ExportSpecifier':
  2663. case 'ImportSpecifier': return node === parent.local;
  2664. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  2665. case 'LabeledStatement':
  2666. case 'BreakStatement':
  2667. case 'ContinueStatement': return false;
  2668. default: return true;
  2669. }
  2670. }
  2671. return false;
  2672. }
  2673. const BLANK = Object.freeze(Object.create(null));
  2674. const EMPTY_OBJECT = Object.freeze({});
  2675. const EMPTY_ARRAY = Object.freeze([]);
  2676. const ValueProperties = Symbol('Value Properties');
  2677. const PURE = { pure: true };
  2678. const IMPURE = { pure: false };
  2679. // We use shortened variables to reduce file size here
  2680. /* OBJECT */
  2681. const O = {
  2682. // @ts-ignore
  2683. __proto__: null,
  2684. [ValueProperties]: IMPURE
  2685. };
  2686. /* PURE FUNCTION */
  2687. const PF = {
  2688. // @ts-ignore
  2689. __proto__: null,
  2690. [ValueProperties]: PURE
  2691. };
  2692. /* CONSTRUCTOR */
  2693. const C = {
  2694. // @ts-ignore
  2695. __proto__: null,
  2696. [ValueProperties]: IMPURE,
  2697. prototype: O
  2698. };
  2699. /* PURE CONSTRUCTOR */
  2700. const PC = {
  2701. // @ts-ignore
  2702. __proto__: null,
  2703. [ValueProperties]: PURE,
  2704. prototype: O
  2705. };
  2706. const ARRAY_TYPE = {
  2707. // @ts-ignore
  2708. __proto__: null,
  2709. [ValueProperties]: PURE,
  2710. from: PF,
  2711. of: PF,
  2712. prototype: O
  2713. };
  2714. const INTL_MEMBER = {
  2715. // @ts-ignore
  2716. __proto__: null,
  2717. [ValueProperties]: PURE,
  2718. supportedLocalesOf: PC
  2719. };
  2720. const knownGlobals = {
  2721. // Placeholders for global objects to avoid shape mutations
  2722. global: O,
  2723. globalThis: O,
  2724. self: O,
  2725. window: O,
  2726. // Common globals
  2727. // @ts-ignore
  2728. __proto__: null,
  2729. [ValueProperties]: IMPURE,
  2730. Array: {
  2731. // @ts-ignore
  2732. __proto__: null,
  2733. [ValueProperties]: IMPURE,
  2734. from: O,
  2735. isArray: PF,
  2736. of: PF,
  2737. prototype: O
  2738. },
  2739. ArrayBuffer: {
  2740. // @ts-ignore
  2741. __proto__: null,
  2742. [ValueProperties]: PURE,
  2743. isView: PF,
  2744. prototype: O
  2745. },
  2746. Atomics: O,
  2747. BigInt: C,
  2748. BigInt64Array: C,
  2749. BigUint64Array: C,
  2750. Boolean: PC,
  2751. // @ts-ignore
  2752. constructor: C,
  2753. DataView: PC,
  2754. Date: {
  2755. // @ts-ignore
  2756. __proto__: null,
  2757. [ValueProperties]: PURE,
  2758. now: PF,
  2759. parse: PF,
  2760. prototype: O,
  2761. UTC: PF
  2762. },
  2763. decodeURI: PF,
  2764. decodeURIComponent: PF,
  2765. encodeURI: PF,
  2766. encodeURIComponent: PF,
  2767. Error: PC,
  2768. escape: PF,
  2769. eval: O,
  2770. EvalError: PC,
  2771. Float32Array: ARRAY_TYPE,
  2772. Float64Array: ARRAY_TYPE,
  2773. Function: C,
  2774. // @ts-ignore
  2775. hasOwnProperty: O,
  2776. Infinity: O,
  2777. Int16Array: ARRAY_TYPE,
  2778. Int32Array: ARRAY_TYPE,
  2779. Int8Array: ARRAY_TYPE,
  2780. isFinite: PF,
  2781. isNaN: PF,
  2782. // @ts-ignore
  2783. isPrototypeOf: O,
  2784. JSON: O,
  2785. Map: PC,
  2786. Math: {
  2787. // @ts-ignore
  2788. __proto__: null,
  2789. [ValueProperties]: IMPURE,
  2790. abs: PF,
  2791. acos: PF,
  2792. acosh: PF,
  2793. asin: PF,
  2794. asinh: PF,
  2795. atan: PF,
  2796. atan2: PF,
  2797. atanh: PF,
  2798. cbrt: PF,
  2799. ceil: PF,
  2800. clz32: PF,
  2801. cos: PF,
  2802. cosh: PF,
  2803. exp: PF,
  2804. expm1: PF,
  2805. floor: PF,
  2806. fround: PF,
  2807. hypot: PF,
  2808. imul: PF,
  2809. log: PF,
  2810. log10: PF,
  2811. log1p: PF,
  2812. log2: PF,
  2813. max: PF,
  2814. min: PF,
  2815. pow: PF,
  2816. random: PF,
  2817. round: PF,
  2818. sign: PF,
  2819. sin: PF,
  2820. sinh: PF,
  2821. sqrt: PF,
  2822. tan: PF,
  2823. tanh: PF,
  2824. trunc: PF
  2825. },
  2826. NaN: O,
  2827. Number: {
  2828. // @ts-ignore
  2829. __proto__: null,
  2830. [ValueProperties]: PURE,
  2831. isFinite: PF,
  2832. isInteger: PF,
  2833. isNaN: PF,
  2834. isSafeInteger: PF,
  2835. parseFloat: PF,
  2836. parseInt: PF,
  2837. prototype: O
  2838. },
  2839. Object: {
  2840. // @ts-ignore
  2841. __proto__: null,
  2842. [ValueProperties]: PURE,
  2843. create: PF,
  2844. getNotifier: PF,
  2845. getOwn: PF,
  2846. getOwnPropertyDescriptor: PF,
  2847. getOwnPropertyNames: PF,
  2848. getOwnPropertySymbols: PF,
  2849. getPrototypeOf: PF,
  2850. is: PF,
  2851. isExtensible: PF,
  2852. isFrozen: PF,
  2853. isSealed: PF,
  2854. keys: PF,
  2855. prototype: O
  2856. },
  2857. parseFloat: PF,
  2858. parseInt: PF,
  2859. Promise: {
  2860. // @ts-ignore
  2861. __proto__: null,
  2862. [ValueProperties]: IMPURE,
  2863. all: PF,
  2864. prototype: O,
  2865. race: PF,
  2866. resolve: PF
  2867. },
  2868. // @ts-ignore
  2869. propertyIsEnumerable: O,
  2870. Proxy: O,
  2871. RangeError: PC,
  2872. ReferenceError: PC,
  2873. Reflect: O,
  2874. RegExp: PC,
  2875. Set: PC,
  2876. SharedArrayBuffer: C,
  2877. String: {
  2878. // @ts-ignore
  2879. __proto__: null,
  2880. [ValueProperties]: PURE,
  2881. fromCharCode: PF,
  2882. fromCodePoint: PF,
  2883. prototype: O,
  2884. raw: PF
  2885. },
  2886. Symbol: {
  2887. // @ts-ignore
  2888. __proto__: null,
  2889. [ValueProperties]: PURE,
  2890. for: PF,
  2891. keyFor: PF,
  2892. prototype: O
  2893. },
  2894. SyntaxError: PC,
  2895. // @ts-ignore
  2896. toLocaleString: O,
  2897. // @ts-ignore
  2898. toString: O,
  2899. TypeError: PC,
  2900. Uint16Array: ARRAY_TYPE,
  2901. Uint32Array: ARRAY_TYPE,
  2902. Uint8Array: ARRAY_TYPE,
  2903. Uint8ClampedArray: ARRAY_TYPE,
  2904. // Technically, this is a global, but it needs special handling
  2905. // undefined: ?,
  2906. unescape: PF,
  2907. URIError: PC,
  2908. // @ts-ignore
  2909. valueOf: O,
  2910. WeakMap: PC,
  2911. WeakSet: PC,
  2912. // Additional globals shared by Node and Browser that are not strictly part of the language
  2913. clearInterval: C,
  2914. clearTimeout: C,
  2915. console: O,
  2916. Intl: {
  2917. // @ts-ignore
  2918. __proto__: null,
  2919. [ValueProperties]: IMPURE,
  2920. Collator: INTL_MEMBER,
  2921. DateTimeFormat: INTL_MEMBER,
  2922. ListFormat: INTL_MEMBER,
  2923. NumberFormat: INTL_MEMBER,
  2924. PluralRules: INTL_MEMBER,
  2925. RelativeTimeFormat: INTL_MEMBER
  2926. },
  2927. setInterval: C,
  2928. setTimeout: C,
  2929. TextDecoder: C,
  2930. TextEncoder: C,
  2931. URL: C,
  2932. URLSearchParams: C,
  2933. // Browser specific globals
  2934. AbortController: C,
  2935. AbortSignal: C,
  2936. addEventListener: O,
  2937. alert: O,
  2938. AnalyserNode: C,
  2939. Animation: C,
  2940. AnimationEvent: C,
  2941. applicationCache: O,
  2942. ApplicationCache: C,
  2943. ApplicationCacheErrorEvent: C,
  2944. atob: O,
  2945. Attr: C,
  2946. Audio: C,
  2947. AudioBuffer: C,
  2948. AudioBufferSourceNode: C,
  2949. AudioContext: C,
  2950. AudioDestinationNode: C,
  2951. AudioListener: C,
  2952. AudioNode: C,
  2953. AudioParam: C,
  2954. AudioProcessingEvent: C,
  2955. AudioScheduledSourceNode: C,
  2956. AudioWorkletNode: C,
  2957. BarProp: C,
  2958. BaseAudioContext: C,
  2959. BatteryManager: C,
  2960. BeforeUnloadEvent: C,
  2961. BiquadFilterNode: C,
  2962. Blob: C,
  2963. BlobEvent: C,
  2964. blur: O,
  2965. BroadcastChannel: C,
  2966. btoa: O,
  2967. ByteLengthQueuingStrategy: C,
  2968. Cache: C,
  2969. caches: O,
  2970. CacheStorage: C,
  2971. cancelAnimationFrame: O,
  2972. cancelIdleCallback: O,
  2973. CanvasCaptureMediaStreamTrack: C,
  2974. CanvasGradient: C,
  2975. CanvasPattern: C,
  2976. CanvasRenderingContext2D: C,
  2977. ChannelMergerNode: C,
  2978. ChannelSplitterNode: C,
  2979. CharacterData: C,
  2980. clientInformation: O,
  2981. ClipboardEvent: C,
  2982. close: O,
  2983. closed: O,
  2984. CloseEvent: C,
  2985. Comment: C,
  2986. CompositionEvent: C,
  2987. confirm: O,
  2988. ConstantSourceNode: C,
  2989. ConvolverNode: C,
  2990. CountQueuingStrategy: C,
  2991. createImageBitmap: O,
  2992. Credential: C,
  2993. CredentialsContainer: C,
  2994. crypto: O,
  2995. Crypto: C,
  2996. CryptoKey: C,
  2997. CSS: C,
  2998. CSSConditionRule: C,
  2999. CSSFontFaceRule: C,
  3000. CSSGroupingRule: C,
  3001. CSSImportRule: C,
  3002. CSSKeyframeRule: C,
  3003. CSSKeyframesRule: C,
  3004. CSSMediaRule: C,
  3005. CSSNamespaceRule: C,
  3006. CSSPageRule: C,
  3007. CSSRule: C,
  3008. CSSRuleList: C,
  3009. CSSStyleDeclaration: C,
  3010. CSSStyleRule: C,
  3011. CSSStyleSheet: C,
  3012. CSSSupportsRule: C,
  3013. CustomElementRegistry: C,
  3014. customElements: O,
  3015. CustomEvent: C,
  3016. DataTransfer: C,
  3017. DataTransferItem: C,
  3018. DataTransferItemList: C,
  3019. defaultstatus: O,
  3020. defaultStatus: O,
  3021. DelayNode: C,
  3022. DeviceMotionEvent: C,
  3023. DeviceOrientationEvent: C,
  3024. devicePixelRatio: O,
  3025. dispatchEvent: O,
  3026. document: O,
  3027. Document: C,
  3028. DocumentFragment: C,
  3029. DocumentType: C,
  3030. DOMError: C,
  3031. DOMException: C,
  3032. DOMImplementation: C,
  3033. DOMMatrix: C,
  3034. DOMMatrixReadOnly: C,
  3035. DOMParser: C,
  3036. DOMPoint: C,
  3037. DOMPointReadOnly: C,
  3038. DOMQuad: C,
  3039. DOMRect: C,
  3040. DOMRectReadOnly: C,
  3041. DOMStringList: C,
  3042. DOMStringMap: C,
  3043. DOMTokenList: C,
  3044. DragEvent: C,
  3045. DynamicsCompressorNode: C,
  3046. Element: C,
  3047. ErrorEvent: C,
  3048. Event: C,
  3049. EventSource: C,
  3050. EventTarget: C,
  3051. external: O,
  3052. fetch: O,
  3053. File: C,
  3054. FileList: C,
  3055. FileReader: C,
  3056. find: O,
  3057. focus: O,
  3058. FocusEvent: C,
  3059. FontFace: C,
  3060. FontFaceSetLoadEvent: C,
  3061. FormData: C,
  3062. frames: O,
  3063. GainNode: C,
  3064. Gamepad: C,
  3065. GamepadButton: C,
  3066. GamepadEvent: C,
  3067. getComputedStyle: O,
  3068. getSelection: O,
  3069. HashChangeEvent: C,
  3070. Headers: C,
  3071. history: O,
  3072. History: C,
  3073. HTMLAllCollection: C,
  3074. HTMLAnchorElement: C,
  3075. HTMLAreaElement: C,
  3076. HTMLAudioElement: C,
  3077. HTMLBaseElement: C,
  3078. HTMLBodyElement: C,
  3079. HTMLBRElement: C,
  3080. HTMLButtonElement: C,
  3081. HTMLCanvasElement: C,
  3082. HTMLCollection: C,
  3083. HTMLContentElement: C,
  3084. HTMLDataElement: C,
  3085. HTMLDataListElement: C,
  3086. HTMLDetailsElement: C,
  3087. HTMLDialogElement: C,
  3088. HTMLDirectoryElement: C,
  3089. HTMLDivElement: C,
  3090. HTMLDListElement: C,
  3091. HTMLDocument: C,
  3092. HTMLElement: C,
  3093. HTMLEmbedElement: C,
  3094. HTMLFieldSetElement: C,
  3095. HTMLFontElement: C,
  3096. HTMLFormControlsCollection: C,
  3097. HTMLFormElement: C,
  3098. HTMLFrameElement: C,
  3099. HTMLFrameSetElement: C,
  3100. HTMLHeadElement: C,
  3101. HTMLHeadingElement: C,
  3102. HTMLHRElement: C,
  3103. HTMLHtmlElement: C,
  3104. HTMLIFrameElement: C,
  3105. HTMLImageElement: C,
  3106. HTMLInputElement: C,
  3107. HTMLLabelElement: C,
  3108. HTMLLegendElement: C,
  3109. HTMLLIElement: C,
  3110. HTMLLinkElement: C,
  3111. HTMLMapElement: C,
  3112. HTMLMarqueeElement: C,
  3113. HTMLMediaElement: C,
  3114. HTMLMenuElement: C,
  3115. HTMLMetaElement: C,
  3116. HTMLMeterElement: C,
  3117. HTMLModElement: C,
  3118. HTMLObjectElement: C,
  3119. HTMLOListElement: C,
  3120. HTMLOptGroupElement: C,
  3121. HTMLOptionElement: C,
  3122. HTMLOptionsCollection: C,
  3123. HTMLOutputElement: C,
  3124. HTMLParagraphElement: C,
  3125. HTMLParamElement: C,
  3126. HTMLPictureElement: C,
  3127. HTMLPreElement: C,
  3128. HTMLProgressElement: C,
  3129. HTMLQuoteElement: C,
  3130. HTMLScriptElement: C,
  3131. HTMLSelectElement: C,
  3132. HTMLShadowElement: C,
  3133. HTMLSlotElement: C,
  3134. HTMLSourceElement: C,
  3135. HTMLSpanElement: C,
  3136. HTMLStyleElement: C,
  3137. HTMLTableCaptionElement: C,
  3138. HTMLTableCellElement: C,
  3139. HTMLTableColElement: C,
  3140. HTMLTableElement: C,
  3141. HTMLTableRowElement: C,
  3142. HTMLTableSectionElement: C,
  3143. HTMLTemplateElement: C,
  3144. HTMLTextAreaElement: C,
  3145. HTMLTimeElement: C,
  3146. HTMLTitleElement: C,
  3147. HTMLTrackElement: C,
  3148. HTMLUListElement: C,
  3149. HTMLUnknownElement: C,
  3150. HTMLVideoElement: C,
  3151. IDBCursor: C,
  3152. IDBCursorWithValue: C,
  3153. IDBDatabase: C,
  3154. IDBFactory: C,
  3155. IDBIndex: C,
  3156. IDBKeyRange: C,
  3157. IDBObjectStore: C,
  3158. IDBOpenDBRequest: C,
  3159. IDBRequest: C,
  3160. IDBTransaction: C,
  3161. IDBVersionChangeEvent: C,
  3162. IdleDeadline: C,
  3163. IIRFilterNode: C,
  3164. Image: C,
  3165. ImageBitmap: C,
  3166. ImageBitmapRenderingContext: C,
  3167. ImageCapture: C,
  3168. ImageData: C,
  3169. indexedDB: O,
  3170. innerHeight: O,
  3171. innerWidth: O,
  3172. InputEvent: C,
  3173. IntersectionObserver: C,
  3174. IntersectionObserverEntry: C,
  3175. isSecureContext: O,
  3176. KeyboardEvent: C,
  3177. KeyframeEffect: C,
  3178. length: O,
  3179. localStorage: O,
  3180. location: O,
  3181. Location: C,
  3182. locationbar: O,
  3183. matchMedia: O,
  3184. MediaDeviceInfo: C,
  3185. MediaDevices: C,
  3186. MediaElementAudioSourceNode: C,
  3187. MediaEncryptedEvent: C,
  3188. MediaError: C,
  3189. MediaKeyMessageEvent: C,
  3190. MediaKeySession: C,
  3191. MediaKeyStatusMap: C,
  3192. MediaKeySystemAccess: C,
  3193. MediaList: C,
  3194. MediaQueryList: C,
  3195. MediaQueryListEvent: C,
  3196. MediaRecorder: C,
  3197. MediaSettingsRange: C,
  3198. MediaSource: C,
  3199. MediaStream: C,
  3200. MediaStreamAudioDestinationNode: C,
  3201. MediaStreamAudioSourceNode: C,
  3202. MediaStreamEvent: C,
  3203. MediaStreamTrack: C,
  3204. MediaStreamTrackEvent: C,
  3205. menubar: O,
  3206. MessageChannel: C,
  3207. MessageEvent: C,
  3208. MessagePort: C,
  3209. MIDIAccess: C,
  3210. MIDIConnectionEvent: C,
  3211. MIDIInput: C,
  3212. MIDIInputMap: C,
  3213. MIDIMessageEvent: C,
  3214. MIDIOutput: C,
  3215. MIDIOutputMap: C,
  3216. MIDIPort: C,
  3217. MimeType: C,
  3218. MimeTypeArray: C,
  3219. MouseEvent: C,
  3220. moveBy: O,
  3221. moveTo: O,
  3222. MutationEvent: C,
  3223. MutationObserver: C,
  3224. MutationRecord: C,
  3225. name: O,
  3226. NamedNodeMap: C,
  3227. NavigationPreloadManager: C,
  3228. navigator: O,
  3229. Navigator: C,
  3230. NetworkInformation: C,
  3231. Node: C,
  3232. NodeFilter: O,
  3233. NodeIterator: C,
  3234. NodeList: C,
  3235. Notification: C,
  3236. OfflineAudioCompletionEvent: C,
  3237. OfflineAudioContext: C,
  3238. offscreenBuffering: O,
  3239. OffscreenCanvas: C,
  3240. open: O,
  3241. openDatabase: O,
  3242. Option: C,
  3243. origin: O,
  3244. OscillatorNode: C,
  3245. outerHeight: O,
  3246. outerWidth: O,
  3247. PageTransitionEvent: C,
  3248. pageXOffset: O,
  3249. pageYOffset: O,
  3250. PannerNode: C,
  3251. parent: O,
  3252. Path2D: C,
  3253. PaymentAddress: C,
  3254. PaymentRequest: C,
  3255. PaymentRequestUpdateEvent: C,
  3256. PaymentResponse: C,
  3257. performance: O,
  3258. Performance: C,
  3259. PerformanceEntry: C,
  3260. PerformanceLongTaskTiming: C,
  3261. PerformanceMark: C,
  3262. PerformanceMeasure: C,
  3263. PerformanceNavigation: C,
  3264. PerformanceNavigationTiming: C,
  3265. PerformanceObserver: C,
  3266. PerformanceObserverEntryList: C,
  3267. PerformancePaintTiming: C,
  3268. PerformanceResourceTiming: C,
  3269. PerformanceTiming: C,
  3270. PeriodicWave: C,
  3271. Permissions: C,
  3272. PermissionStatus: C,
  3273. personalbar: O,
  3274. PhotoCapabilities: C,
  3275. Plugin: C,
  3276. PluginArray: C,
  3277. PointerEvent: C,
  3278. PopStateEvent: C,
  3279. postMessage: O,
  3280. Presentation: C,
  3281. PresentationAvailability: C,
  3282. PresentationConnection: C,
  3283. PresentationConnectionAvailableEvent: C,
  3284. PresentationConnectionCloseEvent: C,
  3285. PresentationConnectionList: C,
  3286. PresentationReceiver: C,
  3287. PresentationRequest: C,
  3288. print: O,
  3289. ProcessingInstruction: C,
  3290. ProgressEvent: C,
  3291. PromiseRejectionEvent: C,
  3292. prompt: O,
  3293. PushManager: C,
  3294. PushSubscription: C,
  3295. PushSubscriptionOptions: C,
  3296. queueMicrotask: O,
  3297. RadioNodeList: C,
  3298. Range: C,
  3299. ReadableStream: C,
  3300. RemotePlayback: C,
  3301. removeEventListener: O,
  3302. Request: C,
  3303. requestAnimationFrame: O,
  3304. requestIdleCallback: O,
  3305. resizeBy: O,
  3306. ResizeObserver: C,
  3307. ResizeObserverEntry: C,
  3308. resizeTo: O,
  3309. Response: C,
  3310. RTCCertificate: C,
  3311. RTCDataChannel: C,
  3312. RTCDataChannelEvent: C,
  3313. RTCDtlsTransport: C,
  3314. RTCIceCandidate: C,
  3315. RTCIceTransport: C,
  3316. RTCPeerConnection: C,
  3317. RTCPeerConnectionIceEvent: C,
  3318. RTCRtpReceiver: C,
  3319. RTCRtpSender: C,
  3320. RTCSctpTransport: C,
  3321. RTCSessionDescription: C,
  3322. RTCStatsReport: C,
  3323. RTCTrackEvent: C,
  3324. screen: O,
  3325. Screen: C,
  3326. screenLeft: O,
  3327. ScreenOrientation: C,
  3328. screenTop: O,
  3329. screenX: O,
  3330. screenY: O,
  3331. ScriptProcessorNode: C,
  3332. scroll: O,
  3333. scrollbars: O,
  3334. scrollBy: O,
  3335. scrollTo: O,
  3336. scrollX: O,
  3337. scrollY: O,
  3338. SecurityPolicyViolationEvent: C,
  3339. Selection: C,
  3340. ServiceWorker: C,
  3341. ServiceWorkerContainer: C,
  3342. ServiceWorkerRegistration: C,
  3343. sessionStorage: O,
  3344. ShadowRoot: C,
  3345. SharedWorker: C,
  3346. SourceBuffer: C,
  3347. SourceBufferList: C,
  3348. speechSynthesis: O,
  3349. SpeechSynthesisEvent: C,
  3350. SpeechSynthesisUtterance: C,
  3351. StaticRange: C,
  3352. status: O,
  3353. statusbar: O,
  3354. StereoPannerNode: C,
  3355. stop: O,
  3356. Storage: C,
  3357. StorageEvent: C,
  3358. StorageManager: C,
  3359. styleMedia: O,
  3360. StyleSheet: C,
  3361. StyleSheetList: C,
  3362. SubtleCrypto: C,
  3363. SVGAElement: C,
  3364. SVGAngle: C,
  3365. SVGAnimatedAngle: C,
  3366. SVGAnimatedBoolean: C,
  3367. SVGAnimatedEnumeration: C,
  3368. SVGAnimatedInteger: C,
  3369. SVGAnimatedLength: C,
  3370. SVGAnimatedLengthList: C,
  3371. SVGAnimatedNumber: C,
  3372. SVGAnimatedNumberList: C,
  3373. SVGAnimatedPreserveAspectRatio: C,
  3374. SVGAnimatedRect: C,
  3375. SVGAnimatedString: C,
  3376. SVGAnimatedTransformList: C,
  3377. SVGAnimateElement: C,
  3378. SVGAnimateMotionElement: C,
  3379. SVGAnimateTransformElement: C,
  3380. SVGAnimationElement: C,
  3381. SVGCircleElement: C,
  3382. SVGClipPathElement: C,
  3383. SVGComponentTransferFunctionElement: C,
  3384. SVGDefsElement: C,
  3385. SVGDescElement: C,
  3386. SVGDiscardElement: C,
  3387. SVGElement: C,
  3388. SVGEllipseElement: C,
  3389. SVGFEBlendElement: C,
  3390. SVGFEColorMatrixElement: C,
  3391. SVGFEComponentTransferElement: C,
  3392. SVGFECompositeElement: C,
  3393. SVGFEConvolveMatrixElement: C,
  3394. SVGFEDiffuseLightingElement: C,
  3395. SVGFEDisplacementMapElement: C,
  3396. SVGFEDistantLightElement: C,
  3397. SVGFEDropShadowElement: C,
  3398. SVGFEFloodElement: C,
  3399. SVGFEFuncAElement: C,
  3400. SVGFEFuncBElement: C,
  3401. SVGFEFuncGElement: C,
  3402. SVGFEFuncRElement: C,
  3403. SVGFEGaussianBlurElement: C,
  3404. SVGFEImageElement: C,
  3405. SVGFEMergeElement: C,
  3406. SVGFEMergeNodeElement: C,
  3407. SVGFEMorphologyElement: C,
  3408. SVGFEOffsetElement: C,
  3409. SVGFEPointLightElement: C,
  3410. SVGFESpecularLightingElement: C,
  3411. SVGFESpotLightElement: C,
  3412. SVGFETileElement: C,
  3413. SVGFETurbulenceElement: C,
  3414. SVGFilterElement: C,
  3415. SVGForeignObjectElement: C,
  3416. SVGGElement: C,
  3417. SVGGeometryElement: C,
  3418. SVGGradientElement: C,
  3419. SVGGraphicsElement: C,
  3420. SVGImageElement: C,
  3421. SVGLength: C,
  3422. SVGLengthList: C,
  3423. SVGLinearGradientElement: C,
  3424. SVGLineElement: C,
  3425. SVGMarkerElement: C,
  3426. SVGMaskElement: C,
  3427. SVGMatrix: C,
  3428. SVGMetadataElement: C,
  3429. SVGMPathElement: C,
  3430. SVGNumber: C,
  3431. SVGNumberList: C,
  3432. SVGPathElement: C,
  3433. SVGPatternElement: C,
  3434. SVGPoint: C,
  3435. SVGPointList: C,
  3436. SVGPolygonElement: C,
  3437. SVGPolylineElement: C,
  3438. SVGPreserveAspectRatio: C,
  3439. SVGRadialGradientElement: C,
  3440. SVGRect: C,
  3441. SVGRectElement: C,
  3442. SVGScriptElement: C,
  3443. SVGSetElement: C,
  3444. SVGStopElement: C,
  3445. SVGStringList: C,
  3446. SVGStyleElement: C,
  3447. SVGSVGElement: C,
  3448. SVGSwitchElement: C,
  3449. SVGSymbolElement: C,
  3450. SVGTextContentElement: C,
  3451. SVGTextElement: C,
  3452. SVGTextPathElement: C,
  3453. SVGTextPositioningElement: C,
  3454. SVGTitleElement: C,
  3455. SVGTransform: C,
  3456. SVGTransformList: C,
  3457. SVGTSpanElement: C,
  3458. SVGUnitTypes: C,
  3459. SVGUseElement: C,
  3460. SVGViewElement: C,
  3461. TaskAttributionTiming: C,
  3462. Text: C,
  3463. TextEvent: C,
  3464. TextMetrics: C,
  3465. TextTrack: C,
  3466. TextTrackCue: C,
  3467. TextTrackCueList: C,
  3468. TextTrackList: C,
  3469. TimeRanges: C,
  3470. toolbar: O,
  3471. top: O,
  3472. Touch: C,
  3473. TouchEvent: C,
  3474. TouchList: C,
  3475. TrackEvent: C,
  3476. TransitionEvent: C,
  3477. TreeWalker: C,
  3478. UIEvent: C,
  3479. ValidityState: C,
  3480. visualViewport: O,
  3481. VisualViewport: C,
  3482. VTTCue: C,
  3483. WaveShaperNode: C,
  3484. WebAssembly: O,
  3485. WebGL2RenderingContext: C,
  3486. WebGLActiveInfo: C,
  3487. WebGLBuffer: C,
  3488. WebGLContextEvent: C,
  3489. WebGLFramebuffer: C,
  3490. WebGLProgram: C,
  3491. WebGLQuery: C,
  3492. WebGLRenderbuffer: C,
  3493. WebGLRenderingContext: C,
  3494. WebGLSampler: C,
  3495. WebGLShader: C,
  3496. WebGLShaderPrecisionFormat: C,
  3497. WebGLSync: C,
  3498. WebGLTexture: C,
  3499. WebGLTransformFeedback: C,
  3500. WebGLUniformLocation: C,
  3501. WebGLVertexArrayObject: C,
  3502. WebSocket: C,
  3503. WheelEvent: C,
  3504. Window: C,
  3505. Worker: C,
  3506. WritableStream: C,
  3507. XMLDocument: C,
  3508. XMLHttpRequest: C,
  3509. XMLHttpRequestEventTarget: C,
  3510. XMLHttpRequestUpload: C,
  3511. XMLSerializer: C,
  3512. XPathEvaluator: C,
  3513. XPathExpression: C,
  3514. XPathResult: C,
  3515. XSLTProcessor: C
  3516. };
  3517. for (const global of ['window', 'global', 'self', 'globalThis']) {
  3518. knownGlobals[global] = knownGlobals;
  3519. }
  3520. function getGlobalAtPath(path) {
  3521. let currentGlobal = knownGlobals;
  3522. for (const pathSegment of path) {
  3523. if (typeof pathSegment !== 'string') {
  3524. return null;
  3525. }
  3526. currentGlobal = currentGlobal[pathSegment];
  3527. if (!currentGlobal) {
  3528. return null;
  3529. }
  3530. }
  3531. return currentGlobal[ValueProperties];
  3532. }
  3533. function isPureGlobal(path) {
  3534. const globalAtPath = getGlobalAtPath(path);
  3535. return globalAtPath !== null && globalAtPath.pure;
  3536. }
  3537. function isGlobalMember(path) {
  3538. if (path.length === 1) {
  3539. return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
  3540. }
  3541. return getGlobalAtPath(path.slice(0, -1)) !== null;
  3542. }
  3543. class GlobalVariable extends Variable {
  3544. constructor() {
  3545. super(...arguments);
  3546. this.isReassigned = true;
  3547. }
  3548. hasEffectsWhenAccessedAtPath(path) {
  3549. return !isGlobalMember([this.name, ...path]);
  3550. }
  3551. hasEffectsWhenCalledAtPath(path) {
  3552. return !isPureGlobal([this.name, ...path]);
  3553. }
  3554. }
  3555. class Identifier extends NodeBase {
  3556. constructor() {
  3557. super(...arguments);
  3558. this.variable = null;
  3559. this.bound = false;
  3560. }
  3561. addExportedVariables(variables, exportNamesByVariable) {
  3562. if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
  3563. variables.push(this.variable);
  3564. }
  3565. }
  3566. bind() {
  3567. if (this.bound)
  3568. return;
  3569. this.bound = true;
  3570. if (this.variable === null && is_reference(this, this.parent)) {
  3571. this.variable = this.scope.findVariable(this.name);
  3572. this.variable.addReference(this);
  3573. }
  3574. if (this.variable !== null &&
  3575. this.variable instanceof LocalVariable &&
  3576. this.variable.additionalInitializers !== null) {
  3577. this.variable.consolidateInitializers();
  3578. }
  3579. }
  3580. declare(kind, init) {
  3581. let variable;
  3582. switch (kind) {
  3583. case 'var':
  3584. variable = this.scope.addDeclaration(this, this.context, init, true);
  3585. break;
  3586. case 'function':
  3587. // in strict mode, functions are only hoisted within a scope but not across block scopes
  3588. variable = this.scope.addDeclaration(this, this.context, init, false);
  3589. break;
  3590. case 'let':
  3591. case 'const':
  3592. case 'class':
  3593. variable = this.scope.addDeclaration(this, this.context, init, false);
  3594. break;
  3595. case 'parameter':
  3596. variable = this.scope.addParameterDeclaration(this);
  3597. break;
  3598. /* istanbul ignore next */
  3599. default:
  3600. /* istanbul ignore next */
  3601. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  3602. }
  3603. return [(this.variable = variable)];
  3604. }
  3605. deoptimizePath(path) {
  3606. if (!this.bound)
  3607. this.bind();
  3608. if (path.length === 0 && !this.scope.contains(this.name)) {
  3609. this.disallowImportReassignment();
  3610. }
  3611. this.variable.deoptimizePath(path);
  3612. }
  3613. getLiteralValueAtPath(path, recursionTracker, origin) {
  3614. if (!this.bound)
  3615. this.bind();
  3616. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  3617. }
  3618. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  3619. if (!this.bound)
  3620. this.bind();
  3621. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  3622. }
  3623. hasEffects() {
  3624. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  3625. this.variable instanceof GlobalVariable &&
  3626. this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
  3627. }
  3628. hasEffectsWhenAccessedAtPath(path, context) {
  3629. return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  3630. }
  3631. hasEffectsWhenAssignedAtPath(path, context) {
  3632. return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
  3633. }
  3634. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3635. return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  3636. }
  3637. include() {
  3638. if (!this.included) {
  3639. this.included = true;
  3640. if (this.variable !== null) {
  3641. this.context.includeVariableInModule(this.variable);
  3642. }
  3643. }
  3644. }
  3645. includeCallArguments(context, args) {
  3646. this.variable.includeCallArguments(context, args);
  3647. }
  3648. render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  3649. if (this.variable) {
  3650. const name = this.variable.getName();
  3651. if (name !== this.name) {
  3652. code.overwrite(this.start, this.end, name, {
  3653. contentOnly: true,
  3654. storeName: true
  3655. });
  3656. if (isShorthandProperty) {
  3657. code.prependRight(this.start, `${this.name}: `);
  3658. }
  3659. }
  3660. // In strict mode, any variable named "eval" must be the actual "eval" function
  3661. if (name === 'eval' &&
  3662. renderedParentType === CallExpression$1 &&
  3663. isCalleeOfRenderedParent) {
  3664. code.appendRight(this.start, '0, ');
  3665. }
  3666. }
  3667. }
  3668. disallowImportReassignment() {
  3669. return this.context.error({
  3670. code: 'ILLEGAL_REASSIGNMENT',
  3671. message: `Illegal reassignment to import '${this.name}'`
  3672. }, this.start);
  3673. }
  3674. }
  3675. class RestElement extends NodeBase {
  3676. constructor() {
  3677. super(...arguments);
  3678. this.declarationInit = null;
  3679. }
  3680. addExportedVariables(variables, exportNamesByVariable) {
  3681. this.argument.addExportedVariables(variables, exportNamesByVariable);
  3682. }
  3683. bind() {
  3684. super.bind();
  3685. if (this.declarationInit !== null) {
  3686. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  3687. }
  3688. }
  3689. declare(kind, init) {
  3690. this.declarationInit = init;
  3691. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  3692. }
  3693. deoptimizePath(path) {
  3694. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  3695. }
  3696. hasEffectsWhenAssignedAtPath(path, context) {
  3697. return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  3698. }
  3699. }
  3700. class FunctionNode extends NodeBase {
  3701. constructor() {
  3702. super(...arguments);
  3703. this.isPrototypeDeoptimized = false;
  3704. }
  3705. createScope(parentScope) {
  3706. this.scope = new FunctionScope(parentScope, this.context);
  3707. }
  3708. deoptimizePath(path) {
  3709. if (path.length === 1) {
  3710. if (path[0] === 'prototype') {
  3711. this.isPrototypeDeoptimized = true;
  3712. }
  3713. else if (path[0] === UnknownKey) {
  3714. this.isPrototypeDeoptimized = true;
  3715. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  3716. // which means the return expression needs to be reassigned as well
  3717. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  3718. }
  3719. }
  3720. }
  3721. getReturnExpressionWhenCalledAtPath(path) {
  3722. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  3723. }
  3724. hasEffects() {
  3725. return this.id !== null && this.id.hasEffects();
  3726. }
  3727. hasEffectsWhenAccessedAtPath(path) {
  3728. if (path.length <= 1)
  3729. return false;
  3730. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  3731. }
  3732. hasEffectsWhenAssignedAtPath(path) {
  3733. if (path.length <= 1) {
  3734. return false;
  3735. }
  3736. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  3737. }
  3738. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3739. if (path.length > 0)
  3740. return true;
  3741. for (const param of this.params) {
  3742. if (param.hasEffects(context))
  3743. return true;
  3744. }
  3745. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  3746. context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
  3747. const { brokenFlow, ignore } = context;
  3748. context.ignore = {
  3749. breaks: false,
  3750. continues: false,
  3751. labels: new Set(),
  3752. returnAwaitYield: true
  3753. };
  3754. if (this.body.hasEffects(context))
  3755. return true;
  3756. context.brokenFlow = brokenFlow;
  3757. if (thisInit) {
  3758. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  3759. }
  3760. else {
  3761. context.replacedVariableInits.delete(this.scope.thisVariable);
  3762. }
  3763. context.ignore = ignore;
  3764. return false;
  3765. }
  3766. include(context, includeChildrenRecursively) {
  3767. this.included = true;
  3768. if (this.id)
  3769. this.id.include();
  3770. const hasArguments = this.scope.argumentsVariable.included;
  3771. for (const param of this.params) {
  3772. if (!(param instanceof Identifier) || hasArguments) {
  3773. param.include(context, includeChildrenRecursively);
  3774. }
  3775. }
  3776. const { brokenFlow } = context;
  3777. context.brokenFlow = BROKEN_FLOW_NONE;
  3778. this.body.include(context, includeChildrenRecursively);
  3779. context.brokenFlow = brokenFlow;
  3780. }
  3781. includeCallArguments(context, args) {
  3782. this.scope.includeCallArguments(context, args);
  3783. }
  3784. initialise() {
  3785. if (this.id !== null) {
  3786. this.id.declare('function', this);
  3787. }
  3788. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  3789. this.body.addImplicitReturnExpressionToScope();
  3790. }
  3791. parseNode(esTreeNode) {
  3792. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  3793. super.parseNode(esTreeNode);
  3794. }
  3795. }
  3796. FunctionNode.prototype.preventChildBlockScope = true;
  3797. class FunctionDeclaration extends FunctionNode {
  3798. initialise() {
  3799. super.initialise();
  3800. if (this.id !== null) {
  3801. this.id.variable.isId = true;
  3802. }
  3803. }
  3804. parseNode(esTreeNode) {
  3805. if (esTreeNode.id !== null) {
  3806. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
  3807. .parent);
  3808. }
  3809. super.parseNode(esTreeNode);
  3810. }
  3811. }
  3812. // The header ends at the first non-white-space after "default"
  3813. function getDeclarationStart(code, start) {
  3814. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  3815. }
  3816. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  3817. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  3818. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  3819. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  3820. if (generatorStarPos === -1) {
  3821. return declarationEnd;
  3822. }
  3823. return declarationEnd + generatorStarPos + 1;
  3824. }
  3825. class ExportDefaultDeclaration extends NodeBase {
  3826. include(context, includeChildrenRecursively) {
  3827. super.include(context, includeChildrenRecursively);
  3828. if (includeChildrenRecursively) {
  3829. this.context.includeVariableInModule(this.variable);
  3830. }
  3831. }
  3832. initialise() {
  3833. const declaration = this.declaration;
  3834. this.declarationName =
  3835. (declaration.id && declaration.id.name) || this.declaration.name;
  3836. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  3837. this.context.addExport(this);
  3838. }
  3839. render(code, options, nodeRenderOptions) {
  3840. const { start, end } = nodeRenderOptions;
  3841. const declarationStart = getDeclarationStart(code.original, this.start);
  3842. if (this.declaration instanceof FunctionDeclaration) {
  3843. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  3844. }
  3845. else if (this.declaration instanceof ClassDeclaration) {
  3846. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  3847. }
  3848. else if (this.variable.getOriginalVariable() !== this.variable) {
  3849. // Remove altogether to prevent re-declaring the same variable
  3850. treeshakeNode(this, code, start, end);
  3851. return;
  3852. }
  3853. else if (this.variable.included) {
  3854. this.renderVariableDeclaration(code, declarationStart, options);
  3855. }
  3856. else {
  3857. code.remove(this.start, declarationStart);
  3858. this.declaration.render(code, options, {
  3859. isCalleeOfRenderedParent: false,
  3860. renderedParentType: ExpressionStatement$1
  3861. });
  3862. if (code.original[this.end - 1] !== ';') {
  3863. code.appendLeft(this.end, ';');
  3864. }
  3865. return;
  3866. }
  3867. this.declaration.render(code, options);
  3868. }
  3869. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  3870. const name = this.variable.getName();
  3871. // Remove `export default`
  3872. code.remove(this.start, declarationStart);
  3873. if (needsId) {
  3874. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  3875. }
  3876. if (options.format === 'system' &&
  3877. this.declaration instanceof ClassDeclaration &&
  3878. options.exportNamesByVariable.has(this.variable)) {
  3879. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  3880. }
  3881. }
  3882. renderVariableDeclaration(code, declarationStart, options) {
  3883. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  3884. const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
  3885. if (systemExportNames) {
  3886. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
  3887. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  3888. }
  3889. else {
  3890. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
  3891. if (!hasTrailingSemicolon) {
  3892. code.appendLeft(this.end, ';');
  3893. }
  3894. }
  3895. }
  3896. }
  3897. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  3898. class UndefinedVariable extends Variable {
  3899. constructor() {
  3900. super('undefined');
  3901. }
  3902. getLiteralValueAtPath() {
  3903. return undefined;
  3904. }
  3905. }
  3906. class ExportDefaultVariable extends LocalVariable {
  3907. constructor(name, exportDefaultDeclaration, context) {
  3908. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  3909. this.hasId = false;
  3910. this.originalId = null;
  3911. this.originalVariable = null;
  3912. const declaration = exportDefaultDeclaration.declaration;
  3913. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  3914. declaration.id) {
  3915. this.hasId = true;
  3916. this.originalId = declaration.id;
  3917. }
  3918. else if (declaration instanceof Identifier) {
  3919. this.originalId = declaration;
  3920. }
  3921. }
  3922. addReference(identifier) {
  3923. if (!this.hasId) {
  3924. this.name = identifier.name;
  3925. }
  3926. }
  3927. getAssignedVariableName() {
  3928. return (this.originalId && this.originalId.name) || null;
  3929. }
  3930. getBaseVariableName() {
  3931. const original = this.getOriginalVariable();
  3932. if (original === this) {
  3933. return super.getBaseVariableName();
  3934. }
  3935. else {
  3936. return original.getBaseVariableName();
  3937. }
  3938. }
  3939. getDirectOriginalVariable() {
  3940. return this.originalId &&
  3941. (this.hasId ||
  3942. !(this.originalId.variable.isReassigned ||
  3943. this.originalId.variable instanceof UndefinedVariable ||
  3944. // this avoids a circular dependency
  3945. 'syntheticNamespace' in this.originalId.variable))
  3946. ? this.originalId.variable
  3947. : null;
  3948. }
  3949. getName() {
  3950. const original = this.getOriginalVariable();
  3951. if (original === this) {
  3952. return super.getName();
  3953. }
  3954. else {
  3955. return original.getName();
  3956. }
  3957. }
  3958. getOriginalVariable() {
  3959. if (this.originalVariable)
  3960. return this.originalVariable;
  3961. let original = this;
  3962. let currentVariable;
  3963. const checkedVariables = new Set();
  3964. do {
  3965. checkedVariables.add(original);
  3966. currentVariable = original;
  3967. original = currentVariable.getDirectOriginalVariable();
  3968. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  3969. return (this.originalVariable = original || currentVariable);
  3970. }
  3971. }
  3972. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  3973. class ExportShimVariable extends Variable {
  3974. constructor(module) {
  3975. super(MISSING_EXPORT_SHIM_VARIABLE);
  3976. this.module = module;
  3977. }
  3978. }
  3979. class NamespaceVariable extends Variable {
  3980. constructor(context, syntheticNamedExports) {
  3981. super(context.getModuleName());
  3982. this.memberVariables = null;
  3983. this.mergedNamespaces = [];
  3984. this.referencedEarly = false;
  3985. this.references = [];
  3986. this.context = context;
  3987. this.module = context.module;
  3988. this.syntheticNamedExports = syntheticNamedExports;
  3989. }
  3990. addReference(identifier) {
  3991. this.references.push(identifier);
  3992. this.name = identifier.name;
  3993. }
  3994. // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
  3995. // build fails due to an illegal namespace reassignment or MemberExpression already forwards
  3996. // the reassignment to the right variable. This means we lost track of this variable and thus
  3997. // need to reassign all exports.
  3998. deoptimizePath() {
  3999. const memberVariables = this.getMemberVariables();
  4000. for (const key of Object.keys(memberVariables)) {
  4001. memberVariables[key].deoptimizePath(UNKNOWN_PATH);
  4002. }
  4003. }
  4004. getMemberVariables() {
  4005. if (this.memberVariables) {
  4006. return this.memberVariables;
  4007. }
  4008. const memberVariables = Object.create(null);
  4009. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  4010. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  4011. memberVariables[name] = this.context.traceExport(name);
  4012. }
  4013. }
  4014. return (this.memberVariables = memberVariables);
  4015. }
  4016. include() {
  4017. this.included = true;
  4018. this.context.includeAllExports();
  4019. }
  4020. prepareNamespace(mergedNamespaces) {
  4021. this.mergedNamespaces = mergedNamespaces;
  4022. const moduleExecIndex = this.context.getModuleExecIndex();
  4023. for (const identifier of this.references) {
  4024. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  4025. this.referencedEarly = true;
  4026. break;
  4027. }
  4028. }
  4029. }
  4030. renderBlock(options) {
  4031. const _ = options.compact ? '' : ' ';
  4032. const n = options.compact ? '' : '\n';
  4033. const t = options.indent;
  4034. const memberVariables = this.getMemberVariables();
  4035. const members = Object.keys(memberVariables).map(name => {
  4036. const original = memberVariables[name];
  4037. if (this.referencedEarly || original.isReassigned) {
  4038. return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
  4039. }
  4040. const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
  4041. return `${t}${safeName}: ${original.getName()}`;
  4042. });
  4043. if (options.namespaceToStringTag) {
  4044. members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
  4045. }
  4046. const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
  4047. if (!needsObjectAssign)
  4048. members.unshift(`${t}__proto__:${_}null`);
  4049. let output = `{${n}${members.join(`,${n}`)}${n}}`;
  4050. if (needsObjectAssign) {
  4051. const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
  4052. if (this.mergedNamespaces.length > 0) {
  4053. assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
  4054. }
  4055. if (this.syntheticNamedExports) {
  4056. assignmentArgs.push(this.module.getSyntheticNamespace().getName());
  4057. }
  4058. if (members.length > 0) {
  4059. assignmentArgs.push(output);
  4060. }
  4061. output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
  4062. }
  4063. if (options.freeze) {
  4064. output = `/*#__PURE__*/Object.freeze(${output})`;
  4065. }
  4066. const name = this.getName();
  4067. output = `${options.varOrConst} ${name}${_}=${_}${output};`;
  4068. if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
  4069. output += `${n}${getSystemExportStatement([this], options)};`;
  4070. }
  4071. return output;
  4072. }
  4073. renderFirst() {
  4074. return this.referencedEarly;
  4075. }
  4076. }
  4077. NamespaceVariable.prototype.isNamespace = true;
  4078. class SyntheticNamedExportVariable extends Variable {
  4079. constructor(context, name, syntheticNamespace) {
  4080. super(name);
  4081. this.baseVariable = null;
  4082. this.context = context;
  4083. this.module = context.module;
  4084. this.syntheticNamespace = syntheticNamespace;
  4085. }
  4086. getBaseVariable() {
  4087. if (this.baseVariable)
  4088. return this.baseVariable;
  4089. let baseVariable = this.syntheticNamespace;
  4090. while (baseVariable instanceof ExportDefaultVariable ||
  4091. baseVariable instanceof SyntheticNamedExportVariable) {
  4092. if (baseVariable instanceof ExportDefaultVariable) {
  4093. const original = baseVariable.getOriginalVariable();
  4094. if (original === baseVariable)
  4095. break;
  4096. baseVariable = original;
  4097. }
  4098. if (baseVariable instanceof SyntheticNamedExportVariable) {
  4099. baseVariable = baseVariable.syntheticNamespace;
  4100. }
  4101. }
  4102. return (this.baseVariable = baseVariable);
  4103. }
  4104. getBaseVariableName() {
  4105. return this.syntheticNamespace.getBaseVariableName();
  4106. }
  4107. getName() {
  4108. const name = this.name;
  4109. return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
  4110. }
  4111. include() {
  4112. if (!this.included) {
  4113. this.included = true;
  4114. this.context.includeVariableInModule(this.syntheticNamespace);
  4115. }
  4116. }
  4117. setRenderNames(baseName, name) {
  4118. super.setRenderNames(baseName, name);
  4119. }
  4120. }
  4121. const getPropertyAccess = (name) => {
  4122. return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
  4123. ? `.${name}`
  4124. : `[${JSON.stringify(name)}]`;
  4125. };
  4126. class ExternalVariable extends Variable {
  4127. constructor(module, name) {
  4128. super(name);
  4129. this.module = module;
  4130. this.isNamespace = name === '*';
  4131. this.referenced = false;
  4132. }
  4133. addReference(identifier) {
  4134. this.referenced = true;
  4135. if (this.name === 'default' || this.name === '*') {
  4136. this.module.suggestName(identifier.name);
  4137. }
  4138. }
  4139. include() {
  4140. if (!this.included) {
  4141. this.included = true;
  4142. this.module.used = true;
  4143. }
  4144. }
  4145. }
  4146. const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' ');
  4147. const builtins$1 = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' ');
  4148. const blacklisted = new Set(reservedWords$1.concat(builtins$1));
  4149. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  4150. const startsWithDigit = (str) => /\d/.test(str[0]);
  4151. function isLegal(str) {
  4152. if (startsWithDigit(str) || blacklisted.has(str)) {
  4153. return false;
  4154. }
  4155. return !illegalCharacters.test(str);
  4156. }
  4157. function makeLegal(str) {
  4158. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  4159. if (startsWithDigit(str) || blacklisted.has(str))
  4160. str = `_${str}`;
  4161. return str || '_';
  4162. }
  4163. const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  4164. const relativePath = /^\.?\.\//;
  4165. function isAbsolute(path) {
  4166. return absolutePath.test(path);
  4167. }
  4168. function isRelative(path) {
  4169. return relativePath.test(path);
  4170. }
  4171. function normalize(path) {
  4172. if (path.indexOf('\\') == -1)
  4173. return path;
  4174. return path.replace(/\\/g, '/');
  4175. }
  4176. class ExternalModule {
  4177. constructor(options, id, hasModuleSideEffects, meta) {
  4178. this.options = options;
  4179. this.id = id;
  4180. this.defaultVariableName = '';
  4181. this.dynamicImporters = [];
  4182. this.importers = [];
  4183. this.mostCommonSuggestion = 0;
  4184. this.namespaceVariableName = '';
  4185. this.reexported = false;
  4186. this.renderPath = undefined;
  4187. this.renormalizeRenderPath = false;
  4188. this.used = false;
  4189. this.variableName = '';
  4190. this.execIndex = Infinity;
  4191. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  4192. this.nameSuggestions = Object.create(null);
  4193. this.declarations = Object.create(null);
  4194. this.exportedVariables = new Map();
  4195. const module = this;
  4196. this.info = {
  4197. ast: null,
  4198. code: null,
  4199. dynamicallyImportedIds: EMPTY_ARRAY,
  4200. get dynamicImporters() {
  4201. return module.dynamicImporters.sort();
  4202. },
  4203. hasModuleSideEffects,
  4204. id,
  4205. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  4206. implicitlyLoadedBefore: EMPTY_ARRAY,
  4207. importedIds: EMPTY_ARRAY,
  4208. get importers() {
  4209. return module.importers.sort();
  4210. },
  4211. isEntry: false,
  4212. isExternal: true,
  4213. meta,
  4214. syntheticNamedExports: false
  4215. };
  4216. }
  4217. getVariableForExportName(name) {
  4218. let declaration = this.declarations[name];
  4219. if (declaration)
  4220. return declaration;
  4221. this.declarations[name] = declaration = new ExternalVariable(this, name);
  4222. this.exportedVariables.set(declaration, name);
  4223. return declaration;
  4224. }
  4225. setRenderPath(options, inputBase) {
  4226. this.renderPath =
  4227. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  4228. if (!this.renderPath) {
  4229. if (!isAbsolute(this.id)) {
  4230. this.renderPath = this.id;
  4231. }
  4232. else {
  4233. this.renderPath = normalize(relative$1(inputBase, this.id));
  4234. this.renormalizeRenderPath = true;
  4235. }
  4236. }
  4237. return this.renderPath;
  4238. }
  4239. suggestName(name) {
  4240. if (!this.nameSuggestions[name])
  4241. this.nameSuggestions[name] = 0;
  4242. this.nameSuggestions[name] += 1;
  4243. if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
  4244. this.mostCommonSuggestion = this.nameSuggestions[name];
  4245. this.suggestedVariableName = name;
  4246. }
  4247. }
  4248. warnUnusedImports() {
  4249. const unused = Object.keys(this.declarations).filter(name => {
  4250. if (name === '*')
  4251. return false;
  4252. const declaration = this.declarations[name];
  4253. return !declaration.included && !this.reexported && !declaration.referenced;
  4254. });
  4255. if (unused.length === 0)
  4256. return;
  4257. const names = unused.length === 1
  4258. ? `'${unused[0]}' is`
  4259. : `${unused
  4260. .slice(0, -1)
  4261. .map(name => `'${name}'`)
  4262. .join(', ')} and '${unused.slice(-1)}' are`;
  4263. this.options.onwarn({
  4264. code: 'UNUSED_EXTERNAL_IMPORT',
  4265. message: `${names} imported from external module '${this.id}' but never used`,
  4266. names: unused,
  4267. source: this.id
  4268. });
  4269. }
  4270. }
  4271. function removeJsExtension(name) {
  4272. return name.endsWith('.js') ? name.slice(0, -3) : name;
  4273. }
  4274. function getCompleteAmdId(options, chunkId) {
  4275. if (!options.autoId) {
  4276. return options.id || '';
  4277. }
  4278. else {
  4279. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  4280. }
  4281. }
  4282. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  4283. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  4284. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  4285. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  4286. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  4287. const defaultInteropHelpersByInteropType = {
  4288. auto: INTEROP_DEFAULT_VARIABLE,
  4289. default: null,
  4290. defaultOnly: null,
  4291. esModule: null,
  4292. false: null,
  4293. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  4294. };
  4295. function isDefaultAProperty(interopType, externalLiveBindings) {
  4296. return (interopType === 'esModule' ||
  4297. (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
  4298. }
  4299. const namespaceInteropHelpersByInteropType = {
  4300. auto: INTEROP_NAMESPACE_VARIABLE,
  4301. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  4302. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  4303. esModule: null,
  4304. false: null,
  4305. true: INTEROP_NAMESPACE_VARIABLE
  4306. };
  4307. function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
  4308. return (isDefaultAProperty(interopType, externalLiveBindings) &&
  4309. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
  4310. }
  4311. function getDefaultOnlyHelper() {
  4312. return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
  4313. }
  4314. function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
  4315. return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
  4316. ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  4317. : '').join('');
  4318. }
  4319. const HELPER_GENERATORS = {
  4320. [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
  4321. `e${_}&&${_}e.__esModule${_}?${_}` +
  4322. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  4323. [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
  4324. `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  4325. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  4326. [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  4327. (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
  4328. ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
  4329. : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  4330. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
  4331. `}${n}${n}`,
  4332. [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  4333. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
  4334. `}${n}${n}`,
  4335. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
  4336. `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
  4337. `}${n}${n}`
  4338. };
  4339. function getDefaultLiveBinding(_) {
  4340. return `e${_}:${_}{${_}'default':${_}e${_}}`;
  4341. }
  4342. function getDefaultStatic(_) {
  4343. return `e['default']${_}:${_}e`;
  4344. }
  4345. function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
  4346. return (`${i}var n${_}=${_}${namespaceToStringTag
  4347. ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
  4348. : 'Object.create(null)'};${n}` +
  4349. `${i}if${_}(e)${_}{${n}` +
  4350. `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
  4351. (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
  4352. `${i}${t}});${n}` +
  4353. `${i}}${n}` +
  4354. `${i}n['default']${_}=${_}e;${n}` +
  4355. `${i}return ${getFrozen('n', freeze)};${n}`);
  4356. }
  4357. function copyPropertyLiveBinding(_, n, t, i) {
  4358. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  4359. `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  4360. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  4361. `${i}${t}${t}enumerable:${_}true,${n}` +
  4362. `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
  4363. `${i}${t}${t}${t}return e[k];${n}` +
  4364. `${i}${t}${t}}${n}` +
  4365. `${i}${t}});${n}` +
  4366. `${i}}${n}`);
  4367. }
  4368. function copyPropertyStatic(_, n, _t, i) {
  4369. return `${i}n[k]${_}=${_}e[k];${n}`;
  4370. }
  4371. function getFrozen(fragment, freeze) {
  4372. return freeze ? `Object.freeze(${fragment})` : fragment;
  4373. }
  4374. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  4375. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
  4376. const _ = compact ? '' : ' ';
  4377. const n = compact ? '' : '\n';
  4378. if (!namedExportsMode) {
  4379. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
  4380. }
  4381. let exportBlock = '';
  4382. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4383. if (reexports && namedExportsMode) {
  4384. for (const specifier of reexports) {
  4385. if (specifier.reexported !== '*') {
  4386. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  4387. if (exportBlock)
  4388. exportBlock += n;
  4389. exportBlock +=
  4390. specifier.imported !== '*' && specifier.needsLiveBinding
  4391. ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  4392. `${t}enumerable:${_}true,${n}` +
  4393. `${t}get:${_}function${_}()${_}{${n}` +
  4394. `${t}${t}return ${importName};${n}${t}}${n}});`
  4395. : `exports.${specifier.reexported}${_}=${_}${importName};`;
  4396. }
  4397. }
  4398. }
  4399. }
  4400. for (const chunkExport of exports) {
  4401. const lhs = `exports.${chunkExport.exported}`;
  4402. const rhs = chunkExport.local;
  4403. if (lhs !== rhs) {
  4404. if (exportBlock)
  4405. exportBlock += n;
  4406. exportBlock += `${lhs}${_}=${_}${rhs};`;
  4407. }
  4408. }
  4409. for (const { name, reexports } of dependencies) {
  4410. if (reexports && namedExportsMode) {
  4411. for (const specifier of reexports) {
  4412. if (specifier.reexported === '*') {
  4413. if (exportBlock)
  4414. exportBlock += n;
  4415. if (specifier.needsLiveBinding) {
  4416. exportBlock +=
  4417. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4418. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
  4419. `${t}${t}enumerable:${_}true,${n}` +
  4420. `${t}${t}get:${_}function${_}()${_}{${n}` +
  4421. `${t}${t}${t}return ${name}[k];${n}` +
  4422. `${t}${t}}${n}${t}});${n}});`;
  4423. }
  4424. else {
  4425. exportBlock +=
  4426. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4427. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}exports[k]${_}=${_}${name}[k];${n}});`;
  4428. }
  4429. }
  4430. }
  4431. }
  4432. }
  4433. if (exportBlock) {
  4434. return `${n}${n}${exportBlock}`;
  4435. }
  4436. return '';
  4437. }
  4438. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
  4439. if (exports.length > 0) {
  4440. return exports[0].local;
  4441. }
  4442. else {
  4443. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4444. if (reexports) {
  4445. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  4446. }
  4447. }
  4448. }
  4449. }
  4450. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
  4451. if (imported === 'default') {
  4452. if (!isChunk) {
  4453. const moduleInterop = String(interop(moduleId));
  4454. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  4455. ? defaultVariableName
  4456. : moduleVariableName;
  4457. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  4458. ? `${variableName}['default']`
  4459. : variableName;
  4460. }
  4461. return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
  4462. }
  4463. if (imported === '*') {
  4464. return (isChunk
  4465. ? !depNamedExportsMode
  4466. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  4467. ? namespaceVariableName
  4468. : moduleVariableName;
  4469. }
  4470. return `${moduleVariableName}.${imported}`;
  4471. }
  4472. function getEsModuleExport(_) {
  4473. return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
  4474. }
  4475. function getNamespaceToStringExport(_) {
  4476. return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
  4477. }
  4478. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
  4479. let namespaceMarkers = '';
  4480. if (hasNamedExports) {
  4481. if (addEsModule) {
  4482. namespaceMarkers += getEsModuleExport(_);
  4483. }
  4484. if (addNamespaceToStringTag) {
  4485. if (namespaceMarkers) {
  4486. namespaceMarkers += n;
  4487. }
  4488. namespaceMarkers += getNamespaceToStringExport(_);
  4489. }
  4490. }
  4491. return namespaceMarkers;
  4492. }
  4493. function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
  4494. const neededInteropHelpers = new Set();
  4495. const interopStatements = [];
  4496. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  4497. neededInteropHelpers.add(helper);
  4498. interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  4499. };
  4500. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4501. if (isChunk) {
  4502. for (const { imported, reexported } of [
  4503. ...(imports || []),
  4504. ...(reexports || [])
  4505. ]) {
  4506. if (imported === '*' && reexported !== '*') {
  4507. if (!namedExportsMode) {
  4508. addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
  4509. }
  4510. break;
  4511. }
  4512. }
  4513. }
  4514. else {
  4515. const moduleInterop = String(interop(id));
  4516. let hasDefault = false;
  4517. let hasNamespace = false;
  4518. for (const { imported, reexported } of [
  4519. ...(imports || []),
  4520. ...(reexports || [])
  4521. ]) {
  4522. let helper;
  4523. let variableName;
  4524. if (imported === 'default') {
  4525. if (!hasDefault) {
  4526. hasDefault = true;
  4527. if (defaultVariableName !== namespaceVariableName) {
  4528. variableName = defaultVariableName;
  4529. helper = defaultInteropHelpersByInteropType[moduleInterop];
  4530. }
  4531. }
  4532. }
  4533. else if (imported === '*' && reexported !== '*') {
  4534. if (!hasNamespace) {
  4535. hasNamespace = true;
  4536. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  4537. variableName = namespaceVariableName;
  4538. }
  4539. }
  4540. if (helper) {
  4541. addInteropStatement(variableName, helper, name);
  4542. }
  4543. }
  4544. }
  4545. }
  4546. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  4547. }
  4548. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  4549. // The assumption is that this makes sense for all relative ids:
  4550. // https://requirejs.org/docs/api.html#jsfiles
  4551. function removeExtensionFromRelativeAmdId(id) {
  4552. return id[0] === '.' ? removeJsExtension(id) : id;
  4553. }
  4554. const builtins = {
  4555. assert: true,
  4556. buffer: true,
  4557. console: true,
  4558. constants: true,
  4559. domain: true,
  4560. events: true,
  4561. http: true,
  4562. https: true,
  4563. os: true,
  4564. path: true,
  4565. process: true,
  4566. punycode: true,
  4567. querystring: true,
  4568. stream: true,
  4569. string_decoder: true,
  4570. timers: true,
  4571. tty: true,
  4572. url: true,
  4573. util: true,
  4574. vm: true,
  4575. zlib: true
  4576. };
  4577. function warnOnBuiltins(warn, dependencies) {
  4578. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  4579. if (!externalBuiltins.length)
  4580. return;
  4581. const detail = externalBuiltins.length === 1
  4582. ? `module ('${externalBuiltins[0]}')`
  4583. : `modules (${externalBuiltins
  4584. .slice(0, -1)
  4585. .map(name => `'${name}'`)
  4586. .join(', ')} and '${externalBuiltins.slice(-1)}')`;
  4587. warn({
  4588. code: 'MISSING_NODE_BUILTINS',
  4589. 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`,
  4590. modules: externalBuiltins
  4591. });
  4592. }
  4593. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  4594. warnOnBuiltins(warn, dependencies);
  4595. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  4596. const args = dependencies.map(m => m.name);
  4597. const n = compact ? '' : '\n';
  4598. const s = compact ? '' : ';';
  4599. const _ = compact ? '' : ' ';
  4600. if (namedExportsMode && hasExports) {
  4601. args.unshift(`exports`);
  4602. deps.unshift(`'exports'`);
  4603. }
  4604. if (accessedGlobals.has('require')) {
  4605. args.unshift('require');
  4606. deps.unshift(`'require'`);
  4607. }
  4608. if (accessedGlobals.has('module')) {
  4609. args.unshift('module');
  4610. deps.unshift(`'module'`);
  4611. }
  4612. const completeAmdId = getCompleteAmdId(amd, id);
  4613. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  4614. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  4615. const useStrict = strict ? `${_}'use strict';` : '';
  4616. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  4617. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  4618. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  4619. if (namespaceMarkers) {
  4620. namespaceMarkers = n + n + namespaceMarkers;
  4621. }
  4622. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  4623. return magicString
  4624. .indent(t)
  4625. .prepend(`${amd.define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
  4626. .append(`${n}${n}});`);
  4627. }
  4628. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  4629. const n = compact ? '' : '\n';
  4630. const s = compact ? '' : ';';
  4631. const _ = compact ? '' : ' ';
  4632. const useStrict = strict ? `'use strict';${n}${n}` : '';
  4633. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  4634. if (namespaceMarkers) {
  4635. namespaceMarkers += n + n;
  4636. }
  4637. const importBlock = getImportBlock$1(dependencies, compact, varOrConst, n, _);
  4638. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  4639. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  4640. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
  4641. return magicString.append(`${exportBlock}${outro}`);
  4642. }
  4643. function getImportBlock$1(dependencies, compact, varOrConst, n, _) {
  4644. let importBlock = '';
  4645. let definingVariable = false;
  4646. for (const { id, name, reexports, imports } of dependencies) {
  4647. if (!reexports && !imports) {
  4648. if (importBlock) {
  4649. importBlock += !compact || definingVariable ? `;${n}` : ',';
  4650. }
  4651. definingVariable = false;
  4652. importBlock += `require('${id}')`;
  4653. }
  4654. else {
  4655. importBlock +=
  4656. compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
  4657. definingVariable = true;
  4658. importBlock += `${name}${_}=${_}require('${id}')`;
  4659. }
  4660. }
  4661. if (importBlock) {
  4662. return `${importBlock};${n}${n}`;
  4663. }
  4664. return '';
  4665. }
  4666. function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
  4667. const _ = compact ? '' : ' ';
  4668. const n = compact ? '' : '\n';
  4669. const importBlock = getImportBlock(dependencies, _);
  4670. if (importBlock.length > 0)
  4671. intro += importBlock.join(n) + n + n;
  4672. if (intro)
  4673. magicString.prepend(intro);
  4674. const exportBlock = getExportBlock(exports, _, varOrConst);
  4675. if (exportBlock.length)
  4676. magicString.append(n + n + exportBlock.join(n).trim());
  4677. if (outro)
  4678. magicString.append(outro);
  4679. return magicString.trim();
  4680. }
  4681. function getImportBlock(dependencies, _) {
  4682. const importBlock = [];
  4683. for (const { id, reexports, imports, name } of dependencies) {
  4684. if (!reexports && !imports) {
  4685. importBlock.push(`import${_}'${id}';`);
  4686. continue;
  4687. }
  4688. if (imports) {
  4689. let defaultImport = null;
  4690. let starImport = null;
  4691. const importedNames = [];
  4692. for (const specifier of imports) {
  4693. if (specifier.imported === 'default') {
  4694. defaultImport = specifier;
  4695. }
  4696. else if (specifier.imported === '*') {
  4697. starImport = specifier;
  4698. }
  4699. else {
  4700. importedNames.push(specifier);
  4701. }
  4702. }
  4703. if (starImport) {
  4704. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  4705. }
  4706. if (defaultImport && importedNames.length === 0) {
  4707. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  4708. }
  4709. else if (importedNames.length > 0) {
  4710. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  4711. .map(specifier => {
  4712. if (specifier.imported === specifier.local) {
  4713. return specifier.imported;
  4714. }
  4715. else {
  4716. return `${specifier.imported} as ${specifier.local}`;
  4717. }
  4718. })
  4719. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  4720. }
  4721. }
  4722. if (reexports) {
  4723. let starExport = null;
  4724. const namespaceReexports = [];
  4725. const namedReexports = [];
  4726. for (const specifier of reexports) {
  4727. if (specifier.reexported === '*') {
  4728. starExport = specifier;
  4729. }
  4730. else if (specifier.imported === '*') {
  4731. namespaceReexports.push(specifier);
  4732. }
  4733. else {
  4734. namedReexports.push(specifier);
  4735. }
  4736. }
  4737. if (starExport) {
  4738. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  4739. }
  4740. if (namespaceReexports.length > 0) {
  4741. if (!imports ||
  4742. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  4743. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  4744. }
  4745. for (const specifier of namespaceReexports) {
  4746. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  4747. }
  4748. }
  4749. if (namedReexports.length > 0) {
  4750. importBlock.push(`export${_}{${_}${namedReexports
  4751. .map(specifier => {
  4752. if (specifier.imported === specifier.reexported) {
  4753. return specifier.imported;
  4754. }
  4755. else {
  4756. return `${specifier.imported} as ${specifier.reexported}`;
  4757. }
  4758. })
  4759. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  4760. }
  4761. }
  4762. }
  4763. return importBlock;
  4764. }
  4765. function getExportBlock(exports, _, varOrConst) {
  4766. const exportBlock = [];
  4767. const exportDeclaration = [];
  4768. for (const specifier of exports) {
  4769. if (specifier.exported === 'default') {
  4770. exportBlock.push(`export default ${specifier.local};`);
  4771. }
  4772. else {
  4773. if (specifier.expression) {
  4774. exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
  4775. }
  4776. exportDeclaration.push(specifier.exported === specifier.local
  4777. ? specifier.local
  4778. : `${specifier.local} as ${specifier.exported}`);
  4779. }
  4780. }
  4781. if (exportDeclaration.length) {
  4782. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  4783. }
  4784. return exportBlock;
  4785. }
  4786. function spaces(i) {
  4787. let result = '';
  4788. while (i--)
  4789. result += ' ';
  4790. return result;
  4791. }
  4792. function tabsToSpaces(str) {
  4793. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  4794. }
  4795. function getCodeFrame(source, line, column) {
  4796. let lines = source.split('\n');
  4797. const frameStart = Math.max(0, line - 3);
  4798. let frameEnd = Math.min(line + 2, lines.length);
  4799. lines = lines.slice(frameStart, frameEnd);
  4800. while (!/\S/.test(lines[lines.length - 1])) {
  4801. lines.pop();
  4802. frameEnd -= 1;
  4803. }
  4804. const digits = String(frameEnd).length;
  4805. return lines
  4806. .map((str, i) => {
  4807. const isErrorLine = frameStart + i + 1 === line;
  4808. let lineNum = String(i + frameStart + 1);
  4809. while (lineNum.length < digits)
  4810. lineNum = ` ${lineNum}`;
  4811. if (isErrorLine) {
  4812. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  4813. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  4814. }
  4815. return `${lineNum}: ${tabsToSpaces(str)}`;
  4816. })
  4817. .join('\n');
  4818. }
  4819. function sanitizeFileName(name) {
  4820. const match = /^[a-z]:/i.exec(name);
  4821. const driveLetter = match ? match[0] : "";
  4822. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  4823. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  4824. return driveLetter + name.substr(driveLetter.length).replace(/[\0?*:]/g, '_');
  4825. }
  4826. function getAliasName(id) {
  4827. const base = basename(id);
  4828. return base.substr(0, base.length - extname(id).length);
  4829. }
  4830. function relativeId(id) {
  4831. if (!isAbsolute(id))
  4832. return id;
  4833. return relative$1(resolve(), id);
  4834. }
  4835. function isPlainPathFragment(name) {
  4836. // not starting with "/", "./", "../"
  4837. return (name[0] !== '/' &&
  4838. !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
  4839. sanitizeFileName(name) === name &&
  4840. !isAbsolute(name));
  4841. }
  4842. function error(base) {
  4843. if (!(base instanceof Error))
  4844. base = Object.assign(new Error(base.message), base);
  4845. throw base;
  4846. }
  4847. function augmentCodeLocation(props, pos, source, id) {
  4848. if (typeof pos === 'object') {
  4849. const { line, column } = pos;
  4850. props.loc = { file: id, line, column };
  4851. }
  4852. else {
  4853. props.pos = pos;
  4854. const { line, column } = locate(source, pos, { offsetLine: 1 });
  4855. props.loc = { file: id, line, column };
  4856. }
  4857. if (props.frame === undefined) {
  4858. const { line, column } = props.loc;
  4859. props.frame = getCodeFrame(source, line, column);
  4860. }
  4861. }
  4862. var Errors;
  4863. (function (Errors) {
  4864. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  4865. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  4866. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  4867. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  4868. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  4869. Errors["BAD_LOADER"] = "BAD_LOADER";
  4870. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  4871. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  4872. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  4873. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  4874. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  4875. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  4876. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  4877. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  4878. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  4879. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  4880. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  4881. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  4882. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  4883. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  4884. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  4885. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  4886. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  4887. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  4888. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  4889. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  4890. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  4891. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  4892. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  4893. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  4894. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  4895. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  4896. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  4897. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  4898. })(Errors || (Errors = {}));
  4899. function errAssetNotFinalisedForFileName(name) {
  4900. return {
  4901. code: Errors.ASSET_NOT_FINALISED,
  4902. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  4903. };
  4904. }
  4905. function errCannotEmitFromOptionsHook() {
  4906. return {
  4907. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  4908. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  4909. };
  4910. }
  4911. function errChunkNotGeneratedForFileName(name) {
  4912. return {
  4913. code: Errors.CHUNK_NOT_GENERATED,
  4914. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  4915. };
  4916. }
  4917. function errChunkInvalid({ fileName, code }, exception) {
  4918. const errorProps = {
  4919. code: Errors.CHUNK_INVALID,
  4920. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  4921. };
  4922. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  4923. return errorProps;
  4924. }
  4925. function errCircularReexport(exportName, importedModule) {
  4926. return {
  4927. code: Errors.CIRCULAR_REEXPORT,
  4928. id: importedModule,
  4929. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  4930. };
  4931. }
  4932. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  4933. return {
  4934. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  4935. exporter,
  4936. importer,
  4937. message: `Export "${exportName}" of module ${relativeId(exporter)} was reexported through module ${relativeId(reexporter)} while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in ${relativeId(importer)} to point directly to the exporting module or do not use "preserveModules" to ensure these modules end up in the same chunk.`,
  4938. reexporter
  4939. };
  4940. }
  4941. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  4942. return {
  4943. code: Errors.ASSET_NOT_FOUND,
  4944. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  4945. };
  4946. }
  4947. function errAssetSourceAlreadySet(name) {
  4948. return {
  4949. code: Errors.ASSET_SOURCE_ALREADY_SET,
  4950. message: `Unable to set the source for asset "${name}", source already set.`
  4951. };
  4952. }
  4953. function errNoAssetSourceSet(assetName) {
  4954. return {
  4955. code: Errors.ASSET_SOURCE_MISSING,
  4956. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  4957. };
  4958. }
  4959. function errBadLoader(id) {
  4960. return {
  4961. code: Errors.BAD_LOADER,
  4962. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  4963. };
  4964. }
  4965. function errDeprecation(deprecation) {
  4966. return {
  4967. code: Errors.DEPRECATED_FEATURE,
  4968. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  4969. };
  4970. }
  4971. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  4972. return {
  4973. code: Errors.FILE_NOT_FOUND,
  4974. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  4975. };
  4976. }
  4977. function errFileNameConflict(fileName) {
  4978. return {
  4979. code: Errors.FILE_NAME_CONFLICT,
  4980. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  4981. };
  4982. }
  4983. function errInputHookInOutputPlugin(pluginName, hookName) {
  4984. return {
  4985. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  4986. 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.`
  4987. };
  4988. }
  4989. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  4990. return {
  4991. code: Errors.INVALID_CHUNK,
  4992. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  4993. };
  4994. }
  4995. function errInvalidExportOptionValue(optionValue) {
  4996. return {
  4997. code: Errors.INVALID_EXPORT_OPTION,
  4998. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  4999. url: `https://rollupjs.org/guide/en/#outputexports`
  5000. };
  5001. }
  5002. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  5003. return {
  5004. code: 'INVALID_EXPORT_OPTION',
  5005. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  5006. };
  5007. }
  5008. function errInternalIdCannotBeExternal(source, importer) {
  5009. return {
  5010. code: Errors.INVALID_EXTERNAL_ID,
  5011. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  5012. };
  5013. }
  5014. function errInvalidOption(option, explanation) {
  5015. return {
  5016. code: Errors.INVALID_OPTION,
  5017. message: `Invalid value for option "${option}" - ${explanation}.`
  5018. };
  5019. }
  5020. function errInvalidRollupPhaseForAddWatchFile() {
  5021. return {
  5022. code: Errors.INVALID_ROLLUP_PHASE,
  5023. message: `Cannot call addWatchFile after the build has finished.`
  5024. };
  5025. }
  5026. function errInvalidRollupPhaseForChunkEmission() {
  5027. return {
  5028. code: Errors.INVALID_ROLLUP_PHASE,
  5029. message: `Cannot emit chunks after module loading has finished.`
  5030. };
  5031. }
  5032. function errMissingExport(exportName, importingModule, importedModule) {
  5033. return {
  5034. code: Errors.MISSING_EXPORT,
  5035. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  5036. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  5037. };
  5038. }
  5039. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  5040. return {
  5041. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5042. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  5043. };
  5044. }
  5045. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  5046. return {
  5047. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5048. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  5049. };
  5050. }
  5051. function errImplicitDependantIsNotIncluded(module) {
  5052. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  5053. return {
  5054. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5055. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before "${implicitDependencies.length === 1
  5056. ? implicitDependencies[0]
  5057. : `${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.`
  5058. };
  5059. }
  5060. function errMixedExport(facadeModuleId, name) {
  5061. return {
  5062. code: Errors.MIXED_EXPORTS,
  5063. id: facadeModuleId,
  5064. 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`,
  5065. url: `https://rollupjs.org/guide/en/#outputexports`
  5066. };
  5067. }
  5068. function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
  5069. return {
  5070. code: Errors.NAMESPACE_CONFLICT,
  5071. message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
  5072. name,
  5073. reexporter: reexportingModule.id,
  5074. sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
  5075. };
  5076. }
  5077. function errNoTransformMapOrAstWithoutCode(pluginName) {
  5078. return {
  5079. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  5080. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  5081. 'a "code". This will be ignored.'
  5082. };
  5083. }
  5084. function errPreferNamedExports(facadeModuleId) {
  5085. const file = relativeId(facadeModuleId);
  5086. return {
  5087. code: Errors.PREFER_NAMED_EXPORTS,
  5088. id: facadeModuleId,
  5089. 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.`,
  5090. url: `https://rollupjs.org/guide/en/#outputexports`
  5091. };
  5092. }
  5093. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  5094. return {
  5095. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  5096. id,
  5097. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  5098. ? `an export named "${syntheticNamedExportsOption}"`
  5099. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  5100. };
  5101. }
  5102. function errUnexpectedNamedImport(id, imported, isReexport) {
  5103. const importType = isReexport ? 'reexport' : 'import';
  5104. return {
  5105. code: Errors.UNEXPECTED_NAMED_IMPORT,
  5106. id,
  5107. 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.`,
  5108. url: 'https://rollupjs.org/guide/en/#outputinterop'
  5109. };
  5110. }
  5111. function errUnexpectedNamespaceReexport(id) {
  5112. return {
  5113. code: Errors.UNEXPECTED_NAMED_IMPORT,
  5114. id,
  5115. 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.`,
  5116. url: 'https://rollupjs.org/guide/en/#outputinterop'
  5117. };
  5118. }
  5119. function errEntryCannotBeExternal(unresolvedId) {
  5120. return {
  5121. code: Errors.UNRESOLVED_ENTRY,
  5122. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  5123. };
  5124. }
  5125. function errUnresolvedEntry(unresolvedId) {
  5126. return {
  5127. code: Errors.UNRESOLVED_ENTRY,
  5128. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  5129. };
  5130. }
  5131. function errUnresolvedImport(source, importer) {
  5132. return {
  5133. code: Errors.UNRESOLVED_IMPORT,
  5134. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  5135. };
  5136. }
  5137. function errUnresolvedImportTreatedAsExternal(source, importer) {
  5138. return {
  5139. code: Errors.UNRESOLVED_IMPORT,
  5140. importer: relativeId(importer),
  5141. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  5142. source,
  5143. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  5144. };
  5145. }
  5146. function errExternalSyntheticExports(source, importer) {
  5147. return {
  5148. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  5149. importer: relativeId(importer),
  5150. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  5151. source
  5152. };
  5153. }
  5154. function errFailedValidation(message) {
  5155. return {
  5156. code: Errors.VALIDATION_ERROR,
  5157. message
  5158. };
  5159. }
  5160. function errAlreadyClosed() {
  5161. return {
  5162. code: Errors.ALREADY_CLOSED,
  5163. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  5164. };
  5165. }
  5166. function warnDeprecation(deprecation, activeDeprecation, options) {
  5167. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  5168. }
  5169. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  5170. if (activeDeprecation || strictDeprecations) {
  5171. const warning = errDeprecation(deprecation);
  5172. if (strictDeprecations) {
  5173. return error(warning);
  5174. }
  5175. warn(warning);
  5176. }
  5177. }
  5178. // Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
  5179. // if the property name isn't trivial
  5180. const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
  5181. function property(prop) {
  5182. return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
  5183. }
  5184. function keypath(keypath) {
  5185. return keypath
  5186. .split('.')
  5187. .map(property)
  5188. .join('');
  5189. }
  5190. function setupNamespace(name, root, globals, compact) {
  5191. const _ = compact ? '' : ' ';
  5192. const parts = name.split('.');
  5193. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5194. parts.pop();
  5195. let acc = root;
  5196. return (parts
  5197. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
  5198. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  5199. }
  5200. function assignToDeepVariable(deepName, root, globals, compact, assignment) {
  5201. const _ = compact ? '' : ' ';
  5202. const parts = deepName.split('.');
  5203. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5204. const last = parts.pop();
  5205. let acc = root;
  5206. let deepAssignment = parts
  5207. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
  5208. .concat(`${acc}${property(last)}`)
  5209. .join(`,${_}`)
  5210. .concat(`${_}=${_}${assignment}`);
  5211. if (parts.length > 0) {
  5212. deepAssignment = `(${deepAssignment})`;
  5213. }
  5214. return deepAssignment;
  5215. }
  5216. function trimEmptyImports(dependencies) {
  5217. let i = dependencies.length;
  5218. while (i--) {
  5219. const { imports, reexports } = dependencies[i];
  5220. if (imports || reexports) {
  5221. return dependencies.slice(0, i + 1);
  5222. }
  5223. }
  5224. return [];
  5225. }
  5226. const thisProp = (name) => `this${keypath(name)}`;
  5227. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  5228. const _ = compact ? '' : ' ';
  5229. const s = compact ? '' : ';';
  5230. const n = compact ? '' : '\n';
  5231. const isNamespaced = name && name.indexOf('.') !== -1;
  5232. const useVariableAssignment = !extend && !isNamespaced;
  5233. if (name && useVariableAssignment && !isLegal(name)) {
  5234. return error({
  5235. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  5236. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  5237. });
  5238. }
  5239. warnOnBuiltins(warn, dependencies);
  5240. const external = trimEmptyImports(dependencies);
  5241. const deps = external.map(dep => dep.globalName || 'null');
  5242. const args = external.map(m => m.name);
  5243. if (hasExports && !name) {
  5244. warn({
  5245. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5246. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  5247. });
  5248. }
  5249. if (namedExportsMode && hasExports) {
  5250. if (extend) {
  5251. deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
  5252. args.unshift('exports');
  5253. }
  5254. else {
  5255. deps.unshift('{}');
  5256. args.unshift('exports');
  5257. }
  5258. }
  5259. const useStrict = strict ? `${t}'use strict';${n}` : '';
  5260. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  5261. magicString.prepend(`${intro}${interopBlock}`);
  5262. let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
  5263. if (hasExports) {
  5264. if (name && !(extend && namedExportsMode)) {
  5265. wrapperIntro =
  5266. (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
  5267. `${_}=${_}${wrapperIntro}`;
  5268. }
  5269. if (isNamespaced) {
  5270. wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
  5271. }
  5272. }
  5273. let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
  5274. if (hasExports && !extend && namedExportsMode) {
  5275. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  5276. }
  5277. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  5278. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  5279. if (namespaceMarkers) {
  5280. namespaceMarkers = n + n + namespaceMarkers;
  5281. }
  5282. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  5283. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  5284. }
  5285. function getStarExcludes({ dependencies, exports }) {
  5286. const starExcludes = new Set(exports.map(expt => expt.exported));
  5287. if (!starExcludes.has('default'))
  5288. starExcludes.add('default');
  5289. // also include reexport names
  5290. for (const { reexports } of dependencies) {
  5291. if (reexports) {
  5292. for (const reexport of reexports) {
  5293. if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
  5294. starExcludes.add(reexport.reexported);
  5295. }
  5296. }
  5297. }
  5298. return starExcludes;
  5299. }
  5300. const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
  5301. ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
  5302. .map(prop => `${prop}:${_}1`)
  5303. .join(`,${_}`)}${_}};`
  5304. : '';
  5305. const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  5306. function getExportsBlock(exports, _, t, n) {
  5307. if (exports.length === 0) {
  5308. return '';
  5309. }
  5310. if (exports.length === 1) {
  5311. return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  5312. }
  5313. return (`${t}${t}${t}exports({${n}` +
  5314. exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
  5315. `${n}${t}${t}${t}});${n}${n}`);
  5316. }
  5317. const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5318. .filter(expt => expt.hoisted || expt.uninitialized)
  5319. .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
  5320. const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5321. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  5322. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
  5323. const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5324. .filter(expt => expt.expression)
  5325. .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  5326. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
  5327. const n = options.compact ? '' : '\n';
  5328. const _ = options.compact ? '' : ' ';
  5329. const dependencyIds = dependencies.map(m => `'${m.id}'`);
  5330. const importBindings = [];
  5331. let starExcludes;
  5332. const setters = [];
  5333. for (const { imports, reexports } of dependencies) {
  5334. const setter = [];
  5335. if (imports) {
  5336. for (const specifier of imports) {
  5337. importBindings.push(specifier.local);
  5338. if (specifier.imported === '*') {
  5339. setter.push(`${specifier.local}${_}=${_}module;`);
  5340. }
  5341. else {
  5342. setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
  5343. }
  5344. }
  5345. }
  5346. if (reexports) {
  5347. let createdSetter = false;
  5348. // bulk-reexport form
  5349. if (reexports.length > 1 ||
  5350. (reexports.length === 1 &&
  5351. (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
  5352. // star reexports
  5353. for (const specifier of reexports) {
  5354. if (specifier.reexported !== '*')
  5355. continue;
  5356. // need own exports list for deduping in star export case
  5357. if (!starExcludes) {
  5358. starExcludes = getStarExcludes({ dependencies, exports });
  5359. }
  5360. if (!createdSetter) {
  5361. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5362. createdSetter = true;
  5363. }
  5364. setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
  5365. setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
  5366. setter.push('}');
  5367. }
  5368. // star import reexport
  5369. for (const specifier of reexports) {
  5370. if (specifier.imported !== '*' || specifier.reexported === '*')
  5371. continue;
  5372. setter.push(`exports('${specifier.reexported}',${_}module);`);
  5373. }
  5374. // reexports
  5375. for (const specifier of reexports) {
  5376. if (specifier.reexported === '*' || specifier.imported === '*')
  5377. continue;
  5378. if (!createdSetter) {
  5379. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5380. createdSetter = true;
  5381. }
  5382. setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
  5383. }
  5384. if (createdSetter) {
  5385. setter.push('exports(_setter);');
  5386. }
  5387. }
  5388. else {
  5389. // single reexport
  5390. for (const specifier of reexports) {
  5391. setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
  5392. }
  5393. }
  5394. }
  5395. setters.push(setter.join(`${n}${t}${t}${t}`));
  5396. }
  5397. const registeredName = options.name ? `'${options.name}',${_}` : '';
  5398. const wrapperParams = accessedGlobals.has('module')
  5399. ? `exports,${_}module`
  5400. : hasExports
  5401. ? 'exports'
  5402. : '';
  5403. let wrapperStart = `System.register(${registeredName}[` +
  5404. dependencyIds.join(`,${_}`) +
  5405. `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
  5406. getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
  5407. getImportBindingsBlock(importBindings, _, t, n) +
  5408. `${n}${t}return${_}{${setters.length
  5409. ? `${n}${t}${t}setters:${_}[${setters
  5410. .map(s => s
  5411. ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
  5412. : options.systemNullSetters
  5413. ? `null`
  5414. : `function${_}()${_}{}`)
  5415. .join(`,${_}`)}],`
  5416. : ''}${n}`;
  5417. wrapperStart +=
  5418. `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
  5419. getHoistedExportsBlock(exports, _, t, n);
  5420. const wrapperEnd = `${n}${n}` +
  5421. getSyntheticExportsBlock(exports, _, t, n) +
  5422. getMissingExportsBlock(exports, _, t, n) +
  5423. `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
  5424. if (intro)
  5425. magicString.prepend(intro);
  5426. if (outro)
  5427. magicString.append(outro);
  5428. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  5429. }
  5430. function globalProp(name, globalVar) {
  5431. if (!name)
  5432. return 'null';
  5433. return `${globalVar}${keypath(name)}`;
  5434. }
  5435. function safeAccess(name, globalVar, _) {
  5436. const parts = name.split('.');
  5437. let acc = globalVar;
  5438. return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
  5439. }
  5440. function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  5441. const _ = compact ? '' : ' ';
  5442. const n = compact ? '' : '\n';
  5443. const s = compact ? '' : ';';
  5444. const factoryVar = compact ? 'f' : 'factory';
  5445. const globalVar = compact ? 'g' : 'global';
  5446. if (hasExports && !name) {
  5447. return error({
  5448. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5449. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  5450. });
  5451. }
  5452. warnOnBuiltins(warn, dependencies);
  5453. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  5454. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  5455. const trimmedImports = trimEmptyImports(dependencies);
  5456. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
  5457. const factoryArgs = trimmedImports.map(m => m.name);
  5458. if (namedExportsMode && (hasExports || noConflict)) {
  5459. amdDeps.unshift(`'exports'`);
  5460. cjsDeps.unshift(`exports`);
  5461. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
  5462. factoryArgs.unshift('exports');
  5463. }
  5464. const completeAmdId = getCompleteAmdId(amd, id);
  5465. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  5466. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  5467. const define = amd.define;
  5468. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  5469. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  5470. let iifeExport;
  5471. if (noConflict) {
  5472. const noConflictExportsVar = compact ? 'e' : 'exports';
  5473. let factory;
  5474. if (!namedExportsMode && hasExports) {
  5475. factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
  5476. }
  5477. else {
  5478. const module = globalDeps.shift();
  5479. factory =
  5480. `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
  5481. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  5482. }
  5483. iifeExport =
  5484. `(function${_}()${_}{${n}` +
  5485. `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
  5486. `${t}${t}${factory}${n}` +
  5487. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
  5488. `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
  5489. `${t}}())`;
  5490. }
  5491. else {
  5492. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  5493. if (!namedExportsMode && hasExports) {
  5494. iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
  5495. }
  5496. }
  5497. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  5498. const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
  5499. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  5500. const iifeStart = iifeNeedsGlobal
  5501. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  5502. : '';
  5503. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  5504. const cjsIntro = iifeNeedsGlobal
  5505. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  5506. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  5507. : '';
  5508. // factory function should be wrapped by parentheses to avoid lazy parsing
  5509. const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
  5510. cjsIntro +
  5511. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  5512. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  5513. `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
  5514. const wrapperOutro = n + n + '})));';
  5515. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  5516. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  5517. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  5518. if (namespaceMarkers) {
  5519. namespaceMarkers = n + n + namespaceMarkers;
  5520. }
  5521. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  5522. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  5523. }
  5524. var finalisers = { system, amd, cjs, es, iife, umd };
  5525. const extractors = {
  5526. ArrayPattern(names, param) {
  5527. for (const element of param.elements) {
  5528. if (element)
  5529. extractors[element.type](names, element);
  5530. }
  5531. },
  5532. AssignmentPattern(names, param) {
  5533. extractors[param.left.type](names, param.left);
  5534. },
  5535. Identifier(names, param) {
  5536. names.push(param.name);
  5537. },
  5538. MemberExpression() { },
  5539. ObjectPattern(names, param) {
  5540. for (const prop of param.properties) {
  5541. if (prop.type === 'RestElement') {
  5542. extractors.RestElement(names, prop);
  5543. }
  5544. else {
  5545. extractors[prop.value.type](names, prop.value);
  5546. }
  5547. }
  5548. },
  5549. RestElement(names, param) {
  5550. extractors[param.argument.type](names, param.argument);
  5551. }
  5552. };
  5553. const extractAssignedNames = function extractAssignedNames(param) {
  5554. const names = [];
  5555. extractors[param.type](names, param);
  5556. return names;
  5557. };
  5558. class ExportAllDeclaration extends NodeBase {
  5559. hasEffects() {
  5560. return false;
  5561. }
  5562. initialise() {
  5563. this.context.addExport(this);
  5564. }
  5565. render(code, _options, nodeRenderOptions) {
  5566. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  5567. }
  5568. }
  5569. ExportAllDeclaration.prototype.needsBoundaries = true;
  5570. class ArrayExpression extends NodeBase {
  5571. bind() {
  5572. super.bind();
  5573. for (const element of this.elements) {
  5574. if (element !== null)
  5575. element.deoptimizePath(UNKNOWN_PATH);
  5576. }
  5577. }
  5578. getReturnExpressionWhenCalledAtPath(path) {
  5579. if (path.length !== 1)
  5580. return UNKNOWN_EXPRESSION;
  5581. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  5582. }
  5583. hasEffectsWhenAccessedAtPath(path) {
  5584. return path.length > 1;
  5585. }
  5586. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5587. if (path.length === 1) {
  5588. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  5589. }
  5590. return true;
  5591. }
  5592. }
  5593. class ArrayPattern extends NodeBase {
  5594. addExportedVariables(variables, exportNamesByVariable) {
  5595. for (const element of this.elements) {
  5596. if (element !== null) {
  5597. element.addExportedVariables(variables, exportNamesByVariable);
  5598. }
  5599. }
  5600. }
  5601. declare(kind) {
  5602. const variables = [];
  5603. for (const element of this.elements) {
  5604. if (element !== null) {
  5605. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5606. }
  5607. }
  5608. return variables;
  5609. }
  5610. deoptimizePath(path) {
  5611. if (path.length === 0) {
  5612. for (const element of this.elements) {
  5613. if (element !== null) {
  5614. element.deoptimizePath(path);
  5615. }
  5616. }
  5617. }
  5618. }
  5619. hasEffectsWhenAssignedAtPath(path, context) {
  5620. if (path.length > 0)
  5621. return true;
  5622. for (const element of this.elements) {
  5623. if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  5624. return true;
  5625. }
  5626. return false;
  5627. }
  5628. }
  5629. class BlockScope extends ChildScope {
  5630. addDeclaration(identifier, context, init, isHoisted) {
  5631. if (isHoisted) {
  5632. return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, isHoisted);
  5633. }
  5634. else {
  5635. return super.addDeclaration(identifier, context, init, false);
  5636. }
  5637. }
  5638. }
  5639. class ExpressionStatement extends NodeBase {
  5640. initialise() {
  5641. if (this.directive &&
  5642. this.directive !== 'use strict' &&
  5643. this.parent.type === Program$1) {
  5644. this.context.warn(
  5645. // This is necessary, because either way (deleting or not) can lead to errors.
  5646. {
  5647. code: 'MODULE_LEVEL_DIRECTIVE',
  5648. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  5649. }, this.start);
  5650. }
  5651. }
  5652. render(code, options) {
  5653. super.render(code, options);
  5654. if (this.included)
  5655. this.insertSemicolon(code);
  5656. }
  5657. shouldBeIncluded(context) {
  5658. if (this.directive && this.directive !== 'use strict')
  5659. return this.parent.type !== Program$1;
  5660. return super.shouldBeIncluded(context);
  5661. }
  5662. }
  5663. class BlockStatement extends NodeBase {
  5664. constructor() {
  5665. super(...arguments);
  5666. this.directlyIncluded = false;
  5667. }
  5668. addImplicitReturnExpressionToScope() {
  5669. const lastStatement = this.body[this.body.length - 1];
  5670. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  5671. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  5672. }
  5673. }
  5674. createScope(parentScope) {
  5675. this.scope = this.parent.preventChildBlockScope
  5676. ? parentScope
  5677. : new BlockScope(parentScope);
  5678. }
  5679. hasEffects(context) {
  5680. if (this.deoptimizeBody)
  5681. return true;
  5682. for (const node of this.body) {
  5683. if (node.hasEffects(context))
  5684. return true;
  5685. if (context.brokenFlow)
  5686. break;
  5687. }
  5688. return false;
  5689. }
  5690. include(context, includeChildrenRecursively) {
  5691. if (!this.deoptimizeBody || !this.directlyIncluded) {
  5692. this.included = true;
  5693. this.directlyIncluded = true;
  5694. if (this.deoptimizeBody)
  5695. includeChildrenRecursively = true;
  5696. for (const node of this.body) {
  5697. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5698. node.include(context, includeChildrenRecursively);
  5699. }
  5700. }
  5701. }
  5702. initialise() {
  5703. const firstBodyStatement = this.body[0];
  5704. this.deoptimizeBody =
  5705. firstBodyStatement instanceof ExpressionStatement &&
  5706. firstBodyStatement.directive === 'use asm';
  5707. }
  5708. render(code, options) {
  5709. if (this.body.length) {
  5710. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  5711. }
  5712. else {
  5713. super.render(code, options);
  5714. }
  5715. }
  5716. }
  5717. class ArrowFunctionExpression extends NodeBase {
  5718. createScope(parentScope) {
  5719. this.scope = new ReturnValueScope(parentScope, this.context);
  5720. }
  5721. deoptimizePath(path) {
  5722. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  5723. // which means the return expression needs to be reassigned
  5724. if (path.length === 1 && path[0] === UnknownKey) {
  5725. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5726. }
  5727. }
  5728. getReturnExpressionWhenCalledAtPath(path) {
  5729. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  5730. }
  5731. hasEffects() {
  5732. return false;
  5733. }
  5734. hasEffectsWhenAccessedAtPath(path) {
  5735. return path.length > 1;
  5736. }
  5737. hasEffectsWhenAssignedAtPath(path) {
  5738. return path.length > 1;
  5739. }
  5740. hasEffectsWhenCalledAtPath(path, _callOptions, context) {
  5741. if (path.length > 0)
  5742. return true;
  5743. for (const param of this.params) {
  5744. if (param.hasEffects(context))
  5745. return true;
  5746. }
  5747. const { ignore, brokenFlow } = context;
  5748. context.ignore = {
  5749. breaks: false,
  5750. continues: false,
  5751. labels: new Set(),
  5752. returnAwaitYield: true
  5753. };
  5754. if (this.body.hasEffects(context))
  5755. return true;
  5756. context.ignore = ignore;
  5757. context.brokenFlow = brokenFlow;
  5758. return false;
  5759. }
  5760. include(context, includeChildrenRecursively) {
  5761. this.included = true;
  5762. for (const param of this.params) {
  5763. if (!(param instanceof Identifier)) {
  5764. param.include(context, includeChildrenRecursively);
  5765. }
  5766. }
  5767. const { brokenFlow } = context;
  5768. context.brokenFlow = BROKEN_FLOW_NONE;
  5769. this.body.include(context, includeChildrenRecursively);
  5770. context.brokenFlow = brokenFlow;
  5771. }
  5772. includeCallArguments(context, args) {
  5773. this.scope.includeCallArguments(context, args);
  5774. }
  5775. initialise() {
  5776. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  5777. if (this.body instanceof BlockStatement) {
  5778. this.body.addImplicitReturnExpressionToScope();
  5779. }
  5780. else {
  5781. this.scope.addReturnExpression(this.body);
  5782. }
  5783. }
  5784. parseNode(esTreeNode) {
  5785. if (esTreeNode.body.type === BlockStatement$1) {
  5786. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  5787. }
  5788. super.parseNode(esTreeNode);
  5789. }
  5790. }
  5791. ArrowFunctionExpression.prototype.preventChildBlockScope = true;
  5792. class AssignmentExpression extends NodeBase {
  5793. constructor() {
  5794. super(...arguments);
  5795. this.deoptimized = false;
  5796. }
  5797. hasEffects(context) {
  5798. if (!this.deoptimized)
  5799. this.applyDeoptimizations();
  5800. return (this.right.hasEffects(context) ||
  5801. this.left.hasEffects(context) ||
  5802. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  5803. }
  5804. hasEffectsWhenAccessedAtPath(path, context) {
  5805. return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
  5806. }
  5807. include(context, includeChildrenRecursively) {
  5808. if (!this.deoptimized)
  5809. this.applyDeoptimizations();
  5810. this.included = true;
  5811. let hasEffectsContext;
  5812. if (includeChildrenRecursively ||
  5813. this.operator !== '=' ||
  5814. this.left.included ||
  5815. ((hasEffectsContext = createHasEffectsContext()),
  5816. this.left.hasEffects(hasEffectsContext) ||
  5817. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, hasEffectsContext))) {
  5818. this.left.include(context, includeChildrenRecursively);
  5819. }
  5820. this.right.include(context, includeChildrenRecursively);
  5821. }
  5822. render(code, options, { preventASI, renderedParentType } = BLANK) {
  5823. if (this.left.included) {
  5824. this.left.render(code, options);
  5825. this.right.render(code, options);
  5826. }
  5827. else {
  5828. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', this.left.end) + 1);
  5829. code.remove(this.start, inclusionStart);
  5830. if (preventASI) {
  5831. removeLineBreaks(code, inclusionStart, this.right.start);
  5832. }
  5833. this.right.render(code, options, {
  5834. renderedParentType: renderedParentType || this.parent.type
  5835. });
  5836. }
  5837. if (options.format === 'system') {
  5838. const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
  5839. if (this.left.type === 'Identifier' && exportNames) {
  5840. const _ = options.compact ? '' : ' ';
  5841. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  5842. const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
  5843. code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
  5844. ? `exports('${exportNames[0]}',${_}`
  5845. : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
  5846. code.appendLeft(this.right.end, ')');
  5847. }
  5848. else {
  5849. const systemPatternExports = [];
  5850. this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  5851. if (systemPatternExports.length > 0) {
  5852. code.prependRight(this.start, `(${getSystemExportFunctionLeft(systemPatternExports, true, options)}`);
  5853. code.appendLeft(this.end, '))');
  5854. }
  5855. }
  5856. }
  5857. }
  5858. applyDeoptimizations() {
  5859. this.deoptimized = true;
  5860. this.left.deoptimizePath(EMPTY_PATH);
  5861. this.right.deoptimizePath(UNKNOWN_PATH);
  5862. }
  5863. }
  5864. class AssignmentPattern extends NodeBase {
  5865. addExportedVariables(variables, exportNamesByVariable) {
  5866. this.left.addExportedVariables(variables, exportNamesByVariable);
  5867. }
  5868. bind() {
  5869. super.bind();
  5870. this.left.deoptimizePath(EMPTY_PATH);
  5871. this.right.deoptimizePath(UNKNOWN_PATH);
  5872. }
  5873. declare(kind, init) {
  5874. return this.left.declare(kind, init);
  5875. }
  5876. deoptimizePath(path) {
  5877. path.length === 0 && this.left.deoptimizePath(path);
  5878. }
  5879. hasEffectsWhenAssignedAtPath(path, context) {
  5880. return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  5881. }
  5882. render(code, options, { isShorthandProperty } = BLANK) {
  5883. this.left.render(code, options, { isShorthandProperty });
  5884. this.right.render(code, options);
  5885. }
  5886. }
  5887. class AwaitExpression extends NodeBase {
  5888. hasEffects(context) {
  5889. return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
  5890. }
  5891. include(context, includeChildrenRecursively) {
  5892. if (!this.included) {
  5893. this.included = true;
  5894. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  5895. let parent = this.parent;
  5896. do {
  5897. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  5898. break checkTopLevelAwait;
  5899. } while ((parent = parent.parent));
  5900. this.context.usesTopLevelAwait = true;
  5901. }
  5902. }
  5903. this.argument.include(context, includeChildrenRecursively);
  5904. }
  5905. }
  5906. const binaryOperators = {
  5907. '!=': (left, right) => left != right,
  5908. '!==': (left, right) => left !== right,
  5909. '%': (left, right) => left % right,
  5910. '&': (left, right) => left & right,
  5911. '*': (left, right) => left * right,
  5912. // At the moment, "**" will be transpiled to Math.pow
  5913. '**': (left, right) => left ** right,
  5914. '+': (left, right) => left + right,
  5915. '-': (left, right) => left - right,
  5916. '/': (left, right) => left / right,
  5917. '<': (left, right) => left < right,
  5918. '<<': (left, right) => left << right,
  5919. '<=': (left, right) => left <= right,
  5920. '==': (left, right) => left == right,
  5921. '===': (left, right) => left === right,
  5922. '>': (left, right) => left > right,
  5923. '>=': (left, right) => left >= right,
  5924. '>>': (left, right) => left >> right,
  5925. '>>>': (left, right) => left >>> right,
  5926. '^': (left, right) => left ^ right,
  5927. in: () => UnknownValue,
  5928. instanceof: () => UnknownValue,
  5929. '|': (left, right) => left | right
  5930. };
  5931. class BinaryExpression extends NodeBase {
  5932. deoptimizeCache() { }
  5933. getLiteralValueAtPath(path, recursionTracker, origin) {
  5934. if (path.length > 0)
  5935. return UnknownValue;
  5936. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  5937. if (leftValue === UnknownValue)
  5938. return UnknownValue;
  5939. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  5940. if (rightValue === UnknownValue)
  5941. return UnknownValue;
  5942. const operatorFn = binaryOperators[this.operator];
  5943. if (!operatorFn)
  5944. return UnknownValue;
  5945. return operatorFn(leftValue, rightValue);
  5946. }
  5947. hasEffects(context) {
  5948. // support some implicit type coercion runtime errors
  5949. if (this.operator === '+' &&
  5950. this.parent instanceof ExpressionStatement &&
  5951. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
  5952. return true;
  5953. return super.hasEffects(context);
  5954. }
  5955. hasEffectsWhenAccessedAtPath(path) {
  5956. return path.length > 1;
  5957. }
  5958. }
  5959. class BreakStatement extends NodeBase {
  5960. hasEffects(context) {
  5961. if (this.label) {
  5962. if (!context.ignore.labels.has(this.label.name))
  5963. return true;
  5964. context.includedLabels.add(this.label.name);
  5965. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  5966. }
  5967. else {
  5968. if (!context.ignore.breaks)
  5969. return true;
  5970. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  5971. }
  5972. return false;
  5973. }
  5974. include(context) {
  5975. this.included = true;
  5976. if (this.label) {
  5977. this.label.include();
  5978. context.includedLabels.add(this.label.name);
  5979. }
  5980. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  5981. }
  5982. }
  5983. class Literal extends NodeBase {
  5984. getLiteralValueAtPath(path) {
  5985. if (path.length > 0 ||
  5986. // unknown literals can also be null but do not start with an "n"
  5987. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  5988. typeof this.value === 'bigint' ||
  5989. // to support shims for regular expressions
  5990. this.context.code.charCodeAt(this.start) === 47) {
  5991. return UnknownValue;
  5992. }
  5993. return this.value;
  5994. }
  5995. getReturnExpressionWhenCalledAtPath(path) {
  5996. if (path.length !== 1)
  5997. return UNKNOWN_EXPRESSION;
  5998. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  5999. }
  6000. hasEffectsWhenAccessedAtPath(path) {
  6001. if (this.value === null) {
  6002. return path.length > 0;
  6003. }
  6004. return path.length > 1;
  6005. }
  6006. hasEffectsWhenAssignedAtPath(path) {
  6007. return path.length > 0;
  6008. }
  6009. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6010. if (path.length === 1) {
  6011. return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
  6012. }
  6013. return true;
  6014. }
  6015. initialise() {
  6016. this.members = getLiteralMembersForValue(this.value);
  6017. }
  6018. parseNode(esTreeNode) {
  6019. this.value = esTreeNode.value;
  6020. this.regex = esTreeNode.regex;
  6021. super.parseNode(esTreeNode);
  6022. }
  6023. render(code) {
  6024. if (typeof this.value === 'string') {
  6025. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6026. }
  6027. }
  6028. }
  6029. function getResolvablePropertyKey(memberExpression) {
  6030. return memberExpression.computed
  6031. ? getResolvableComputedPropertyKey(memberExpression.property)
  6032. : memberExpression.property.name;
  6033. }
  6034. function getResolvableComputedPropertyKey(propertyKey) {
  6035. if (propertyKey instanceof Literal) {
  6036. return String(propertyKey.value);
  6037. }
  6038. return null;
  6039. }
  6040. function getPathIfNotComputed(memberExpression) {
  6041. const nextPathKey = memberExpression.propertyKey;
  6042. const object = memberExpression.object;
  6043. if (typeof nextPathKey === 'string') {
  6044. if (object instanceof Identifier) {
  6045. return [
  6046. { key: object.name, pos: object.start },
  6047. { key: nextPathKey, pos: memberExpression.property.start }
  6048. ];
  6049. }
  6050. if (object instanceof MemberExpression) {
  6051. const parentPath = getPathIfNotComputed(object);
  6052. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6053. }
  6054. }
  6055. return null;
  6056. }
  6057. function getStringFromPath(path) {
  6058. let pathString = path[0].key;
  6059. for (let index = 1; index < path.length; index++) {
  6060. pathString += '.' + path[index].key;
  6061. }
  6062. return pathString;
  6063. }
  6064. class MemberExpression extends NodeBase {
  6065. constructor() {
  6066. super(...arguments);
  6067. this.variable = null;
  6068. this.bound = false;
  6069. this.expressionsToBeDeoptimized = [];
  6070. this.replacement = null;
  6071. this.wasPathDeoptimizedWhileOptimized = false;
  6072. }
  6073. bind() {
  6074. if (this.bound)
  6075. return;
  6076. this.bound = true;
  6077. const path = getPathIfNotComputed(this);
  6078. const baseVariable = path && this.scope.findVariable(path[0].key);
  6079. if (baseVariable && baseVariable.isNamespace) {
  6080. const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
  6081. if (!resolvedVariable) {
  6082. super.bind();
  6083. }
  6084. else if (typeof resolvedVariable === 'string') {
  6085. this.replacement = resolvedVariable;
  6086. }
  6087. else {
  6088. if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
  6089. resolvedVariable.module.suggestName(path[0].key);
  6090. }
  6091. this.variable = resolvedVariable;
  6092. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6093. }
  6094. }
  6095. else {
  6096. super.bind();
  6097. // ensure the propertyKey is set for the tree-shaking passes
  6098. this.getPropertyKey();
  6099. }
  6100. }
  6101. deoptimizeCache() {
  6102. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6103. this.expressionsToBeDeoptimized = [];
  6104. this.propertyKey = UnknownKey;
  6105. if (this.wasPathDeoptimizedWhileOptimized) {
  6106. this.object.deoptimizePath(UNKNOWN_PATH);
  6107. }
  6108. for (const expression of expressionsToBeDeoptimized) {
  6109. expression.deoptimizeCache();
  6110. }
  6111. }
  6112. deoptimizePath(path) {
  6113. if (!this.bound)
  6114. this.bind();
  6115. if (path.length === 0)
  6116. this.disallowNamespaceReassignment();
  6117. if (this.variable) {
  6118. this.variable.deoptimizePath(path);
  6119. }
  6120. else {
  6121. const propertyKey = this.getPropertyKey();
  6122. if (propertyKey === UnknownKey) {
  6123. this.object.deoptimizePath(UNKNOWN_PATH);
  6124. }
  6125. else {
  6126. this.wasPathDeoptimizedWhileOptimized = true;
  6127. this.object.deoptimizePath([propertyKey, ...path]);
  6128. }
  6129. }
  6130. }
  6131. getLiteralValueAtPath(path, recursionTracker, origin) {
  6132. if (!this.bound)
  6133. this.bind();
  6134. if (this.variable !== null) {
  6135. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6136. }
  6137. this.expressionsToBeDeoptimized.push(origin);
  6138. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6139. }
  6140. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6141. if (!this.bound)
  6142. this.bind();
  6143. if (this.variable !== null) {
  6144. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6145. }
  6146. this.expressionsToBeDeoptimized.push(origin);
  6147. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6148. }
  6149. hasEffects(context) {
  6150. return (this.property.hasEffects(context) ||
  6151. this.object.hasEffects(context) ||
  6152. (this.context.options.treeshake.propertyReadSideEffects &&
  6153. this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
  6154. }
  6155. hasEffectsWhenAccessedAtPath(path, context) {
  6156. if (path.length === 0)
  6157. return false;
  6158. if (this.variable !== null) {
  6159. return this.variable.hasEffectsWhenAccessedAtPath(path, context);
  6160. }
  6161. return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
  6162. }
  6163. hasEffectsWhenAssignedAtPath(path, context) {
  6164. if (this.variable !== null) {
  6165. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  6166. }
  6167. return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
  6168. }
  6169. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6170. if (this.variable !== null) {
  6171. return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6172. }
  6173. return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
  6174. }
  6175. include(context, includeChildrenRecursively) {
  6176. if (!this.included) {
  6177. this.included = true;
  6178. if (this.variable !== null) {
  6179. this.context.includeVariableInModule(this.variable);
  6180. }
  6181. }
  6182. this.object.include(context, includeChildrenRecursively);
  6183. this.property.include(context, includeChildrenRecursively);
  6184. }
  6185. includeCallArguments(context, args) {
  6186. if (this.variable) {
  6187. this.variable.includeCallArguments(context, args);
  6188. }
  6189. else {
  6190. super.includeCallArguments(context, args);
  6191. }
  6192. }
  6193. initialise() {
  6194. this.propertyKey = getResolvablePropertyKey(this);
  6195. }
  6196. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  6197. const isCalleeOfDifferentParent = renderedParentType === CallExpression$1 && isCalleeOfRenderedParent;
  6198. if (this.variable || this.replacement) {
  6199. let replacement = this.variable ? this.variable.getName() : this.replacement;
  6200. if (isCalleeOfDifferentParent)
  6201. replacement = '0, ' + replacement;
  6202. code.overwrite(this.start, this.end, replacement, {
  6203. contentOnly: true,
  6204. storeName: true
  6205. });
  6206. }
  6207. else {
  6208. if (isCalleeOfDifferentParent) {
  6209. code.appendRight(this.start, '0, ');
  6210. }
  6211. const surroundingElement = renderedParentType || renderedSurroundingElement;
  6212. this.object.render(code, options, surroundingElement ? { renderedSurroundingElement: surroundingElement } : BLANK);
  6213. this.property.render(code, options);
  6214. }
  6215. }
  6216. disallowNamespaceReassignment() {
  6217. if (this.object instanceof Identifier) {
  6218. const variable = this.scope.findVariable(this.object.name);
  6219. if (variable.isNamespace) {
  6220. if (this.variable) {
  6221. this.context.includeVariableInModule(this.variable);
  6222. }
  6223. this.context.warn({
  6224. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  6225. message: `Illegal reassignment to import '${this.object.name}'`
  6226. }, this.start);
  6227. }
  6228. }
  6229. }
  6230. getPropertyKey() {
  6231. if (this.propertyKey === null) {
  6232. this.propertyKey = UnknownKey;
  6233. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6234. return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
  6235. }
  6236. return this.propertyKey;
  6237. }
  6238. resolveNamespaceVariables(baseVariable, path) {
  6239. if (path.length === 0)
  6240. return baseVariable;
  6241. if (!baseVariable.isNamespace)
  6242. return null;
  6243. const exportName = path[0].key;
  6244. const variable = baseVariable instanceof ExternalVariable
  6245. ? baseVariable.module.getVariableForExportName(exportName)
  6246. : baseVariable.context.traceExport(exportName);
  6247. if (!variable) {
  6248. const fileName = baseVariable instanceof ExternalVariable
  6249. ? baseVariable.module.id
  6250. : baseVariable.context.fileName;
  6251. this.context.warn({
  6252. code: 'MISSING_EXPORT',
  6253. exporter: relativeId(fileName),
  6254. importer: relativeId(this.context.fileName),
  6255. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  6256. missing: exportName,
  6257. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  6258. }, path[0].pos);
  6259. return 'undefined';
  6260. }
  6261. return this.resolveNamespaceVariables(variable, path.slice(1));
  6262. }
  6263. }
  6264. class CallExpression extends NodeBase {
  6265. constructor() {
  6266. super(...arguments);
  6267. this.expressionsToBeDeoptimized = [];
  6268. this.returnExpression = null;
  6269. this.wasPathDeoptmizedWhileOptimized = false;
  6270. }
  6271. bind() {
  6272. super.bind();
  6273. if (this.callee instanceof Identifier) {
  6274. const variable = this.scope.findVariable(this.callee.name);
  6275. if (variable.isNamespace) {
  6276. this.context.warn({
  6277. code: 'CANNOT_CALL_NAMESPACE',
  6278. message: `Cannot call a namespace ('${this.callee.name}')`
  6279. }, this.start);
  6280. }
  6281. if (this.callee.name === 'eval') {
  6282. this.context.warn({
  6283. code: 'EVAL',
  6284. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  6285. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  6286. }, this.start);
  6287. }
  6288. }
  6289. // ensure the returnExpression is set for the tree-shaking passes
  6290. this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6291. // This deoptimizes "this" for non-namespace calls until we have a better solution
  6292. if (this.callee instanceof MemberExpression && !this.callee.variable) {
  6293. this.callee.object.deoptimizePath(UNKNOWN_PATH);
  6294. }
  6295. for (const argument of this.arguments) {
  6296. // This will make sure all properties of parameters behave as "unknown"
  6297. argument.deoptimizePath(UNKNOWN_PATH);
  6298. }
  6299. }
  6300. deoptimizeCache() {
  6301. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  6302. this.returnExpression = null;
  6303. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6304. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6305. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6306. // We need to replace here because is possible new expressions are added
  6307. // while we are deoptimizing the old ones
  6308. this.expressionsToBeDeoptimized = [];
  6309. if (this.wasPathDeoptmizedWhileOptimized) {
  6310. returnExpression.deoptimizePath(UNKNOWN_PATH);
  6311. this.wasPathDeoptmizedWhileOptimized = false;
  6312. }
  6313. }
  6314. for (const expression of expressionsToBeDeoptimized) {
  6315. expression.deoptimizeCache();
  6316. }
  6317. }
  6318. }
  6319. deoptimizePath(path) {
  6320. if (path.length === 0)
  6321. return;
  6322. const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
  6323. if (trackedEntities.has(this))
  6324. return;
  6325. trackedEntities.add(this);
  6326. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6327. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6328. this.wasPathDeoptmizedWhileOptimized = true;
  6329. returnExpression.deoptimizePath(path);
  6330. }
  6331. }
  6332. getLiteralValueAtPath(path, recursionTracker, origin) {
  6333. const returnExpression = this.getReturnExpression(recursionTracker);
  6334. if (returnExpression === UNKNOWN_EXPRESSION) {
  6335. return UnknownValue;
  6336. }
  6337. const trackedEntities = recursionTracker.getEntities(path);
  6338. if (trackedEntities.has(returnExpression)) {
  6339. return UnknownValue;
  6340. }
  6341. this.expressionsToBeDeoptimized.push(origin);
  6342. trackedEntities.add(returnExpression);
  6343. const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6344. trackedEntities.delete(returnExpression);
  6345. return value;
  6346. }
  6347. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6348. const returnExpression = this.getReturnExpression(recursionTracker);
  6349. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  6350. return UNKNOWN_EXPRESSION;
  6351. }
  6352. const trackedEntities = recursionTracker.getEntities(path);
  6353. if (trackedEntities.has(returnExpression)) {
  6354. return UNKNOWN_EXPRESSION;
  6355. }
  6356. this.expressionsToBeDeoptimized.push(origin);
  6357. trackedEntities.add(returnExpression);
  6358. const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6359. trackedEntities.delete(returnExpression);
  6360. return value;
  6361. }
  6362. hasEffects(context) {
  6363. for (const argument of this.arguments) {
  6364. if (argument.hasEffects(context))
  6365. return true;
  6366. }
  6367. if (this.context.options.treeshake.annotations &&
  6368. this.annotatedPure)
  6369. return false;
  6370. return (this.callee.hasEffects(context) ||
  6371. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  6372. }
  6373. hasEffectsWhenAccessedAtPath(path, context) {
  6374. if (path.length === 0)
  6375. return false;
  6376. const trackedExpressions = context.accessed.getEntities(path);
  6377. if (trackedExpressions.has(this))
  6378. return false;
  6379. trackedExpressions.add(this);
  6380. return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
  6381. }
  6382. hasEffectsWhenAssignedAtPath(path, context) {
  6383. if (path.length === 0)
  6384. return true;
  6385. const trackedExpressions = context.assigned.getEntities(path);
  6386. if (trackedExpressions.has(this))
  6387. return false;
  6388. trackedExpressions.add(this);
  6389. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  6390. }
  6391. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6392. const trackedExpressions = (callOptions.withNew
  6393. ? context.instantiated
  6394. : context.called).getEntities(path, callOptions);
  6395. if (trackedExpressions.has(this))
  6396. return false;
  6397. trackedExpressions.add(this);
  6398. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6399. }
  6400. include(context, includeChildrenRecursively) {
  6401. if (includeChildrenRecursively) {
  6402. super.include(context, includeChildrenRecursively);
  6403. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  6404. this.callee instanceof Identifier &&
  6405. this.callee.variable) {
  6406. this.callee.variable.markCalledFromTryStatement();
  6407. }
  6408. }
  6409. else {
  6410. this.included = true;
  6411. this.callee.include(context, false);
  6412. }
  6413. this.callee.includeCallArguments(context, this.arguments);
  6414. if (!this.returnExpression.included) {
  6415. this.returnExpression.include(context, false);
  6416. }
  6417. }
  6418. initialise() {
  6419. this.callOptions = {
  6420. args: this.arguments,
  6421. withNew: false
  6422. };
  6423. }
  6424. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  6425. const surroundingELement = renderedParentType || renderedSurroundingElement;
  6426. this.callee.render(code, options, surroundingELement ? { renderedSurroundingElement: surroundingELement } : BLANK);
  6427. if (this.arguments.length > 0) {
  6428. if (this.arguments[this.arguments.length - 1].included) {
  6429. for (const arg of this.arguments) {
  6430. arg.render(code, options);
  6431. }
  6432. }
  6433. else {
  6434. let lastIncludedIndex = this.arguments.length - 2;
  6435. while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
  6436. lastIncludedIndex--;
  6437. }
  6438. if (lastIncludedIndex >= 0) {
  6439. for (let index = 0; index <= lastIncludedIndex; index++) {
  6440. this.arguments[index].render(code, options);
  6441. }
  6442. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
  6443. }
  6444. else {
  6445. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
  6446. }
  6447. }
  6448. }
  6449. }
  6450. getReturnExpression(recursionTracker) {
  6451. if (this.returnExpression === null) {
  6452. this.returnExpression = UNKNOWN_EXPRESSION;
  6453. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
  6454. }
  6455. return this.returnExpression;
  6456. }
  6457. }
  6458. class CatchScope extends ParameterScope {
  6459. addDeclaration(identifier, context, init, isHoisted) {
  6460. if (isHoisted) {
  6461. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6462. }
  6463. else {
  6464. return super.addDeclaration(identifier, context, init, false);
  6465. }
  6466. }
  6467. }
  6468. class CatchClause extends NodeBase {
  6469. createScope(parentScope) {
  6470. this.scope = new CatchScope(parentScope, this.context);
  6471. }
  6472. initialise() {
  6473. if (this.param) {
  6474. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  6475. }
  6476. }
  6477. parseNode(esTreeNode) {
  6478. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
  6479. super.parseNode(esTreeNode);
  6480. }
  6481. }
  6482. CatchClause.prototype.preventChildBlockScope = true;
  6483. class ChainExpression extends NodeBase {
  6484. }
  6485. class ClassBodyScope extends ChildScope {
  6486. findLexicalBoundary() {
  6487. return this;
  6488. }
  6489. }
  6490. class MethodDefinition extends NodeBase {
  6491. hasEffects(context) {
  6492. return this.key.hasEffects(context);
  6493. }
  6494. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6495. return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6496. }
  6497. }
  6498. class ClassBody extends NodeBase {
  6499. createScope(parentScope) {
  6500. this.scope = new ClassBodyScope(parentScope);
  6501. }
  6502. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6503. if (path.length > 0)
  6504. return true;
  6505. return (this.classConstructor !== null &&
  6506. this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6507. }
  6508. initialise() {
  6509. for (const method of this.body) {
  6510. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  6511. this.classConstructor = method;
  6512. return;
  6513. }
  6514. }
  6515. this.classConstructor = null;
  6516. }
  6517. }
  6518. class ClassExpression extends ClassNode {
  6519. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  6520. super.render(code, options);
  6521. const surroundingElement = renderedParentType || renderedSurroundingElement;
  6522. if (surroundingElement === ExpressionStatement$1) {
  6523. code.appendRight(this.start, '(');
  6524. code.prependLeft(this.end, ')');
  6525. }
  6526. }
  6527. }
  6528. class MultiExpression {
  6529. constructor(expressions) {
  6530. this.included = false;
  6531. this.expressions = expressions;
  6532. }
  6533. deoptimizePath(path) {
  6534. for (const expression of this.expressions) {
  6535. expression.deoptimizePath(path);
  6536. }
  6537. }
  6538. getLiteralValueAtPath() {
  6539. return UnknownValue;
  6540. }
  6541. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6542. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
  6543. }
  6544. hasEffectsWhenAccessedAtPath(path, context) {
  6545. for (const expression of this.expressions) {
  6546. if (expression.hasEffectsWhenAccessedAtPath(path, context))
  6547. return true;
  6548. }
  6549. return false;
  6550. }
  6551. hasEffectsWhenAssignedAtPath(path, context) {
  6552. for (const expression of this.expressions) {
  6553. if (expression.hasEffectsWhenAssignedAtPath(path, context))
  6554. return true;
  6555. }
  6556. return false;
  6557. }
  6558. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6559. for (const expression of this.expressions) {
  6560. if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
  6561. return true;
  6562. }
  6563. return false;
  6564. }
  6565. include(context, includeChildrenRecursively) {
  6566. // This is only relevant to include values that do not have an AST representation,
  6567. // such as UnknownArrayExpression. Thus we only need to include them once.
  6568. for (const expression of this.expressions) {
  6569. if (!expression.included) {
  6570. expression.include(context, includeChildrenRecursively);
  6571. }
  6572. }
  6573. }
  6574. includeCallArguments() { }
  6575. }
  6576. class ConditionalExpression extends NodeBase {
  6577. constructor() {
  6578. super(...arguments);
  6579. this.expressionsToBeDeoptimized = [];
  6580. this.isBranchResolutionAnalysed = false;
  6581. this.usedBranch = null;
  6582. this.wasPathDeoptimizedWhileOptimized = false;
  6583. }
  6584. bind() {
  6585. super.bind();
  6586. // ensure the usedBranch is set for the tree-shaking passes
  6587. this.getUsedBranch();
  6588. }
  6589. deoptimizeCache() {
  6590. if (this.usedBranch !== null) {
  6591. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  6592. this.usedBranch = null;
  6593. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6594. this.expressionsToBeDeoptimized = [];
  6595. if (this.wasPathDeoptimizedWhileOptimized) {
  6596. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  6597. }
  6598. for (const expression of expressionsToBeDeoptimized) {
  6599. expression.deoptimizeCache();
  6600. }
  6601. }
  6602. }
  6603. deoptimizePath(path) {
  6604. if (path.length > 0) {
  6605. const usedBranch = this.getUsedBranch();
  6606. if (usedBranch === null) {
  6607. this.consequent.deoptimizePath(path);
  6608. this.alternate.deoptimizePath(path);
  6609. }
  6610. else {
  6611. this.wasPathDeoptimizedWhileOptimized = true;
  6612. usedBranch.deoptimizePath(path);
  6613. }
  6614. }
  6615. }
  6616. getLiteralValueAtPath(path, recursionTracker, origin) {
  6617. const usedBranch = this.getUsedBranch();
  6618. if (usedBranch === null)
  6619. return UnknownValue;
  6620. this.expressionsToBeDeoptimized.push(origin);
  6621. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  6622. }
  6623. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6624. const usedBranch = this.getUsedBranch();
  6625. if (usedBranch === null)
  6626. return new MultiExpression([
  6627. this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  6628. this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  6629. ]);
  6630. this.expressionsToBeDeoptimized.push(origin);
  6631. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6632. }
  6633. hasEffects(context) {
  6634. if (this.test.hasEffects(context))
  6635. return true;
  6636. if (this.usedBranch === null) {
  6637. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  6638. }
  6639. return this.usedBranch.hasEffects(context);
  6640. }
  6641. hasEffectsWhenAccessedAtPath(path, context) {
  6642. if (path.length === 0)
  6643. return false;
  6644. if (this.usedBranch === null) {
  6645. return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
  6646. this.alternate.hasEffectsWhenAccessedAtPath(path, context));
  6647. }
  6648. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  6649. }
  6650. hasEffectsWhenAssignedAtPath(path, context) {
  6651. if (path.length === 0)
  6652. return true;
  6653. if (this.usedBranch === null) {
  6654. return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
  6655. this.alternate.hasEffectsWhenAssignedAtPath(path, context));
  6656. }
  6657. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  6658. }
  6659. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6660. if (this.usedBranch === null) {
  6661. return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  6662. this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
  6663. }
  6664. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6665. }
  6666. include(context, includeChildrenRecursively) {
  6667. this.included = true;
  6668. if (includeChildrenRecursively ||
  6669. this.test.shouldBeIncluded(context) ||
  6670. this.usedBranch === null) {
  6671. this.test.include(context, includeChildrenRecursively);
  6672. this.consequent.include(context, includeChildrenRecursively);
  6673. this.alternate.include(context, includeChildrenRecursively);
  6674. }
  6675. else {
  6676. this.usedBranch.include(context, includeChildrenRecursively);
  6677. }
  6678. }
  6679. includeCallArguments(context, args) {
  6680. if (this.usedBranch === null) {
  6681. this.consequent.includeCallArguments(context, args);
  6682. this.alternate.includeCallArguments(context, args);
  6683. }
  6684. else {
  6685. this.usedBranch.includeCallArguments(context, args);
  6686. }
  6687. }
  6688. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  6689. if (!this.test.included) {
  6690. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  6691. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  6692. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  6693. : colonPos) + 1);
  6694. if (preventASI) {
  6695. removeLineBreaks(code, inclusionStart, this.usedBranch.start);
  6696. }
  6697. code.remove(this.start, inclusionStart);
  6698. if (this.consequent.included) {
  6699. code.remove(colonPos, this.end);
  6700. }
  6701. removeAnnotations(this, code);
  6702. this.usedBranch.render(code, options, {
  6703. isCalleeOfRenderedParent: renderedParentType
  6704. ? isCalleeOfRenderedParent
  6705. : this.parent.callee === this,
  6706. preventASI: true,
  6707. renderedParentType: renderedParentType || this.parent.type
  6708. });
  6709. }
  6710. else {
  6711. super.render(code, options);
  6712. }
  6713. }
  6714. getUsedBranch() {
  6715. if (this.isBranchResolutionAnalysed) {
  6716. return this.usedBranch;
  6717. }
  6718. this.isBranchResolutionAnalysed = true;
  6719. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6720. return testValue === UnknownValue
  6721. ? null
  6722. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  6723. }
  6724. }
  6725. class ContinueStatement extends NodeBase {
  6726. hasEffects(context) {
  6727. if (this.label) {
  6728. if (!context.ignore.labels.has(this.label.name))
  6729. return true;
  6730. context.includedLabels.add(this.label.name);
  6731. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6732. }
  6733. else {
  6734. if (!context.ignore.continues)
  6735. return true;
  6736. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6737. }
  6738. return false;
  6739. }
  6740. include(context) {
  6741. this.included = true;
  6742. if (this.label) {
  6743. this.label.include();
  6744. context.includedLabels.add(this.label.name);
  6745. }
  6746. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6747. }
  6748. }
  6749. class DoWhileStatement extends NodeBase {
  6750. hasEffects(context) {
  6751. if (this.test.hasEffects(context))
  6752. return true;
  6753. const { brokenFlow, ignore: { breaks, continues } } = context;
  6754. context.ignore.breaks = true;
  6755. context.ignore.continues = true;
  6756. if (this.body.hasEffects(context))
  6757. return true;
  6758. context.ignore.breaks = breaks;
  6759. context.ignore.continues = continues;
  6760. context.brokenFlow = brokenFlow;
  6761. return false;
  6762. }
  6763. include(context, includeChildrenRecursively) {
  6764. this.included = true;
  6765. this.test.include(context, includeChildrenRecursively);
  6766. const { brokenFlow } = context;
  6767. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6768. context.brokenFlow = brokenFlow;
  6769. }
  6770. }
  6771. class EmptyStatement extends NodeBase {
  6772. hasEffects() {
  6773. return false;
  6774. }
  6775. }
  6776. class ExportNamedDeclaration extends NodeBase {
  6777. bind() {
  6778. // Do not bind specifiers
  6779. if (this.declaration !== null)
  6780. this.declaration.bind();
  6781. }
  6782. hasEffects(context) {
  6783. return this.declaration !== null && this.declaration.hasEffects(context);
  6784. }
  6785. initialise() {
  6786. this.context.addExport(this);
  6787. }
  6788. render(code, options, nodeRenderOptions) {
  6789. const { start, end } = nodeRenderOptions;
  6790. if (this.declaration === null) {
  6791. code.remove(start, end);
  6792. }
  6793. else {
  6794. code.remove(this.start, this.declaration.start);
  6795. this.declaration.render(code, options, { start, end });
  6796. }
  6797. }
  6798. }
  6799. ExportNamedDeclaration.prototype.needsBoundaries = true;
  6800. class ExportSpecifier extends NodeBase {
  6801. }
  6802. class ForInStatement extends NodeBase {
  6803. bind() {
  6804. this.left.bind();
  6805. this.left.deoptimizePath(EMPTY_PATH);
  6806. this.right.bind();
  6807. this.body.bind();
  6808. }
  6809. createScope(parentScope) {
  6810. this.scope = new BlockScope(parentScope);
  6811. }
  6812. hasEffects(context) {
  6813. if ((this.left &&
  6814. (this.left.hasEffects(context) ||
  6815. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
  6816. (this.right && this.right.hasEffects(context)))
  6817. return true;
  6818. const { brokenFlow, ignore: { breaks, continues } } = context;
  6819. context.ignore.breaks = true;
  6820. context.ignore.continues = true;
  6821. if (this.body.hasEffects(context))
  6822. return true;
  6823. context.ignore.breaks = breaks;
  6824. context.ignore.continues = continues;
  6825. context.brokenFlow = brokenFlow;
  6826. return false;
  6827. }
  6828. include(context, includeChildrenRecursively) {
  6829. this.included = true;
  6830. this.left.include(context, includeChildrenRecursively || true);
  6831. this.left.deoptimizePath(EMPTY_PATH);
  6832. this.right.include(context, includeChildrenRecursively);
  6833. const { brokenFlow } = context;
  6834. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6835. context.brokenFlow = brokenFlow;
  6836. }
  6837. render(code, options) {
  6838. this.left.render(code, options, NO_SEMICOLON);
  6839. this.right.render(code, options, NO_SEMICOLON);
  6840. // handle no space between "in" and the right side
  6841. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  6842. code.prependLeft(this.right.start, ' ');
  6843. }
  6844. this.body.render(code, options);
  6845. }
  6846. }
  6847. class ForOfStatement extends NodeBase {
  6848. bind() {
  6849. this.left.bind();
  6850. this.left.deoptimizePath(EMPTY_PATH);
  6851. this.right.bind();
  6852. this.body.bind();
  6853. }
  6854. createScope(parentScope) {
  6855. this.scope = new BlockScope(parentScope);
  6856. }
  6857. hasEffects() {
  6858. // Placeholder until proper Symbol.Iterator support
  6859. return true;
  6860. }
  6861. include(context, includeChildrenRecursively) {
  6862. this.included = true;
  6863. this.left.include(context, includeChildrenRecursively || true);
  6864. this.left.deoptimizePath(EMPTY_PATH);
  6865. this.right.include(context, includeChildrenRecursively);
  6866. const { brokenFlow } = context;
  6867. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6868. context.brokenFlow = brokenFlow;
  6869. }
  6870. render(code, options) {
  6871. this.left.render(code, options, NO_SEMICOLON);
  6872. this.right.render(code, options, NO_SEMICOLON);
  6873. // handle no space between "of" and the right side
  6874. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  6875. code.prependLeft(this.right.start, ' ');
  6876. }
  6877. this.body.render(code, options);
  6878. }
  6879. }
  6880. class ForStatement extends NodeBase {
  6881. createScope(parentScope) {
  6882. this.scope = new BlockScope(parentScope);
  6883. }
  6884. hasEffects(context) {
  6885. if ((this.init && this.init.hasEffects(context)) ||
  6886. (this.test && this.test.hasEffects(context)) ||
  6887. (this.update && this.update.hasEffects(context)))
  6888. return true;
  6889. const { brokenFlow, ignore: { breaks, continues } } = context;
  6890. context.ignore.breaks = true;
  6891. context.ignore.continues = true;
  6892. if (this.body.hasEffects(context))
  6893. return true;
  6894. context.ignore.breaks = breaks;
  6895. context.ignore.continues = continues;
  6896. context.brokenFlow = brokenFlow;
  6897. return false;
  6898. }
  6899. include(context, includeChildrenRecursively) {
  6900. this.included = true;
  6901. if (this.init)
  6902. this.init.includeAsSingleStatement(context, includeChildrenRecursively);
  6903. if (this.test)
  6904. this.test.include(context, includeChildrenRecursively);
  6905. const { brokenFlow } = context;
  6906. if (this.update)
  6907. this.update.include(context, includeChildrenRecursively);
  6908. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6909. context.brokenFlow = brokenFlow;
  6910. }
  6911. render(code, options) {
  6912. if (this.init)
  6913. this.init.render(code, options, NO_SEMICOLON);
  6914. if (this.test)
  6915. this.test.render(code, options, NO_SEMICOLON);
  6916. if (this.update)
  6917. this.update.render(code, options, NO_SEMICOLON);
  6918. this.body.render(code, options);
  6919. }
  6920. }
  6921. class FunctionExpression extends FunctionNode {
  6922. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  6923. super.render(code, options);
  6924. const surroundingElement = renderedParentType || renderedSurroundingElement;
  6925. if (surroundingElement === ExpressionStatement$1) {
  6926. code.appendRight(this.start, '(');
  6927. code.prependLeft(this.end, ')');
  6928. }
  6929. }
  6930. }
  6931. class TrackingScope extends BlockScope {
  6932. constructor() {
  6933. super(...arguments);
  6934. this.hoistedDeclarations = [];
  6935. }
  6936. addDeclaration(identifier, context, init, isHoisted) {
  6937. this.hoistedDeclarations.push(identifier);
  6938. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6939. }
  6940. }
  6941. const unset = Symbol('unset');
  6942. class IfStatement extends NodeBase {
  6943. constructor() {
  6944. super(...arguments);
  6945. this.testValue = unset;
  6946. }
  6947. deoptimizeCache() {
  6948. this.testValue = UnknownValue;
  6949. }
  6950. hasEffects(context) {
  6951. if (this.test.hasEffects(context)) {
  6952. return true;
  6953. }
  6954. const testValue = this.getTestValue();
  6955. if (testValue === UnknownValue) {
  6956. const { brokenFlow } = context;
  6957. if (this.consequent.hasEffects(context))
  6958. return true;
  6959. const consequentBrokenFlow = context.brokenFlow;
  6960. context.brokenFlow = brokenFlow;
  6961. if (this.alternate === null)
  6962. return false;
  6963. if (this.alternate.hasEffects(context))
  6964. return true;
  6965. context.brokenFlow =
  6966. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  6967. return false;
  6968. }
  6969. return testValue
  6970. ? this.consequent.hasEffects(context)
  6971. : this.alternate !== null && this.alternate.hasEffects(context);
  6972. }
  6973. include(context, includeChildrenRecursively) {
  6974. this.included = true;
  6975. if (includeChildrenRecursively) {
  6976. this.includeRecursively(includeChildrenRecursively, context);
  6977. }
  6978. else {
  6979. const testValue = this.getTestValue();
  6980. if (testValue === UnknownValue) {
  6981. this.includeUnknownTest(context);
  6982. }
  6983. else {
  6984. this.includeKnownTest(context, testValue);
  6985. }
  6986. }
  6987. }
  6988. parseNode(esTreeNode) {
  6989. this.consequentScope = new TrackingScope(this.scope);
  6990. this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
  6991. this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
  6992. if (esTreeNode.alternate) {
  6993. this.alternateScope = new TrackingScope(this.scope);
  6994. this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
  6995. this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
  6996. }
  6997. super.parseNode(esTreeNode);
  6998. }
  6999. render(code, options) {
  7000. // Note that unknown test values are always included
  7001. const testValue = this.getTestValue();
  7002. const hoistedDeclarations = [];
  7003. const includesIfElse = this.test.included;
  7004. const noTreeshake = !this.context.options.treeshake;
  7005. if (includesIfElse) {
  7006. this.test.render(code, options);
  7007. }
  7008. else {
  7009. removeAnnotations(this, code);
  7010. code.remove(this.start, this.consequent.start);
  7011. }
  7012. if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
  7013. this.consequent.render(code, options);
  7014. }
  7015. else {
  7016. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  7017. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  7018. }
  7019. if (this.alternate) {
  7020. if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
  7021. if (includesIfElse) {
  7022. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  7023. code.prependLeft(this.alternate.start, ' ');
  7024. }
  7025. }
  7026. else {
  7027. code.remove(this.consequent.end, this.alternate.start);
  7028. }
  7029. this.alternate.render(code, options);
  7030. }
  7031. else {
  7032. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  7033. code.overwrite(this.alternate.start, this.end, ';');
  7034. }
  7035. else {
  7036. code.remove(this.consequent.end, this.end);
  7037. }
  7038. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  7039. }
  7040. }
  7041. this.renderHoistedDeclarations(hoistedDeclarations, code);
  7042. }
  7043. getTestValue() {
  7044. if (this.testValue === unset) {
  7045. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  7046. }
  7047. return this.testValue;
  7048. }
  7049. includeKnownTest(context, testValue) {
  7050. if (this.test.shouldBeIncluded(context)) {
  7051. this.test.include(context, false);
  7052. }
  7053. if (testValue && this.consequent.shouldBeIncluded(context)) {
  7054. this.consequent.includeAsSingleStatement(context, false);
  7055. }
  7056. if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
  7057. this.alternate.includeAsSingleStatement(context, false);
  7058. }
  7059. }
  7060. includeRecursively(includeChildrenRecursively, context) {
  7061. this.test.include(context, includeChildrenRecursively);
  7062. this.consequent.include(context, includeChildrenRecursively);
  7063. if (this.alternate !== null) {
  7064. this.alternate.include(context, includeChildrenRecursively);
  7065. }
  7066. }
  7067. includeUnknownTest(context) {
  7068. this.test.include(context, false);
  7069. const { brokenFlow } = context;
  7070. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  7071. if (this.consequent.shouldBeIncluded(context)) {
  7072. this.consequent.includeAsSingleStatement(context, false);
  7073. consequentBrokenFlow = context.brokenFlow;
  7074. context.brokenFlow = brokenFlow;
  7075. }
  7076. if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
  7077. this.alternate.includeAsSingleStatement(context, false);
  7078. context.brokenFlow =
  7079. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7080. }
  7081. }
  7082. renderHoistedDeclarations(hoistedDeclarations, code) {
  7083. const hoistedVars = [
  7084. ...new Set(hoistedDeclarations.map(identifier => {
  7085. const variable = identifier.variable;
  7086. return variable.included ? variable.getName() : '';
  7087. }))
  7088. ]
  7089. .filter(Boolean)
  7090. .join(', ');
  7091. if (hoistedVars) {
  7092. const parentType = this.parent.type;
  7093. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  7094. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  7095. if (needsBraces) {
  7096. code.appendLeft(this.end, ` }`);
  7097. }
  7098. }
  7099. }
  7100. shouldKeepAlternateBranch() {
  7101. let currentParent = this.parent;
  7102. do {
  7103. if (currentParent instanceof IfStatement && currentParent.alternate) {
  7104. return true;
  7105. }
  7106. if (currentParent instanceof BlockStatement) {
  7107. return false;
  7108. }
  7109. currentParent = currentParent.parent;
  7110. } while (currentParent);
  7111. return false;
  7112. }
  7113. }
  7114. class ImportDeclaration extends NodeBase {
  7115. bind() { }
  7116. hasEffects() {
  7117. return false;
  7118. }
  7119. initialise() {
  7120. this.context.addImport(this);
  7121. }
  7122. render(code, _options, nodeRenderOptions) {
  7123. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  7124. }
  7125. }
  7126. ImportDeclaration.prototype.needsBoundaries = true;
  7127. class ImportDefaultSpecifier extends NodeBase {
  7128. }
  7129. class ImportExpression extends NodeBase {
  7130. constructor() {
  7131. super(...arguments);
  7132. this.inlineNamespace = null;
  7133. this.mechanism = null;
  7134. this.resolution = null;
  7135. }
  7136. hasEffects() {
  7137. return true;
  7138. }
  7139. include(context, includeChildrenRecursively) {
  7140. if (!this.included) {
  7141. this.included = true;
  7142. this.context.includeDynamicImport(this);
  7143. this.scope.addAccessedDynamicImport(this);
  7144. }
  7145. this.source.include(context, includeChildrenRecursively);
  7146. }
  7147. initialise() {
  7148. this.context.addDynamicImport(this);
  7149. }
  7150. render(code, options) {
  7151. if (this.inlineNamespace) {
  7152. const _ = options.compact ? '' : ' ';
  7153. const s = options.compact ? '' : ';';
  7154. code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
  7155. return;
  7156. }
  7157. if (this.mechanism) {
  7158. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  7159. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  7160. }
  7161. this.source.render(code, options);
  7162. }
  7163. renderFinalResolution(code, resolution, namespaceExportName, options) {
  7164. code.overwrite(this.source.start, this.source.end, resolution);
  7165. if (namespaceExportName) {
  7166. const _ = options.compact ? '' : ' ';
  7167. const s = options.compact ? '' : ';';
  7168. code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
  7169. }
  7170. }
  7171. setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
  7172. this.resolution = resolution;
  7173. const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
  7174. let helper;
  7175. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
  7176. if (helper) {
  7177. accessedGlobals.push(helper);
  7178. }
  7179. if (accessedGlobals.length > 0) {
  7180. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7181. }
  7182. }
  7183. setInternalResolution(inlineNamespace) {
  7184. this.inlineNamespace = inlineNamespace;
  7185. }
  7186. getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
  7187. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  7188. {
  7189. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  7190. format: options.format,
  7191. moduleId: this.context.module.id,
  7192. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  7193. }
  7194. ]);
  7195. if (mechanism) {
  7196. return { helper: null, mechanism };
  7197. }
  7198. switch (options.format) {
  7199. case 'cjs': {
  7200. const _ = options.compact ? '' : ' ';
  7201. const s = options.compact ? '' : ';';
  7202. const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
  7203. const helper = this.getInteropHelper(resolution, exportMode, options.interop);
  7204. return {
  7205. helper,
  7206. mechanism: helper
  7207. ? {
  7208. left: `${leftStart} /*#__PURE__*/${helper}(require(`,
  7209. right: `))${s}${_}})`
  7210. }
  7211. : {
  7212. left: `${leftStart} require(`,
  7213. right: `)${s}${_}})`
  7214. }
  7215. };
  7216. }
  7217. case 'amd': {
  7218. const _ = options.compact ? '' : ' ';
  7219. const resolve = options.compact ? 'c' : 'resolve';
  7220. const reject = options.compact ? 'e' : 'reject';
  7221. const helper = this.getInteropHelper(resolution, exportMode, options.interop);
  7222. const resolveNamespace = helper
  7223. ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
  7224. : resolve;
  7225. return {
  7226. helper,
  7227. mechanism: {
  7228. left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
  7229. right: `],${_}${resolveNamespace},${_}${reject})${_}})`
  7230. }
  7231. };
  7232. }
  7233. case 'system':
  7234. return {
  7235. helper: null,
  7236. mechanism: {
  7237. left: 'module.import(',
  7238. right: ')'
  7239. }
  7240. };
  7241. case 'es':
  7242. if (options.dynamicImportFunction) {
  7243. return {
  7244. helper: null,
  7245. mechanism: {
  7246. left: `${options.dynamicImportFunction}(`,
  7247. right: ')'
  7248. }
  7249. };
  7250. }
  7251. }
  7252. return { helper: null, mechanism: null };
  7253. }
  7254. getInteropHelper(resolution, exportMode, interop) {
  7255. return exportMode === 'external'
  7256. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  7257. : exportMode === 'default'
  7258. ? getDefaultOnlyHelper()
  7259. : null;
  7260. }
  7261. }
  7262. const accessedImportGlobals = {
  7263. amd: ['require'],
  7264. cjs: ['require'],
  7265. system: ['module']
  7266. };
  7267. class ImportNamespaceSpecifier extends NodeBase {
  7268. }
  7269. class ImportSpecifier extends NodeBase {
  7270. }
  7271. class LabeledStatement extends NodeBase {
  7272. hasEffects(context) {
  7273. const brokenFlow = context.brokenFlow;
  7274. context.ignore.labels.add(this.label.name);
  7275. if (this.body.hasEffects(context))
  7276. return true;
  7277. context.ignore.labels.delete(this.label.name);
  7278. if (context.includedLabels.has(this.label.name)) {
  7279. context.includedLabels.delete(this.label.name);
  7280. context.brokenFlow = brokenFlow;
  7281. }
  7282. return false;
  7283. }
  7284. include(context, includeChildrenRecursively) {
  7285. this.included = true;
  7286. const brokenFlow = context.brokenFlow;
  7287. this.body.include(context, includeChildrenRecursively);
  7288. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  7289. this.label.include();
  7290. context.includedLabels.delete(this.label.name);
  7291. context.brokenFlow = brokenFlow;
  7292. }
  7293. }
  7294. render(code, options) {
  7295. if (this.label.included) {
  7296. this.label.render(code, options);
  7297. }
  7298. else {
  7299. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  7300. }
  7301. this.body.render(code, options);
  7302. }
  7303. }
  7304. class LogicalExpression extends NodeBase {
  7305. constructor() {
  7306. super(...arguments);
  7307. // We collect deoptimization information if usedBranch !== null
  7308. this.expressionsToBeDeoptimized = [];
  7309. this.isBranchResolutionAnalysed = false;
  7310. this.unusedBranch = null;
  7311. this.usedBranch = null;
  7312. this.wasPathDeoptimizedWhileOptimized = false;
  7313. }
  7314. bind() {
  7315. super.bind();
  7316. // ensure the usedBranch is set for the tree-shaking passes
  7317. this.getUsedBranch();
  7318. }
  7319. deoptimizeCache() {
  7320. if (this.usedBranch !== null) {
  7321. this.usedBranch = null;
  7322. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7323. this.expressionsToBeDeoptimized = [];
  7324. if (this.wasPathDeoptimizedWhileOptimized) {
  7325. this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7326. }
  7327. for (const expression of expressionsToBeDeoptimized) {
  7328. expression.deoptimizeCache();
  7329. }
  7330. }
  7331. }
  7332. deoptimizePath(path) {
  7333. const usedBranch = this.getUsedBranch();
  7334. if (usedBranch === null) {
  7335. this.left.deoptimizePath(path);
  7336. this.right.deoptimizePath(path);
  7337. }
  7338. else {
  7339. this.wasPathDeoptimizedWhileOptimized = true;
  7340. usedBranch.deoptimizePath(path);
  7341. }
  7342. }
  7343. getLiteralValueAtPath(path, recursionTracker, origin) {
  7344. const usedBranch = this.getUsedBranch();
  7345. if (usedBranch === null)
  7346. return UnknownValue;
  7347. this.expressionsToBeDeoptimized.push(origin);
  7348. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7349. }
  7350. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7351. const usedBranch = this.getUsedBranch();
  7352. if (usedBranch === null)
  7353. return new MultiExpression([
  7354. this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  7355. this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  7356. ]);
  7357. this.expressionsToBeDeoptimized.push(origin);
  7358. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7359. }
  7360. hasEffects(context) {
  7361. if (this.left.hasEffects(context)) {
  7362. return true;
  7363. }
  7364. if (this.usedBranch !== this.left) {
  7365. return this.right.hasEffects(context);
  7366. }
  7367. return false;
  7368. }
  7369. hasEffectsWhenAccessedAtPath(path, context) {
  7370. if (path.length === 0)
  7371. return false;
  7372. if (this.usedBranch === null) {
  7373. return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
  7374. this.right.hasEffectsWhenAccessedAtPath(path, context));
  7375. }
  7376. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7377. }
  7378. hasEffectsWhenAssignedAtPath(path, context) {
  7379. if (path.length === 0)
  7380. return true;
  7381. if (this.usedBranch === null) {
  7382. return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
  7383. this.right.hasEffectsWhenAssignedAtPath(path, context));
  7384. }
  7385. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7386. }
  7387. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7388. if (this.usedBranch === null) {
  7389. return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7390. this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7391. }
  7392. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7393. }
  7394. include(context, includeChildrenRecursively) {
  7395. this.included = true;
  7396. if (includeChildrenRecursively ||
  7397. (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  7398. this.usedBranch === null) {
  7399. this.left.include(context, includeChildrenRecursively);
  7400. this.right.include(context, includeChildrenRecursively);
  7401. }
  7402. else {
  7403. this.usedBranch.include(context, includeChildrenRecursively);
  7404. }
  7405. }
  7406. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  7407. if (!this.left.included || !this.right.included) {
  7408. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  7409. if (this.right.included) {
  7410. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  7411. code.remove(this.start, removePos);
  7412. if (preventASI) {
  7413. removeLineBreaks(code, removePos, this.right.start);
  7414. }
  7415. }
  7416. else {
  7417. code.remove(operatorPos, this.end);
  7418. }
  7419. removeAnnotations(this, code);
  7420. this.usedBranch.render(code, options, {
  7421. isCalleeOfRenderedParent: renderedParentType
  7422. ? isCalleeOfRenderedParent
  7423. : this.parent.callee === this,
  7424. preventASI,
  7425. renderedParentType: renderedParentType || this.parent.type
  7426. });
  7427. }
  7428. else {
  7429. this.left.render(code, options, { preventASI });
  7430. this.right.render(code, options);
  7431. }
  7432. }
  7433. getUsedBranch() {
  7434. if (!this.isBranchResolutionAnalysed) {
  7435. this.isBranchResolutionAnalysed = true;
  7436. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7437. if (leftValue === UnknownValue) {
  7438. return null;
  7439. }
  7440. else {
  7441. if ((this.operator === '||' && leftValue) ||
  7442. (this.operator === '&&' && !leftValue) ||
  7443. (this.operator === '??' && leftValue != null)) {
  7444. this.usedBranch = this.left;
  7445. this.unusedBranch = this.right;
  7446. }
  7447. else {
  7448. this.usedBranch = this.right;
  7449. this.unusedBranch = this.left;
  7450. }
  7451. }
  7452. }
  7453. return this.usedBranch;
  7454. }
  7455. }
  7456. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  7457. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  7458. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7459. class MetaProperty extends NodeBase {
  7460. addAccessedGlobals(format, accessedGlobalsByScope) {
  7461. const metaProperty = this.metaProperty;
  7462. const accessedGlobals = (metaProperty &&
  7463. (metaProperty.startsWith(FILE_PREFIX) ||
  7464. metaProperty.startsWith(ASSET_PREFIX) ||
  7465. metaProperty.startsWith(CHUNK_PREFIX))
  7466. ? accessedFileUrlGlobals
  7467. : accessedMetaUrlGlobals)[format];
  7468. if (accessedGlobals.length > 0) {
  7469. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7470. }
  7471. }
  7472. getReferencedFileName(outputPluginDriver) {
  7473. const metaProperty = this.metaProperty;
  7474. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  7475. return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
  7476. }
  7477. return null;
  7478. }
  7479. hasEffects() {
  7480. return false;
  7481. }
  7482. hasEffectsWhenAccessedAtPath(path) {
  7483. return path.length > 1;
  7484. }
  7485. include() {
  7486. if (!this.included) {
  7487. this.included = true;
  7488. if (this.meta.name === 'import') {
  7489. this.context.addImportMeta(this);
  7490. const parent = this.parent;
  7491. this.metaProperty =
  7492. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7493. ? parent.propertyKey
  7494. : null;
  7495. }
  7496. }
  7497. }
  7498. renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
  7499. var _a;
  7500. const parent = this.parent;
  7501. const metaProperty = this.metaProperty;
  7502. if (metaProperty &&
  7503. (metaProperty.startsWith(FILE_PREFIX) ||
  7504. metaProperty.startsWith(ASSET_PREFIX) ||
  7505. metaProperty.startsWith(CHUNK_PREFIX))) {
  7506. let referenceId = null;
  7507. let assetReferenceId = null;
  7508. let chunkReferenceId = null;
  7509. let fileName;
  7510. if (metaProperty.startsWith(FILE_PREFIX)) {
  7511. referenceId = metaProperty.substr(FILE_PREFIX.length);
  7512. fileName = outputPluginDriver.getFileName(referenceId);
  7513. }
  7514. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  7515. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  7516. assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
  7517. fileName = outputPluginDriver.getFileName(assetReferenceId);
  7518. }
  7519. else {
  7520. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  7521. chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
  7522. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  7523. }
  7524. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  7525. let replacement;
  7526. if (assetReferenceId !== null) {
  7527. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  7528. {
  7529. assetFileName: fileName,
  7530. chunkId,
  7531. format,
  7532. moduleId: this.context.module.id,
  7533. relativeAssetPath: relativePath
  7534. }
  7535. ]);
  7536. }
  7537. if (!replacement) {
  7538. replacement =
  7539. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  7540. {
  7541. assetReferenceId,
  7542. chunkId,
  7543. chunkReferenceId,
  7544. fileName,
  7545. format,
  7546. moduleId: this.context.module.id,
  7547. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  7548. relativePath
  7549. }
  7550. ]) || relativeUrlMechanisms[format](relativePath);
  7551. }
  7552. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7553. return;
  7554. }
  7555. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  7556. metaProperty,
  7557. {
  7558. chunkId,
  7559. format,
  7560. moduleId: this.context.module.id
  7561. }
  7562. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
  7563. if (typeof replacement === 'string') {
  7564. if (parent instanceof MemberExpression) {
  7565. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7566. }
  7567. else {
  7568. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  7569. }
  7570. }
  7571. }
  7572. }
  7573. const accessedMetaUrlGlobals = {
  7574. amd: ['document', 'module', 'URL'],
  7575. cjs: ['document', 'require', 'URL'],
  7576. es: [],
  7577. iife: ['document', 'URL'],
  7578. system: ['module'],
  7579. umd: ['document', 'require', 'URL']
  7580. };
  7581. const accessedFileUrlGlobals = {
  7582. amd: ['document', 'require', 'URL'],
  7583. cjs: ['document', 'require', 'URL'],
  7584. es: [],
  7585. iife: ['document', 'URL'],
  7586. system: ['module', 'URL'],
  7587. umd: ['document', 'require', 'URL']
  7588. };
  7589. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  7590. const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
  7591. const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
  7592. const urlMechanism = getUrl(chunkId);
  7593. return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
  7594. };
  7595. const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  7596. const relativeUrlMechanisms = {
  7597. amd: relativePath => {
  7598. if (relativePath[0] !== '.')
  7599. relativePath = './' + relativePath;
  7600. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  7601. },
  7602. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  7603. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  7604. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  7605. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  7606. umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
  7607. };
  7608. const importMetaMechanisms = {
  7609. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  7610. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  7611. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7612. system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
  7613. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
  7614. };
  7615. class NewExpression extends NodeBase {
  7616. bind() {
  7617. super.bind();
  7618. for (const argument of this.arguments) {
  7619. // This will make sure all properties of parameters behave as "unknown"
  7620. argument.deoptimizePath(UNKNOWN_PATH);
  7621. }
  7622. }
  7623. hasEffects(context) {
  7624. for (const argument of this.arguments) {
  7625. if (argument.hasEffects(context))
  7626. return true;
  7627. }
  7628. if (this.context.options.treeshake.annotations &&
  7629. this.annotatedPure)
  7630. return false;
  7631. return (this.callee.hasEffects(context) ||
  7632. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  7633. }
  7634. hasEffectsWhenAccessedAtPath(path) {
  7635. return path.length > 1;
  7636. }
  7637. initialise() {
  7638. this.callOptions = {
  7639. args: this.arguments,
  7640. withNew: true
  7641. };
  7642. }
  7643. }
  7644. class ObjectExpression extends NodeBase {
  7645. constructor() {
  7646. super(...arguments);
  7647. this.deoptimizedPaths = new Set();
  7648. // We collect deoptimization information if we can resolve a computed property access
  7649. this.expressionsToBeDeoptimized = new Map();
  7650. this.hasUnknownDeoptimizedProperty = false;
  7651. this.propertyMap = null;
  7652. this.unmatchablePropertiesRead = [];
  7653. this.unmatchablePropertiesWrite = [];
  7654. }
  7655. bind() {
  7656. super.bind();
  7657. // ensure the propertyMap is set for the tree-shaking passes
  7658. this.getPropertyMap();
  7659. }
  7660. // We could also track this per-property but this would quickly become much more complex
  7661. deoptimizeCache() {
  7662. if (!this.hasUnknownDeoptimizedProperty)
  7663. this.deoptimizeAllProperties();
  7664. }
  7665. deoptimizePath(path) {
  7666. if (this.hasUnknownDeoptimizedProperty)
  7667. return;
  7668. const propertyMap = this.getPropertyMap();
  7669. const key = path[0];
  7670. if (path.length === 1) {
  7671. if (typeof key !== 'string') {
  7672. this.deoptimizeAllProperties();
  7673. return;
  7674. }
  7675. if (!this.deoptimizedPaths.has(key)) {
  7676. this.deoptimizedPaths.add(key);
  7677. // we only deoptimizeCache exact matches as in all other cases,
  7678. // we do not return a literal value or return expression
  7679. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  7680. if (expressionsToBeDeoptimized) {
  7681. for (const expression of expressionsToBeDeoptimized) {
  7682. expression.deoptimizeCache();
  7683. }
  7684. }
  7685. }
  7686. }
  7687. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  7688. for (const property of typeof key === 'string'
  7689. ? propertyMap[key]
  7690. ? propertyMap[key].propertiesRead
  7691. : []
  7692. : this.properties) {
  7693. property.deoptimizePath(subPath);
  7694. }
  7695. }
  7696. getLiteralValueAtPath(path, recursionTracker, origin) {
  7697. const propertyMap = this.getPropertyMap();
  7698. const key = path[0];
  7699. if (path.length === 0 ||
  7700. this.hasUnknownDeoptimizedProperty ||
  7701. typeof key !== 'string' ||
  7702. this.deoptimizedPaths.has(key)) {
  7703. return UnknownValue;
  7704. }
  7705. if (path.length === 1 &&
  7706. !propertyMap[key] &&
  7707. !objectMembers[key] &&
  7708. this.unmatchablePropertiesRead.length === 0) {
  7709. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7710. return undefined;
  7711. }
  7712. if (!propertyMap[key] ||
  7713. propertyMap[key].exactMatchRead === null ||
  7714. propertyMap[key].propertiesRead.length > 1) {
  7715. return UnknownValue;
  7716. }
  7717. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7718. return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  7719. }
  7720. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7721. const propertyMap = this.getPropertyMap();
  7722. const key = path[0];
  7723. if (path.length === 0 ||
  7724. this.hasUnknownDeoptimizedProperty ||
  7725. typeof key !== 'string' ||
  7726. this.deoptimizedPaths.has(key)) {
  7727. return UNKNOWN_EXPRESSION;
  7728. }
  7729. if (path.length === 1 &&
  7730. objectMembers[key] &&
  7731. this.unmatchablePropertiesRead.length === 0 &&
  7732. (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) {
  7733. return getMemberReturnExpressionWhenCalled(objectMembers, key);
  7734. }
  7735. if (!propertyMap[key] ||
  7736. propertyMap[key].exactMatchRead === null ||
  7737. propertyMap[key].propertiesRead.length > 1) {
  7738. return UNKNOWN_EXPRESSION;
  7739. }
  7740. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7741. return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
  7742. }
  7743. hasEffectsWhenAccessedAtPath(path, context) {
  7744. if (path.length === 0)
  7745. return false;
  7746. const key = path[0];
  7747. const propertyMap = this.propertyMap;
  7748. if (path.length > 1 &&
  7749. (this.hasUnknownDeoptimizedProperty ||
  7750. typeof key !== 'string' ||
  7751. this.deoptimizedPaths.has(key) ||
  7752. !propertyMap[key] ||
  7753. propertyMap[key].exactMatchRead === null))
  7754. return true;
  7755. const subPath = path.slice(1);
  7756. for (const property of typeof key !== 'string'
  7757. ? this.properties
  7758. : propertyMap[key]
  7759. ? propertyMap[key].propertiesRead
  7760. : []) {
  7761. if (property.hasEffectsWhenAccessedAtPath(subPath, context))
  7762. return true;
  7763. }
  7764. return false;
  7765. }
  7766. hasEffectsWhenAssignedAtPath(path, context) {
  7767. const key = path[0];
  7768. const propertyMap = this.propertyMap;
  7769. if (path.length > 1 &&
  7770. (this.hasUnknownDeoptimizedProperty ||
  7771. this.deoptimizedPaths.has(key) ||
  7772. !propertyMap[key] ||
  7773. propertyMap[key].exactMatchRead === null)) {
  7774. return true;
  7775. }
  7776. const subPath = path.slice(1);
  7777. for (const property of typeof key !== 'string'
  7778. ? this.properties
  7779. : path.length > 1
  7780. ? propertyMap[key].propertiesRead
  7781. : propertyMap[key]
  7782. ? propertyMap[key].propertiesWrite
  7783. : []) {
  7784. if (property.hasEffectsWhenAssignedAtPath(subPath, context))
  7785. return true;
  7786. }
  7787. return false;
  7788. }
  7789. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7790. const key = path[0];
  7791. if (typeof key !== 'string' ||
  7792. this.hasUnknownDeoptimizedProperty ||
  7793. this.deoptimizedPaths.has(key) ||
  7794. (this.propertyMap[key]
  7795. ? !this.propertyMap[key].exactMatchRead
  7796. : path.length > 1 || !objectMembers[key])) {
  7797. return true;
  7798. }
  7799. const subPath = path.slice(1);
  7800. if (this.propertyMap[key]) {
  7801. for (const property of this.propertyMap[key].propertiesRead) {
  7802. if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
  7803. return true;
  7804. }
  7805. }
  7806. if (path.length === 1 && objectMembers[key])
  7807. return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
  7808. return false;
  7809. }
  7810. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  7811. super.render(code, options);
  7812. const surroundingElement = renderedParentType || renderedSurroundingElement;
  7813. if (surroundingElement === ExpressionStatement$1 ||
  7814. surroundingElement === ArrowFunctionExpression$1) {
  7815. code.appendRight(this.start, '(');
  7816. code.prependLeft(this.end, ')');
  7817. }
  7818. }
  7819. deoptimizeAllProperties() {
  7820. this.hasUnknownDeoptimizedProperty = true;
  7821. for (const property of this.properties) {
  7822. property.deoptimizePath(UNKNOWN_PATH);
  7823. }
  7824. for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
  7825. for (const expression of expressionsToBeDeoptimized) {
  7826. expression.deoptimizeCache();
  7827. }
  7828. }
  7829. }
  7830. getPropertyMap() {
  7831. if (this.propertyMap !== null) {
  7832. return this.propertyMap;
  7833. }
  7834. const propertyMap = (this.propertyMap = Object.create(null));
  7835. for (let index = this.properties.length - 1; index >= 0; index--) {
  7836. const property = this.properties[index];
  7837. if (property instanceof SpreadElement) {
  7838. this.unmatchablePropertiesRead.push(property);
  7839. continue;
  7840. }
  7841. const isWrite = property.kind !== 'get';
  7842. const isRead = property.kind !== 'set';
  7843. let key;
  7844. if (property.computed) {
  7845. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7846. if (keyValue === UnknownValue) {
  7847. if (isRead) {
  7848. this.unmatchablePropertiesRead.push(property);
  7849. }
  7850. else {
  7851. this.unmatchablePropertiesWrite.push(property);
  7852. }
  7853. continue;
  7854. }
  7855. key = String(keyValue);
  7856. }
  7857. else if (property.key instanceof Identifier) {
  7858. key = property.key.name;
  7859. }
  7860. else {
  7861. key = String(property.key.value);
  7862. }
  7863. const propertyMapProperty = propertyMap[key];
  7864. if (!propertyMapProperty) {
  7865. propertyMap[key] = {
  7866. exactMatchRead: isRead ? property : null,
  7867. exactMatchWrite: isWrite ? property : null,
  7868. propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
  7869. propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
  7870. };
  7871. continue;
  7872. }
  7873. if (isRead && propertyMapProperty.exactMatchRead === null) {
  7874. propertyMapProperty.exactMatchRead = property;
  7875. propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
  7876. }
  7877. if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
  7878. propertyMapProperty.exactMatchWrite = property;
  7879. propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
  7880. }
  7881. }
  7882. return propertyMap;
  7883. }
  7884. }
  7885. class ObjectPattern extends NodeBase {
  7886. addExportedVariables(variables, exportNamesByVariable) {
  7887. for (const property of this.properties) {
  7888. if (property.type === Property$1) {
  7889. property.value.addExportedVariables(variables, exportNamesByVariable);
  7890. }
  7891. else {
  7892. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7893. }
  7894. }
  7895. }
  7896. declare(kind, init) {
  7897. const variables = [];
  7898. for (const property of this.properties) {
  7899. variables.push(...property.declare(kind, init));
  7900. }
  7901. return variables;
  7902. }
  7903. deoptimizePath(path) {
  7904. if (path.length === 0) {
  7905. for (const property of this.properties) {
  7906. property.deoptimizePath(path);
  7907. }
  7908. }
  7909. }
  7910. hasEffectsWhenAssignedAtPath(path, context) {
  7911. if (path.length > 0)
  7912. return true;
  7913. for (const property of this.properties) {
  7914. if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  7915. return true;
  7916. }
  7917. return false;
  7918. }
  7919. }
  7920. class PrivateIdentifier extends NodeBase {
  7921. }
  7922. class Program extends NodeBase {
  7923. constructor() {
  7924. super(...arguments);
  7925. this.hasCachedEffect = false;
  7926. }
  7927. hasEffects(context) {
  7928. // We are caching here to later more efficiently identify side-effect-free modules
  7929. if (this.hasCachedEffect)
  7930. return true;
  7931. for (const node of this.body) {
  7932. if (node.hasEffects(context)) {
  7933. return (this.hasCachedEffect = true);
  7934. }
  7935. }
  7936. return false;
  7937. }
  7938. include(context, includeChildrenRecursively) {
  7939. this.included = true;
  7940. for (const node of this.body) {
  7941. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  7942. node.include(context, includeChildrenRecursively);
  7943. }
  7944. }
  7945. }
  7946. render(code, options) {
  7947. if (this.body.length) {
  7948. renderStatementList(this.body, code, this.start, this.end, options);
  7949. }
  7950. else {
  7951. super.render(code, options);
  7952. }
  7953. }
  7954. }
  7955. class Property extends NodeBase {
  7956. constructor() {
  7957. super(...arguments);
  7958. this.declarationInit = null;
  7959. this.returnExpression = null;
  7960. }
  7961. bind() {
  7962. super.bind();
  7963. if (this.kind === 'get') {
  7964. // ensure the returnExpression is set for the tree-shaking passes
  7965. this.getReturnExpression();
  7966. }
  7967. if (this.declarationInit !== null) {
  7968. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7969. }
  7970. }
  7971. declare(kind, init) {
  7972. this.declarationInit = init;
  7973. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  7974. }
  7975. // As getter properties directly receive their values from function expressions that always
  7976. // have a fixed return value, there is no known situation where a getter is deoptimized.
  7977. deoptimizeCache() { }
  7978. deoptimizePath(path) {
  7979. if (this.kind === 'get') {
  7980. this.getReturnExpression().deoptimizePath(path);
  7981. }
  7982. else {
  7983. this.value.deoptimizePath(path);
  7984. }
  7985. }
  7986. getLiteralValueAtPath(path, recursionTracker, origin) {
  7987. if (this.kind === 'get') {
  7988. return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
  7989. }
  7990. return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
  7991. }
  7992. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7993. if (this.kind === 'get') {
  7994. return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7995. }
  7996. return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7997. }
  7998. hasEffects(context) {
  7999. return this.key.hasEffects(context) || this.value.hasEffects(context);
  8000. }
  8001. hasEffectsWhenAccessedAtPath(path, context) {
  8002. if (this.kind === 'get') {
  8003. const trackedExpressions = context.accessed.getEntities(path);
  8004. if (trackedExpressions.has(this))
  8005. return false;
  8006. trackedExpressions.add(this);
  8007. return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
  8008. (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
  8009. }
  8010. return this.value.hasEffectsWhenAccessedAtPath(path, context);
  8011. }
  8012. hasEffectsWhenAssignedAtPath(path, context) {
  8013. if (this.kind === 'get') {
  8014. const trackedExpressions = context.assigned.getEntities(path);
  8015. if (trackedExpressions.has(this))
  8016. return false;
  8017. trackedExpressions.add(this);
  8018. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  8019. }
  8020. if (this.kind === 'set') {
  8021. const trackedExpressions = context.assigned.getEntities(path);
  8022. if (trackedExpressions.has(this))
  8023. return false;
  8024. trackedExpressions.add(this);
  8025. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  8026. }
  8027. return this.value.hasEffectsWhenAssignedAtPath(path, context);
  8028. }
  8029. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8030. if (this.kind === 'get') {
  8031. const trackedExpressions = (callOptions.withNew
  8032. ? context.instantiated
  8033. : context.called).getEntities(path, callOptions);
  8034. if (trackedExpressions.has(this))
  8035. return false;
  8036. trackedExpressions.add(this);
  8037. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8038. }
  8039. return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8040. }
  8041. initialise() {
  8042. this.accessorCallOptions = {
  8043. args: NO_ARGS,
  8044. withNew: false
  8045. };
  8046. }
  8047. render(code, options) {
  8048. if (!this.shorthand) {
  8049. this.key.render(code, options);
  8050. }
  8051. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  8052. }
  8053. getReturnExpression() {
  8054. if (this.returnExpression === null) {
  8055. this.returnExpression = UNKNOWN_EXPRESSION;
  8056. return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  8057. }
  8058. return this.returnExpression;
  8059. }
  8060. }
  8061. class PropertyDefinition extends NodeBase {
  8062. hasEffects(context) {
  8063. return (this.key.hasEffects(context) ||
  8064. (this.static && this.value !== null && this.value.hasEffects(context)));
  8065. }
  8066. }
  8067. class ReturnStatement extends NodeBase {
  8068. hasEffects(context) {
  8069. if (!context.ignore.returnAwaitYield ||
  8070. (this.argument !== null && this.argument.hasEffects(context)))
  8071. return true;
  8072. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8073. return false;
  8074. }
  8075. include(context, includeChildrenRecursively) {
  8076. this.included = true;
  8077. if (this.argument) {
  8078. this.argument.include(context, includeChildrenRecursively);
  8079. }
  8080. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8081. }
  8082. initialise() {
  8083. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  8084. }
  8085. render(code, options) {
  8086. if (this.argument) {
  8087. this.argument.render(code, options, { preventASI: true });
  8088. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  8089. code.prependLeft(this.start + 6, ' ');
  8090. }
  8091. }
  8092. }
  8093. }
  8094. class SequenceExpression extends NodeBase {
  8095. deoptimizePath(path) {
  8096. if (path.length > 0)
  8097. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  8098. }
  8099. getLiteralValueAtPath(path, recursionTracker, origin) {
  8100. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  8101. }
  8102. hasEffects(context) {
  8103. for (const expression of this.expressions) {
  8104. if (expression.hasEffects(context))
  8105. return true;
  8106. }
  8107. return false;
  8108. }
  8109. hasEffectsWhenAccessedAtPath(path, context) {
  8110. return (path.length > 0 &&
  8111. this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
  8112. }
  8113. hasEffectsWhenAssignedAtPath(path, context) {
  8114. return (path.length === 0 ||
  8115. this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
  8116. }
  8117. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8118. return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
  8119. }
  8120. include(context, includeChildrenRecursively) {
  8121. this.included = true;
  8122. for (let i = 0; i < this.expressions.length - 1; i++) {
  8123. const node = this.expressions[i];
  8124. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8125. node.include(context, includeChildrenRecursively);
  8126. }
  8127. this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
  8128. }
  8129. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  8130. let includedNodes = 0;
  8131. for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  8132. if (!node.included) {
  8133. treeshakeNode(node, code, start, end);
  8134. continue;
  8135. }
  8136. includedNodes++;
  8137. if (includedNodes === 1 && preventASI) {
  8138. removeLineBreaks(code, start, node.start);
  8139. }
  8140. if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
  8141. node.render(code, options, {
  8142. isCalleeOfRenderedParent: renderedParentType
  8143. ? isCalleeOfRenderedParent
  8144. : this.parent.callee === this,
  8145. renderedParentType: renderedParentType || this.parent.type
  8146. });
  8147. }
  8148. else {
  8149. node.render(code, options);
  8150. }
  8151. }
  8152. }
  8153. }
  8154. class Super extends NodeBase {
  8155. }
  8156. class SwitchCase extends NodeBase {
  8157. hasEffects(context) {
  8158. if (this.test && this.test.hasEffects(context))
  8159. return true;
  8160. for (const node of this.consequent) {
  8161. if (context.brokenFlow)
  8162. break;
  8163. if (node.hasEffects(context))
  8164. return true;
  8165. }
  8166. return false;
  8167. }
  8168. include(context, includeChildrenRecursively) {
  8169. this.included = true;
  8170. if (this.test)
  8171. this.test.include(context, includeChildrenRecursively);
  8172. for (const node of this.consequent) {
  8173. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8174. node.include(context, includeChildrenRecursively);
  8175. }
  8176. }
  8177. render(code, options, nodeRenderOptions) {
  8178. if (this.consequent.length) {
  8179. this.test && this.test.render(code, options);
  8180. const testEnd = this.test
  8181. ? this.test.end
  8182. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  8183. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  8184. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  8185. }
  8186. else {
  8187. super.render(code, options);
  8188. }
  8189. }
  8190. }
  8191. SwitchCase.prototype.needsBoundaries = true;
  8192. class SwitchStatement extends NodeBase {
  8193. createScope(parentScope) {
  8194. this.scope = new BlockScope(parentScope);
  8195. }
  8196. hasEffects(context) {
  8197. if (this.discriminant.hasEffects(context))
  8198. return true;
  8199. const { brokenFlow, ignore: { breaks } } = context;
  8200. let minBrokenFlow = Infinity;
  8201. context.ignore.breaks = true;
  8202. for (const switchCase of this.cases) {
  8203. if (switchCase.hasEffects(context))
  8204. return true;
  8205. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  8206. context.brokenFlow = brokenFlow;
  8207. }
  8208. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8209. context.brokenFlow = minBrokenFlow;
  8210. }
  8211. context.ignore.breaks = breaks;
  8212. return false;
  8213. }
  8214. include(context, includeChildrenRecursively) {
  8215. this.included = true;
  8216. this.discriminant.include(context, includeChildrenRecursively);
  8217. const { brokenFlow } = context;
  8218. let minBrokenFlow = Infinity;
  8219. let isCaseIncluded = includeChildrenRecursively ||
  8220. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  8221. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  8222. const switchCase = this.cases[caseIndex];
  8223. if (switchCase.included) {
  8224. isCaseIncluded = true;
  8225. }
  8226. if (!isCaseIncluded) {
  8227. const hasEffectsContext = createHasEffectsContext();
  8228. hasEffectsContext.ignore.breaks = true;
  8229. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  8230. }
  8231. if (isCaseIncluded) {
  8232. switchCase.include(context, includeChildrenRecursively);
  8233. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  8234. context.brokenFlow = brokenFlow;
  8235. }
  8236. else {
  8237. minBrokenFlow = brokenFlow;
  8238. }
  8239. }
  8240. if (isCaseIncluded &&
  8241. this.defaultCase !== null &&
  8242. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8243. context.brokenFlow = minBrokenFlow;
  8244. }
  8245. }
  8246. initialise() {
  8247. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  8248. if (this.cases[caseIndex].test === null) {
  8249. this.defaultCase = caseIndex;
  8250. return;
  8251. }
  8252. }
  8253. this.defaultCase = null;
  8254. }
  8255. render(code, options) {
  8256. this.discriminant.render(code, options);
  8257. if (this.cases.length > 0) {
  8258. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  8259. }
  8260. }
  8261. }
  8262. class TaggedTemplateExpression extends NodeBase {
  8263. bind() {
  8264. super.bind();
  8265. if (this.tag.type === Identifier$1) {
  8266. const name = this.tag.name;
  8267. const variable = this.scope.findVariable(name);
  8268. if (variable.isNamespace) {
  8269. this.context.warn({
  8270. code: 'CANNOT_CALL_NAMESPACE',
  8271. message: `Cannot call a namespace ('${name}')`,
  8272. }, this.start);
  8273. }
  8274. if (name === 'eval') {
  8275. this.context.warn({
  8276. code: 'EVAL',
  8277. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8278. url: 'https://rollupjs.org/guide/en/#avoiding-eval',
  8279. }, this.start);
  8280. }
  8281. }
  8282. }
  8283. hasEffects(context) {
  8284. return (super.hasEffects(context) ||
  8285. this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8286. }
  8287. initialise() {
  8288. this.callOptions = {
  8289. args: NO_ARGS,
  8290. withNew: false,
  8291. };
  8292. }
  8293. }
  8294. class TemplateElement extends NodeBase {
  8295. bind() { }
  8296. hasEffects() {
  8297. return false;
  8298. }
  8299. include() {
  8300. this.included = true;
  8301. }
  8302. parseNode(esTreeNode) {
  8303. this.value = esTreeNode.value;
  8304. super.parseNode(esTreeNode);
  8305. }
  8306. render() { }
  8307. }
  8308. class TemplateLiteral extends NodeBase {
  8309. getLiteralValueAtPath(path) {
  8310. if (path.length > 0 || this.quasis.length !== 1) {
  8311. return UnknownValue;
  8312. }
  8313. return this.quasis[0].value.cooked;
  8314. }
  8315. render(code, options) {
  8316. code.indentExclusionRanges.push([this.start, this.end]);
  8317. super.render(code, options);
  8318. }
  8319. }
  8320. class ModuleScope extends ChildScope {
  8321. constructor(parent, context) {
  8322. super(parent);
  8323. this.context = context;
  8324. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  8325. }
  8326. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  8327. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  8328. this.variables.set('default', variable);
  8329. return variable;
  8330. }
  8331. addNamespaceMemberAccess() { }
  8332. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8333. // all module level variables are already deconflicted when deconflicting the chunk
  8334. for (const scope of this.children)
  8335. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8336. }
  8337. findLexicalBoundary() {
  8338. return this;
  8339. }
  8340. findVariable(name) {
  8341. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8342. if (knownVariable) {
  8343. return knownVariable;
  8344. }
  8345. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  8346. if (variable instanceof GlobalVariable) {
  8347. this.accessedOutsideVariables.set(name, variable);
  8348. }
  8349. return variable;
  8350. }
  8351. }
  8352. class ThisExpression extends NodeBase {
  8353. bind() {
  8354. super.bind();
  8355. this.variable = this.scope.findVariable('this');
  8356. }
  8357. hasEffectsWhenAccessedAtPath(path, context) {
  8358. return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  8359. }
  8360. hasEffectsWhenAssignedAtPath(path, context) {
  8361. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  8362. }
  8363. initialise() {
  8364. this.alias =
  8365. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  8366. if (this.alias === 'undefined') {
  8367. this.context.warn({
  8368. code: 'THIS_IS_UNDEFINED',
  8369. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  8370. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  8371. }, this.start);
  8372. }
  8373. }
  8374. render(code) {
  8375. if (this.alias !== null) {
  8376. code.overwrite(this.start, this.end, this.alias, {
  8377. contentOnly: false,
  8378. storeName: true
  8379. });
  8380. }
  8381. }
  8382. }
  8383. class ThrowStatement extends NodeBase {
  8384. hasEffects() {
  8385. return true;
  8386. }
  8387. include(context, includeChildrenRecursively) {
  8388. this.included = true;
  8389. this.argument.include(context, includeChildrenRecursively);
  8390. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8391. }
  8392. render(code, options) {
  8393. this.argument.render(code, options, { preventASI: true });
  8394. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  8395. code.prependLeft(this.start + 5, ' ');
  8396. }
  8397. }
  8398. }
  8399. class TryStatement extends NodeBase {
  8400. constructor() {
  8401. super(...arguments);
  8402. this.directlyIncluded = false;
  8403. this.includedLabelsAfterBlock = null;
  8404. }
  8405. hasEffects(context) {
  8406. return ((this.context.options.treeshake.tryCatchDeoptimization
  8407. ? this.block.body.length > 0
  8408. : this.block.hasEffects(context)) ||
  8409. (this.finalizer !== null && this.finalizer.hasEffects(context)));
  8410. }
  8411. include(context, includeChildrenRecursively) {
  8412. var _a;
  8413. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  8414. const { brokenFlow } = context;
  8415. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  8416. this.included = true;
  8417. this.directlyIncluded = true;
  8418. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  8419. if (context.includedLabels.size > 0) {
  8420. this.includedLabelsAfterBlock = [...context.includedLabels];
  8421. }
  8422. context.brokenFlow = brokenFlow;
  8423. }
  8424. else if (this.includedLabelsAfterBlock) {
  8425. for (const label of this.includedLabelsAfterBlock) {
  8426. context.includedLabels.add(label);
  8427. }
  8428. }
  8429. if (this.handler !== null) {
  8430. this.handler.include(context, includeChildrenRecursively);
  8431. context.brokenFlow = brokenFlow;
  8432. }
  8433. if (this.finalizer !== null) {
  8434. this.finalizer.include(context, includeChildrenRecursively);
  8435. }
  8436. }
  8437. }
  8438. const unaryOperators = {
  8439. '!': value => !value,
  8440. '+': value => +value,
  8441. '-': value => -value,
  8442. delete: () => UnknownValue,
  8443. typeof: value => typeof value,
  8444. void: () => undefined,
  8445. '~': value => ~value
  8446. };
  8447. class UnaryExpression extends NodeBase {
  8448. bind() {
  8449. super.bind();
  8450. if (this.operator === 'delete') {
  8451. this.argument.deoptimizePath(EMPTY_PATH);
  8452. }
  8453. }
  8454. getLiteralValueAtPath(path, recursionTracker, origin) {
  8455. if (path.length > 0)
  8456. return UnknownValue;
  8457. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8458. if (argumentValue === UnknownValue)
  8459. return UnknownValue;
  8460. return unaryOperators[this.operator](argumentValue);
  8461. }
  8462. hasEffects(context) {
  8463. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  8464. return false;
  8465. return (this.argument.hasEffects(context) ||
  8466. (this.operator === 'delete' &&
  8467. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
  8468. }
  8469. hasEffectsWhenAccessedAtPath(path) {
  8470. if (this.operator === 'void') {
  8471. return path.length > 0;
  8472. }
  8473. return path.length > 1;
  8474. }
  8475. }
  8476. class UnknownNode extends NodeBase {
  8477. hasEffects() {
  8478. return true;
  8479. }
  8480. include(context) {
  8481. super.include(context, true);
  8482. }
  8483. }
  8484. class UpdateExpression extends NodeBase {
  8485. bind() {
  8486. super.bind();
  8487. this.argument.deoptimizePath(EMPTY_PATH);
  8488. if (this.argument instanceof Identifier) {
  8489. const variable = this.scope.findVariable(this.argument.name);
  8490. variable.isReassigned = true;
  8491. }
  8492. }
  8493. hasEffects(context) {
  8494. return (this.argument.hasEffects(context) ||
  8495. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  8496. }
  8497. hasEffectsWhenAccessedAtPath(path) {
  8498. return path.length > 1;
  8499. }
  8500. render(code, options) {
  8501. this.argument.render(code, options);
  8502. if (options.format === 'system') {
  8503. const variable = this.argument.variable;
  8504. const exportNames = options.exportNamesByVariable.get(variable);
  8505. if (exportNames && exportNames.length) {
  8506. const _ = options.compact ? '' : ' ';
  8507. const name = variable.getName();
  8508. if (this.prefix) {
  8509. if (exportNames.length === 1) {
  8510. code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
  8511. }
  8512. else {
  8513. code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
  8514. }
  8515. }
  8516. else if (exportNames.length > 1) {
  8517. code.overwrite(this.start, this.end, `(${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name}))`);
  8518. }
  8519. else {
  8520. let op;
  8521. switch (this.operator) {
  8522. case '++':
  8523. op = `${name}${_}+${_}1`;
  8524. break;
  8525. case '--':
  8526. op = `${name}${_}-${_}1`;
  8527. break;
  8528. }
  8529. code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
  8530. }
  8531. }
  8532. }
  8533. }
  8534. }
  8535. function isReassignedExportsMember(variable, exportNamesByVariable) {
  8536. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  8537. }
  8538. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  8539. for (const declarator of declarations) {
  8540. if (!declarator.id.included)
  8541. return false;
  8542. if (declarator.id.type === Identifier$1) {
  8543. if (exportNamesByVariable.has(declarator.id.variable))
  8544. return false;
  8545. }
  8546. else {
  8547. const exportedVariables = [];
  8548. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  8549. if (exportedVariables.length > 0)
  8550. return false;
  8551. }
  8552. }
  8553. return true;
  8554. }
  8555. class VariableDeclaration extends NodeBase {
  8556. deoptimizePath() {
  8557. for (const declarator of this.declarations) {
  8558. declarator.deoptimizePath(EMPTY_PATH);
  8559. }
  8560. }
  8561. hasEffectsWhenAssignedAtPath() {
  8562. return false;
  8563. }
  8564. include(context, includeChildrenRecursively) {
  8565. this.included = true;
  8566. for (const declarator of this.declarations) {
  8567. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  8568. declarator.include(context, includeChildrenRecursively);
  8569. }
  8570. }
  8571. includeAsSingleStatement(context, includeChildrenRecursively) {
  8572. this.included = true;
  8573. for (const declarator of this.declarations) {
  8574. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  8575. declarator.include(context, includeChildrenRecursively);
  8576. declarator.id.include(context, includeChildrenRecursively);
  8577. }
  8578. }
  8579. }
  8580. initialise() {
  8581. for (const declarator of this.declarations) {
  8582. declarator.declareDeclarator(this.kind);
  8583. }
  8584. }
  8585. render(code, options, nodeRenderOptions = BLANK) {
  8586. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  8587. for (const declarator of this.declarations) {
  8588. declarator.render(code, options);
  8589. }
  8590. if (!nodeRenderOptions.isNoStatement &&
  8591. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  8592. code.appendLeft(this.end, ';');
  8593. }
  8594. }
  8595. else {
  8596. this.renderReplacedDeclarations(code, options, nodeRenderOptions);
  8597. }
  8598. }
  8599. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement) {
  8600. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  8601. code.remove(this.end - 1, this.end);
  8602. }
  8603. if (!isNoStatement) {
  8604. separatorString += ';';
  8605. }
  8606. if (lastSeparatorPos !== null) {
  8607. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  8608. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  8609. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  8610. actualContentEnd--;
  8611. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  8612. actualContentEnd--;
  8613. }
  8614. }
  8615. if (actualContentEnd === lastSeparatorPos + 1) {
  8616. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  8617. }
  8618. else {
  8619. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8620. code.remove(actualContentEnd, renderedContentEnd);
  8621. }
  8622. }
  8623. else {
  8624. code.appendLeft(renderedContentEnd, separatorString);
  8625. }
  8626. if (systemPatternExports.length > 0) {
  8627. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  8628. }
  8629. }
  8630. renderReplacedDeclarations(code, options, { isNoStatement }) {
  8631. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  8632. let actualContentEnd, renderedContentEnd;
  8633. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  8634. let lastSeparatorPos = renderedContentEnd - 1;
  8635. code.remove(this.start, lastSeparatorPos);
  8636. let isInDeclaration = false;
  8637. let hasRenderedContent = false;
  8638. let separatorString = '', leadingString, nextSeparatorString;
  8639. const systemPatternExports = [];
  8640. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  8641. if (!node.included) {
  8642. code.remove(start, end);
  8643. continue;
  8644. }
  8645. leadingString = '';
  8646. nextSeparatorString = '';
  8647. if (!node.id.included ||
  8648. (node.id instanceof Identifier &&
  8649. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  8650. if (hasRenderedContent) {
  8651. separatorString += ';';
  8652. }
  8653. isInDeclaration = false;
  8654. }
  8655. else {
  8656. if (options.format === 'system' && node.init !== null) {
  8657. if (node.id.type !== Identifier$1) {
  8658. node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  8659. }
  8660. else {
  8661. const exportNames = options.exportNamesByVariable.get(node.id.variable);
  8662. if (exportNames) {
  8663. const _ = options.compact ? '' : ' ';
  8664. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  8665. code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
  8666. ? `exports('${exportNames[0]}',${_}`
  8667. : getSystemExportFunctionLeft([node.id.variable], false, options));
  8668. nextSeparatorString += ')';
  8669. }
  8670. }
  8671. }
  8672. if (isInDeclaration) {
  8673. separatorString += ',';
  8674. }
  8675. else {
  8676. if (hasRenderedContent) {
  8677. separatorString += ';';
  8678. }
  8679. leadingString += `${this.kind} `;
  8680. isInDeclaration = true;
  8681. }
  8682. }
  8683. if (renderedContentEnd === lastSeparatorPos + 1) {
  8684. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  8685. }
  8686. else {
  8687. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8688. code.appendLeft(renderedContentEnd, leadingString);
  8689. }
  8690. node.render(code, options);
  8691. actualContentEnd = contentEnd;
  8692. renderedContentEnd = end;
  8693. hasRenderedContent = true;
  8694. lastSeparatorPos = separator;
  8695. separatorString = nextSeparatorString;
  8696. }
  8697. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement);
  8698. }
  8699. }
  8700. class VariableDeclarator extends NodeBase {
  8701. declareDeclarator(kind) {
  8702. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  8703. }
  8704. deoptimizePath(path) {
  8705. this.id.deoptimizePath(path);
  8706. }
  8707. hasEffects(context) {
  8708. return this.id.hasEffects(context) || (this.init !== null && this.init.hasEffects(context));
  8709. }
  8710. include(context, includeChildrenRecursively) {
  8711. this.included = true;
  8712. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  8713. this.id.include(context, includeChildrenRecursively);
  8714. }
  8715. if (this.init) {
  8716. this.init.include(context, includeChildrenRecursively);
  8717. }
  8718. }
  8719. render(code, options) {
  8720. const renderId = this.id.included;
  8721. if (renderId) {
  8722. this.id.render(code, options);
  8723. }
  8724. else {
  8725. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  8726. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  8727. }
  8728. if (this.init) {
  8729. this.init.render(code, options, renderId ? BLANK : { renderedParentType: ExpressionStatement$1 });
  8730. }
  8731. else if (this.id instanceof Identifier &&
  8732. isReassignedExportsMember(this.id.variable, options.exportNamesByVariable)) {
  8733. const _ = options.compact ? '' : ' ';
  8734. code.appendLeft(this.end, `${_}=${_}void 0`);
  8735. }
  8736. }
  8737. }
  8738. class WhileStatement extends NodeBase {
  8739. hasEffects(context) {
  8740. if (this.test.hasEffects(context))
  8741. return true;
  8742. const { brokenFlow, ignore: { breaks, continues } } = context;
  8743. context.ignore.breaks = true;
  8744. context.ignore.continues = true;
  8745. if (this.body.hasEffects(context))
  8746. return true;
  8747. context.ignore.breaks = breaks;
  8748. context.ignore.continues = continues;
  8749. context.brokenFlow = brokenFlow;
  8750. return false;
  8751. }
  8752. include(context, includeChildrenRecursively) {
  8753. this.included = true;
  8754. this.test.include(context, includeChildrenRecursively);
  8755. const { brokenFlow } = context;
  8756. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  8757. context.brokenFlow = brokenFlow;
  8758. }
  8759. }
  8760. class YieldExpression extends NodeBase {
  8761. bind() {
  8762. super.bind();
  8763. if (this.argument !== null) {
  8764. this.argument.deoptimizePath(UNKNOWN_PATH);
  8765. }
  8766. }
  8767. hasEffects(context) {
  8768. return (!context.ignore.returnAwaitYield ||
  8769. (this.argument !== null && this.argument.hasEffects(context)));
  8770. }
  8771. render(code, options) {
  8772. if (this.argument) {
  8773. this.argument.render(code, options, { preventASI: true });
  8774. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  8775. code.prependLeft(this.start + 5, ' ');
  8776. }
  8777. }
  8778. }
  8779. }
  8780. const nodeConstructors = {
  8781. ArrayExpression,
  8782. ArrayPattern,
  8783. ArrowFunctionExpression,
  8784. AssignmentExpression,
  8785. AssignmentPattern,
  8786. AwaitExpression,
  8787. BinaryExpression,
  8788. BlockStatement,
  8789. BreakStatement,
  8790. CallExpression,
  8791. CatchClause,
  8792. ChainExpression,
  8793. ClassBody,
  8794. ClassDeclaration,
  8795. ClassExpression,
  8796. ConditionalExpression,
  8797. ContinueStatement,
  8798. DoWhileStatement,
  8799. EmptyStatement,
  8800. ExportAllDeclaration,
  8801. ExportDefaultDeclaration,
  8802. ExportNamedDeclaration,
  8803. ExportSpecifier,
  8804. ExpressionStatement,
  8805. ForInStatement,
  8806. ForOfStatement,
  8807. ForStatement,
  8808. FunctionDeclaration,
  8809. FunctionExpression,
  8810. Identifier,
  8811. IfStatement,
  8812. ImportDeclaration,
  8813. ImportDefaultSpecifier,
  8814. ImportExpression,
  8815. ImportNamespaceSpecifier,
  8816. ImportSpecifier,
  8817. LabeledStatement,
  8818. Literal,
  8819. LogicalExpression,
  8820. MemberExpression,
  8821. MetaProperty,
  8822. MethodDefinition,
  8823. NewExpression,
  8824. ObjectExpression,
  8825. ObjectPattern,
  8826. PrivateIdentifier,
  8827. Program,
  8828. Property,
  8829. PropertyDefinition,
  8830. RestElement,
  8831. ReturnStatement,
  8832. SequenceExpression,
  8833. SpreadElement,
  8834. Super,
  8835. SwitchCase,
  8836. SwitchStatement,
  8837. TaggedTemplateExpression,
  8838. TemplateElement,
  8839. TemplateLiteral,
  8840. ThisExpression,
  8841. ThrowStatement,
  8842. TryStatement,
  8843. UnaryExpression,
  8844. UnknownNode,
  8845. UpdateExpression,
  8846. VariableDeclaration,
  8847. VariableDeclarator,
  8848. WhileStatement,
  8849. YieldExpression
  8850. };
  8851. function getId(m) {
  8852. return m.id;
  8853. }
  8854. function getOriginalLocation(sourcemapChain, location) {
  8855. // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
  8856. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
  8857. while (filteredSourcemapChain.length > 0) {
  8858. const sourcemap = filteredSourcemapChain.pop();
  8859. const line = sourcemap.mappings[location.line - 1];
  8860. let locationFound = false;
  8861. if (line !== undefined) {
  8862. for (const segment of line) {
  8863. if (segment[0] >= location.column) {
  8864. if (segment.length === 1)
  8865. break;
  8866. location = {
  8867. column: segment[3],
  8868. line: segment[2] + 1,
  8869. name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
  8870. source: sourcemap.sources[segment[1]]
  8871. };
  8872. locationFound = true;
  8873. break;
  8874. }
  8875. }
  8876. }
  8877. if (!locationFound) {
  8878. throw new Error("Can't resolve original location of error.");
  8879. }
  8880. }
  8881. return location;
  8882. }
  8883. // AST walker module for Mozilla Parser API compatible trees
  8884. function skipThrough(node, st, c) { c(node, st); }
  8885. function ignore(_node, _st, _c) {}
  8886. // Node walkers.
  8887. var base = {};
  8888. base.Program = base.BlockStatement = function (node, st, c) {
  8889. for (var i = 0, list = node.body; i < list.length; i += 1)
  8890. {
  8891. var stmt = list[i];
  8892. c(stmt, st, "Statement");
  8893. }
  8894. };
  8895. base.Statement = skipThrough;
  8896. base.EmptyStatement = ignore;
  8897. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  8898. function (node, st, c) { return c(node.expression, st, "Expression"); };
  8899. base.IfStatement = function (node, st, c) {
  8900. c(node.test, st, "Expression");
  8901. c(node.consequent, st, "Statement");
  8902. if (node.alternate) { c(node.alternate, st, "Statement"); }
  8903. };
  8904. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  8905. base.BreakStatement = base.ContinueStatement = ignore;
  8906. base.WithStatement = function (node, st, c) {
  8907. c(node.object, st, "Expression");
  8908. c(node.body, st, "Statement");
  8909. };
  8910. base.SwitchStatement = function (node, st, c) {
  8911. c(node.discriminant, st, "Expression");
  8912. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  8913. var cs = list$1[i$1];
  8914. if (cs.test) { c(cs.test, st, "Expression"); }
  8915. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  8916. {
  8917. var cons = list[i];
  8918. c(cons, st, "Statement");
  8919. }
  8920. }
  8921. };
  8922. base.SwitchCase = function (node, st, c) {
  8923. if (node.test) { c(node.test, st, "Expression"); }
  8924. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  8925. {
  8926. var cons = list[i];
  8927. c(cons, st, "Statement");
  8928. }
  8929. };
  8930. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  8931. if (node.argument) { c(node.argument, st, "Expression"); }
  8932. };
  8933. base.ThrowStatement = base.SpreadElement =
  8934. function (node, st, c) { return c(node.argument, st, "Expression"); };
  8935. base.TryStatement = function (node, st, c) {
  8936. c(node.block, st, "Statement");
  8937. if (node.handler) { c(node.handler, st); }
  8938. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  8939. };
  8940. base.CatchClause = function (node, st, c) {
  8941. if (node.param) { c(node.param, st, "Pattern"); }
  8942. c(node.body, st, "Statement");
  8943. };
  8944. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  8945. c(node.test, st, "Expression");
  8946. c(node.body, st, "Statement");
  8947. };
  8948. base.ForStatement = function (node, st, c) {
  8949. if (node.init) { c(node.init, st, "ForInit"); }
  8950. if (node.test) { c(node.test, st, "Expression"); }
  8951. if (node.update) { c(node.update, st, "Expression"); }
  8952. c(node.body, st, "Statement");
  8953. };
  8954. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  8955. c(node.left, st, "ForInit");
  8956. c(node.right, st, "Expression");
  8957. c(node.body, st, "Statement");
  8958. };
  8959. base.ForInit = function (node, st, c) {
  8960. if (node.type === "VariableDeclaration") { c(node, st); }
  8961. else { c(node, st, "Expression"); }
  8962. };
  8963. base.DebuggerStatement = ignore;
  8964. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  8965. base.VariableDeclaration = function (node, st, c) {
  8966. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  8967. {
  8968. var decl = list[i];
  8969. c(decl, st);
  8970. }
  8971. };
  8972. base.VariableDeclarator = function (node, st, c) {
  8973. c(node.id, st, "Pattern");
  8974. if (node.init) { c(node.init, st, "Expression"); }
  8975. };
  8976. base.Function = function (node, st, c) {
  8977. if (node.id) { c(node.id, st, "Pattern"); }
  8978. for (var i = 0, list = node.params; i < list.length; i += 1)
  8979. {
  8980. var param = list[i];
  8981. c(param, st, "Pattern");
  8982. }
  8983. c(node.body, st, node.expression ? "Expression" : "Statement");
  8984. };
  8985. base.Pattern = function (node, st, c) {
  8986. if (node.type === "Identifier")
  8987. { c(node, st, "VariablePattern"); }
  8988. else if (node.type === "MemberExpression")
  8989. { c(node, st, "MemberPattern"); }
  8990. else
  8991. { c(node, st); }
  8992. };
  8993. base.VariablePattern = ignore;
  8994. base.MemberPattern = skipThrough;
  8995. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  8996. base.ArrayPattern = function (node, st, c) {
  8997. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  8998. var elt = list[i];
  8999. if (elt) { c(elt, st, "Pattern"); }
  9000. }
  9001. };
  9002. base.ObjectPattern = function (node, st, c) {
  9003. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  9004. var prop = list[i];
  9005. if (prop.type === "Property") {
  9006. if (prop.computed) { c(prop.key, st, "Expression"); }
  9007. c(prop.value, st, "Pattern");
  9008. } else if (prop.type === "RestElement") {
  9009. c(prop.argument, st, "Pattern");
  9010. }
  9011. }
  9012. };
  9013. base.Expression = skipThrough;
  9014. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  9015. base.ArrayExpression = function (node, st, c) {
  9016. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  9017. var elt = list[i];
  9018. if (elt) { c(elt, st, "Expression"); }
  9019. }
  9020. };
  9021. base.ObjectExpression = function (node, st, c) {
  9022. for (var i = 0, list = node.properties; i < list.length; i += 1)
  9023. {
  9024. var prop = list[i];
  9025. c(prop, st);
  9026. }
  9027. };
  9028. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  9029. base.SequenceExpression = function (node, st, c) {
  9030. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  9031. {
  9032. var expr = list[i];
  9033. c(expr, st, "Expression");
  9034. }
  9035. };
  9036. base.TemplateLiteral = function (node, st, c) {
  9037. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  9038. {
  9039. var quasi = list[i];
  9040. c(quasi, st);
  9041. }
  9042. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  9043. {
  9044. var expr = list$1[i$1];
  9045. c(expr, st, "Expression");
  9046. }
  9047. };
  9048. base.TemplateElement = ignore;
  9049. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  9050. c(node.argument, st, "Expression");
  9051. };
  9052. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  9053. c(node.left, st, "Expression");
  9054. c(node.right, st, "Expression");
  9055. };
  9056. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  9057. c(node.left, st, "Pattern");
  9058. c(node.right, st, "Expression");
  9059. };
  9060. base.ConditionalExpression = function (node, st, c) {
  9061. c(node.test, st, "Expression");
  9062. c(node.consequent, st, "Expression");
  9063. c(node.alternate, st, "Expression");
  9064. };
  9065. base.NewExpression = base.CallExpression = function (node, st, c) {
  9066. c(node.callee, st, "Expression");
  9067. if (node.arguments)
  9068. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  9069. {
  9070. var arg = list[i];
  9071. c(arg, st, "Expression");
  9072. } }
  9073. };
  9074. base.MemberExpression = function (node, st, c) {
  9075. c(node.object, st, "Expression");
  9076. if (node.computed) { c(node.property, st, "Expression"); }
  9077. };
  9078. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  9079. if (node.declaration)
  9080. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  9081. if (node.source) { c(node.source, st, "Expression"); }
  9082. };
  9083. base.ExportAllDeclaration = function (node, st, c) {
  9084. if (node.exported)
  9085. { c(node.exported, st); }
  9086. c(node.source, st, "Expression");
  9087. };
  9088. base.ImportDeclaration = function (node, st, c) {
  9089. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  9090. {
  9091. var spec = list[i];
  9092. c(spec, st);
  9093. }
  9094. c(node.source, st, "Expression");
  9095. };
  9096. base.ImportExpression = function (node, st, c) {
  9097. c(node.source, st, "Expression");
  9098. };
  9099. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
  9100. base.TaggedTemplateExpression = function (node, st, c) {
  9101. c(node.tag, st, "Expression");
  9102. c(node.quasi, st, "Expression");
  9103. };
  9104. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  9105. base.Class = function (node, st, c) {
  9106. if (node.id) { c(node.id, st, "Pattern"); }
  9107. if (node.superClass) { c(node.superClass, st, "Expression"); }
  9108. c(node.body, st);
  9109. };
  9110. base.ClassBody = function (node, st, c) {
  9111. for (var i = 0, list = node.body; i < list.length; i += 1)
  9112. {
  9113. var elt = list[i];
  9114. c(elt, st);
  9115. }
  9116. };
  9117. base.MethodDefinition = base.Property = function (node, st, c) {
  9118. if (node.computed) { c(node.key, st, "Expression"); }
  9119. c(node.value, st, "Expression");
  9120. };
  9121. // patch up acorn-walk until class-fields are officially supported
  9122. base.PropertyDefinition = function (node, st, c) {
  9123. if (node.computed) {
  9124. c(node.key, st, 'Expression');
  9125. }
  9126. if (node.value) {
  9127. c(node.value, st, 'Expression');
  9128. }
  9129. };
  9130. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  9131. let commentNode = state.commentNodes[state.commentIndex];
  9132. while (commentNode && node.start >= commentNode.end) {
  9133. markPureNode(node, commentNode);
  9134. commentNode = state.commentNodes[++state.commentIndex];
  9135. }
  9136. if (commentNode && commentNode.end <= node.end) {
  9137. base[type](node, state, handlePureAnnotationsOfNode);
  9138. }
  9139. }
  9140. function markPureNode(node, comment) {
  9141. if (node.annotations) {
  9142. node.annotations.push(comment);
  9143. }
  9144. else {
  9145. node.annotations = [comment];
  9146. }
  9147. if (node.type === ExpressionStatement$1) {
  9148. node = node.expression;
  9149. }
  9150. if (node.type === CallExpression$1 || node.type === NewExpression$1) {
  9151. node.annotatedPure = true;
  9152. }
  9153. }
  9154. const pureCommentRegex = /[@#]__PURE__/;
  9155. const isPureComment = (comment) => pureCommentRegex.test(comment.text);
  9156. function markPureCallExpressions(comments, esTreeAst) {
  9157. handlePureAnnotationsOfNode(esTreeAst, {
  9158. commentIndex: 0,
  9159. commentNodes: comments.filter(isPureComment)
  9160. });
  9161. }
  9162. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  9163. // this for an actual sourceMappingURL
  9164. let SOURCEMAPPING_URL = 'sourceMa';
  9165. SOURCEMAPPING_URL += 'ppingURL';
  9166. const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
  9167. const NOOP = () => { };
  9168. let getStartTime = () => [0, 0];
  9169. let getElapsedTime = () => 0;
  9170. let getMemory = () => 0;
  9171. let timers = {};
  9172. const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
  9173. function setTimeHelpers() {
  9174. if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
  9175. getStartTime = process.hrtime.bind(process);
  9176. getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
  9177. }
  9178. else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
  9179. getStartTime = () => [performance.now(), 0];
  9180. getElapsedTime = previous => performance.now() - previous[0];
  9181. }
  9182. if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
  9183. getMemory = () => process.memoryUsage().heapUsed;
  9184. }
  9185. }
  9186. function getPersistedLabel(label, level) {
  9187. switch (level) {
  9188. case 1:
  9189. return `# ${label}`;
  9190. case 2:
  9191. return `## ${label}`;
  9192. case 3:
  9193. return label;
  9194. default:
  9195. return `${' '.repeat(level - 4)}- ${label}`;
  9196. }
  9197. }
  9198. function timeStartImpl(label, level = 3) {
  9199. label = getPersistedLabel(label, level);
  9200. if (!timers.hasOwnProperty(label)) {
  9201. timers[label] = {
  9202. memory: 0,
  9203. startMemory: undefined,
  9204. startTime: undefined,
  9205. time: 0,
  9206. totalMemory: 0
  9207. };
  9208. }
  9209. const currentMemory = getMemory();
  9210. timers[label].startTime = getStartTime();
  9211. timers[label].startMemory = currentMemory;
  9212. }
  9213. function timeEndImpl(label, level = 3) {
  9214. label = getPersistedLabel(label, level);
  9215. if (timers.hasOwnProperty(label)) {
  9216. const currentMemory = getMemory();
  9217. timers[label].time += getElapsedTime(timers[label].startTime);
  9218. timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
  9219. timers[label].memory += currentMemory - timers[label].startMemory;
  9220. }
  9221. }
  9222. function getTimings() {
  9223. const newTimings = {};
  9224. for (const label of Object.keys(timers)) {
  9225. newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
  9226. }
  9227. return newTimings;
  9228. }
  9229. let timeStart = NOOP, timeEnd = NOOP;
  9230. const TIMED_PLUGIN_HOOKS = {
  9231. load: true,
  9232. resolveDynamicImport: true,
  9233. resolveId: true,
  9234. transform: true
  9235. };
  9236. function getPluginWithTimers(plugin, index) {
  9237. const timedPlugin = {};
  9238. for (const hook of Object.keys(plugin)) {
  9239. if (TIMED_PLUGIN_HOOKS[hook] === true) {
  9240. let timerLabel = `plugin ${index}`;
  9241. if (plugin.name) {
  9242. timerLabel += ` (${plugin.name})`;
  9243. }
  9244. timerLabel += ` - ${hook}`;
  9245. timedPlugin[hook] = function () {
  9246. timeStart(timerLabel, 4);
  9247. const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
  9248. timeEnd(timerLabel, 4);
  9249. if (result && typeof result.then === 'function') {
  9250. timeStart(`${timerLabel} (async)`, 4);
  9251. result.then(() => timeEnd(`${timerLabel} (async)`, 4));
  9252. }
  9253. return result;
  9254. };
  9255. }
  9256. else {
  9257. timedPlugin[hook] = plugin[hook];
  9258. }
  9259. }
  9260. return timedPlugin;
  9261. }
  9262. function initialiseTimers(inputOptions) {
  9263. if (inputOptions.perf) {
  9264. timers = {};
  9265. setTimeHelpers();
  9266. timeStart = timeStartImpl;
  9267. timeEnd = timeEndImpl;
  9268. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  9269. }
  9270. else {
  9271. timeStart = NOOP;
  9272. timeEnd = NOOP;
  9273. }
  9274. }
  9275. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  9276. baseModule.isExecuted = true;
  9277. const modules = [baseModule];
  9278. const visitedModules = new Set();
  9279. for (const module of modules) {
  9280. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  9281. if (!(dependency instanceof ExternalModule) &&
  9282. !dependency.isExecuted &&
  9283. (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  9284. !visitedModules.has(dependency.id)) {
  9285. dependency.isExecuted = true;
  9286. visitedModules.add(dependency.id);
  9287. modules.push(dependency);
  9288. }
  9289. }
  9290. }
  9291. }
  9292. function tryParse(module, Parser, acornOptions) {
  9293. try {
  9294. return Parser.parse(module.info.code, {
  9295. ...acornOptions,
  9296. onComment: (block, text, start, end) => module.comments.push({ block, text, start, end })
  9297. });
  9298. }
  9299. catch (err) {
  9300. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  9301. if (module.id.endsWith('.json')) {
  9302. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  9303. }
  9304. else if (!module.id.endsWith('.js')) {
  9305. message += ' (Note that you need plugins to import files that are not JavaScript)';
  9306. }
  9307. return module.error({
  9308. code: 'PARSE_ERROR',
  9309. message,
  9310. parserError: err
  9311. }, err.pos);
  9312. }
  9313. }
  9314. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  9315. identifier: null,
  9316. localName: MISSING_EXPORT_SHIM_VARIABLE
  9317. };
  9318. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  9319. const searchedModules = searchedNamesAndModules.get(name);
  9320. if (searchedModules) {
  9321. if (searchedModules.has(target)) {
  9322. return isExportAllSearch ? null : error(errCircularReexport(name, target.id));
  9323. }
  9324. searchedModules.add(target);
  9325. }
  9326. else {
  9327. searchedNamesAndModules.set(name, new Set([target]));
  9328. }
  9329. return target.getVariableForExportName(name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules);
  9330. }
  9331. function getAndExtendSideEffectModules(variable, module) {
  9332. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  9333. let currentVariable = variable;
  9334. const referencedVariables = new Set([currentVariable]);
  9335. while (true) {
  9336. const importingModule = currentVariable.module;
  9337. currentVariable =
  9338. currentVariable instanceof ExportDefaultVariable
  9339. ? currentVariable.getDirectOriginalVariable()
  9340. : currentVariable instanceof SyntheticNamedExportVariable
  9341. ? currentVariable.syntheticNamespace
  9342. : null;
  9343. if (!currentVariable || referencedVariables.has(currentVariable)) {
  9344. break;
  9345. }
  9346. referencedVariables.add(currentVariable);
  9347. sideEffectModules.add(importingModule);
  9348. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  9349. if (originalSideEffects) {
  9350. for (const module of originalSideEffects) {
  9351. sideEffectModules.add(module);
  9352. }
  9353. }
  9354. }
  9355. return sideEffectModules;
  9356. }
  9357. class Module {
  9358. constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
  9359. this.graph = graph;
  9360. this.id = id;
  9361. this.options = options;
  9362. this.alternativeReexportModules = new Map();
  9363. this.ast = null;
  9364. this.chunkFileNames = new Set();
  9365. this.chunkName = null;
  9366. this.comments = [];
  9367. this.cycles = new Set();
  9368. this.dependencies = new Set();
  9369. this.dynamicDependencies = new Set();
  9370. this.dynamicImporters = [];
  9371. this.dynamicImports = [];
  9372. this.execIndex = Infinity;
  9373. this.exportAllSources = new Set();
  9374. this.exports = Object.create(null);
  9375. this.exportsAll = Object.create(null);
  9376. this.implicitlyLoadedAfter = new Set();
  9377. this.implicitlyLoadedBefore = new Set();
  9378. this.importDescriptions = Object.create(null);
  9379. this.importers = [];
  9380. this.importMetas = [];
  9381. this.imports = new Set();
  9382. this.includedDynamicImporters = [];
  9383. this.isExecuted = false;
  9384. this.isUserDefinedEntryPoint = false;
  9385. this.preserveSignature = this.options.preserveEntrySignatures;
  9386. this.reexportDescriptions = Object.create(null);
  9387. this.sideEffectDependenciesByVariable = new Map();
  9388. this.sources = new Set();
  9389. this.userChunkNames = new Set();
  9390. this.usesTopLevelAwait = false;
  9391. this.allExportNames = null;
  9392. this.exportAllModules = [];
  9393. this.exportNamesByVariable = null;
  9394. this.exportShimVariable = new ExportShimVariable(this);
  9395. this.relevantDependencies = null;
  9396. this.syntheticExports = new Map();
  9397. this.syntheticNamespace = null;
  9398. this.transformDependencies = [];
  9399. this.transitiveReexports = null;
  9400. this.excludeFromSourcemap = /\0/.test(id);
  9401. this.context = options.moduleContext(id);
  9402. const module = this;
  9403. this.info = {
  9404. ast: null,
  9405. code: null,
  9406. get dynamicallyImportedIds() {
  9407. const dynamicallyImportedIds = [];
  9408. for (const { resolution } of module.dynamicImports) {
  9409. if (resolution instanceof Module || resolution instanceof ExternalModule) {
  9410. dynamicallyImportedIds.push(resolution.id);
  9411. }
  9412. }
  9413. return dynamicallyImportedIds;
  9414. },
  9415. get dynamicImporters() {
  9416. return module.dynamicImporters.sort();
  9417. },
  9418. hasModuleSideEffects,
  9419. id,
  9420. get implicitlyLoadedAfterOneOf() {
  9421. return Array.from(module.implicitlyLoadedAfter, getId);
  9422. },
  9423. get implicitlyLoadedBefore() {
  9424. return Array.from(module.implicitlyLoadedBefore, getId);
  9425. },
  9426. get importedIds() {
  9427. return Array.from(module.sources, source => module.resolvedIds[source].id);
  9428. },
  9429. get importers() {
  9430. return module.importers.sort();
  9431. },
  9432. isEntry,
  9433. isExternal: false,
  9434. meta,
  9435. syntheticNamedExports
  9436. };
  9437. }
  9438. basename() {
  9439. const base = basename(this.id);
  9440. const ext = extname(this.id);
  9441. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  9442. }
  9443. bindReferences() {
  9444. this.ast.bind();
  9445. }
  9446. error(props, pos) {
  9447. this.addLocationToLogProps(props, pos);
  9448. return error(props);
  9449. }
  9450. getAllExportNames() {
  9451. if (this.allExportNames) {
  9452. return this.allExportNames;
  9453. }
  9454. const allExportNames = (this.allExportNames = new Set());
  9455. for (const name of Object.keys(this.exports)) {
  9456. allExportNames.add(name);
  9457. }
  9458. for (const name of Object.keys(this.reexportDescriptions)) {
  9459. allExportNames.add(name);
  9460. }
  9461. for (const module of this.exportAllModules) {
  9462. if (module instanceof ExternalModule) {
  9463. allExportNames.add(`*${module.id}`);
  9464. continue;
  9465. }
  9466. for (const name of module.getAllExportNames()) {
  9467. if (name !== 'default')
  9468. allExportNames.add(name);
  9469. }
  9470. }
  9471. return allExportNames;
  9472. }
  9473. getDependenciesToBeIncluded() {
  9474. if (this.relevantDependencies)
  9475. return this.relevantDependencies;
  9476. const relevantDependencies = new Set();
  9477. const necessaryDependencies = new Set();
  9478. const alwaysCheckedDependencies = new Set();
  9479. let dependencyVariables = this.imports.keys();
  9480. if (this.info.isEntry ||
  9481. this.includedDynamicImporters.length > 0 ||
  9482. this.namespace.included ||
  9483. this.implicitlyLoadedAfter.size > 0) {
  9484. dependencyVariables = new Set(dependencyVariables);
  9485. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  9486. dependencyVariables.add(this.getVariableForExportName(exportName));
  9487. }
  9488. }
  9489. for (let variable of dependencyVariables) {
  9490. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  9491. if (sideEffectDependencies) {
  9492. for (const module of sideEffectDependencies) {
  9493. alwaysCheckedDependencies.add(module);
  9494. }
  9495. }
  9496. if (variable instanceof SyntheticNamedExportVariable) {
  9497. variable = variable.getBaseVariable();
  9498. }
  9499. else if (variable instanceof ExportDefaultVariable) {
  9500. variable = variable.getOriginalVariable();
  9501. }
  9502. necessaryDependencies.add(variable.module);
  9503. }
  9504. if (this.options.treeshake && this.info.hasModuleSideEffects !== 'no-treeshake') {
  9505. this.addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  9506. }
  9507. else {
  9508. for (const dependency of this.dependencies) {
  9509. relevantDependencies.add(dependency);
  9510. }
  9511. }
  9512. for (const dependency of necessaryDependencies) {
  9513. relevantDependencies.add(dependency);
  9514. }
  9515. return (this.relevantDependencies = relevantDependencies);
  9516. }
  9517. getExportNamesByVariable() {
  9518. if (this.exportNamesByVariable) {
  9519. return this.exportNamesByVariable;
  9520. }
  9521. const exportNamesByVariable = new Map();
  9522. for (const exportName of this.getAllExportNames()) {
  9523. if (exportName === this.info.syntheticNamedExports)
  9524. continue;
  9525. let tracedVariable = this.getVariableForExportName(exportName);
  9526. if (tracedVariable instanceof ExportDefaultVariable) {
  9527. tracedVariable = tracedVariable.getOriginalVariable();
  9528. }
  9529. if (!tracedVariable ||
  9530. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  9531. continue;
  9532. }
  9533. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  9534. if (existingExportNames) {
  9535. existingExportNames.push(exportName);
  9536. }
  9537. else {
  9538. exportNamesByVariable.set(tracedVariable, [exportName]);
  9539. }
  9540. }
  9541. return (this.exportNamesByVariable = exportNamesByVariable);
  9542. }
  9543. getExports() {
  9544. return Object.keys(this.exports);
  9545. }
  9546. getReexports() {
  9547. if (this.transitiveReexports) {
  9548. return this.transitiveReexports;
  9549. }
  9550. // to avoid infinite recursion when using circular `export * from X`
  9551. this.transitiveReexports = [];
  9552. const reexports = new Set();
  9553. for (const name in this.reexportDescriptions) {
  9554. reexports.add(name);
  9555. }
  9556. for (const module of this.exportAllModules) {
  9557. if (module instanceof ExternalModule) {
  9558. reexports.add(`*${module.id}`);
  9559. }
  9560. else {
  9561. for (const name of [...module.getReexports(), ...module.getExports()]) {
  9562. if (name !== 'default')
  9563. reexports.add(name);
  9564. }
  9565. }
  9566. }
  9567. return (this.transitiveReexports = [...reexports]);
  9568. }
  9569. getRenderedExports() {
  9570. // only direct exports are counted here, not reexports at all
  9571. const renderedExports = [];
  9572. const removedExports = [];
  9573. for (const exportName in this.exports) {
  9574. const variable = this.getVariableForExportName(exportName);
  9575. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  9576. }
  9577. return { renderedExports, removedExports };
  9578. }
  9579. getSyntheticNamespace() {
  9580. if (this.syntheticNamespace === null) {
  9581. this.syntheticNamespace = undefined;
  9582. this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  9583. ? this.info.syntheticNamedExports
  9584. : 'default');
  9585. }
  9586. if (!this.syntheticNamespace) {
  9587. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  9588. }
  9589. return this.syntheticNamespace;
  9590. }
  9591. getVariableForExportName(name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules) {
  9592. if (name[0] === '*') {
  9593. if (name.length === 1) {
  9594. // export * from './other'
  9595. return this.namespace;
  9596. }
  9597. else {
  9598. // export * from 'external'
  9599. const module = this.graph.modulesById.get(name.slice(1));
  9600. return module.getVariableForExportName('*');
  9601. }
  9602. }
  9603. // export { foo } from './other'
  9604. const reexportDeclaration = this.reexportDescriptions[name];
  9605. if (reexportDeclaration) {
  9606. const variable = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  9607. if (!variable) {
  9608. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  9609. }
  9610. if (importerForSideEffects) {
  9611. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9612. }
  9613. return variable;
  9614. }
  9615. const exportDeclaration = this.exports[name];
  9616. if (exportDeclaration) {
  9617. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  9618. return this.exportShimVariable;
  9619. }
  9620. const name = exportDeclaration.localName;
  9621. const variable = this.traceVariable(name, importerForSideEffects);
  9622. if (importerForSideEffects) {
  9623. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  9624. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9625. }
  9626. return variable;
  9627. }
  9628. if (name !== 'default') {
  9629. let foundSyntheticDeclaration = null;
  9630. for (const module of this.exportAllModules) {
  9631. const declaration = getVariableForExportNameRecursive(module, name, importerForSideEffects, true, searchedNamesAndModules);
  9632. if (declaration) {
  9633. if (!(declaration instanceof SyntheticNamedExportVariable)) {
  9634. return declaration;
  9635. }
  9636. if (!foundSyntheticDeclaration) {
  9637. foundSyntheticDeclaration = declaration;
  9638. }
  9639. }
  9640. }
  9641. if (foundSyntheticDeclaration) {
  9642. return foundSyntheticDeclaration;
  9643. }
  9644. }
  9645. if (this.info.syntheticNamedExports) {
  9646. let syntheticExport = this.syntheticExports.get(name);
  9647. if (!syntheticExport) {
  9648. const syntheticNamespace = this.getSyntheticNamespace();
  9649. syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
  9650. this.syntheticExports.set(name, syntheticExport);
  9651. return syntheticExport;
  9652. }
  9653. return syntheticExport;
  9654. }
  9655. // we don't want to create shims when we are just
  9656. // probing export * modules for exports
  9657. if (!isExportAllSearch) {
  9658. if (this.options.shimMissingExports) {
  9659. this.shimMissingExport(name);
  9660. return this.exportShimVariable;
  9661. }
  9662. }
  9663. return null;
  9664. }
  9665. hasEffects() {
  9666. return (this.info.hasModuleSideEffects === 'no-treeshake' ||
  9667. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  9668. }
  9669. include() {
  9670. const context = createInclusionContext();
  9671. if (this.ast.shouldBeIncluded(context))
  9672. this.ast.include(context, false);
  9673. }
  9674. includeAllExports(includeNamespaceMembers) {
  9675. if (!this.isExecuted) {
  9676. this.graph.needsTreeshakingPass = true;
  9677. markModuleAndImpureDependenciesAsExecuted(this);
  9678. }
  9679. for (const exportName of this.getExports()) {
  9680. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  9681. const variable = this.getVariableForExportName(exportName);
  9682. variable.deoptimizePath(UNKNOWN_PATH);
  9683. if (!variable.included) {
  9684. this.includeVariable(variable);
  9685. }
  9686. }
  9687. }
  9688. for (const name of this.getReexports()) {
  9689. const variable = this.getVariableForExportName(name);
  9690. variable.deoptimizePath(UNKNOWN_PATH);
  9691. if (!variable.included) {
  9692. this.includeVariable(variable);
  9693. }
  9694. if (variable instanceof ExternalVariable) {
  9695. variable.module.reexported = true;
  9696. }
  9697. }
  9698. if (includeNamespaceMembers) {
  9699. this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
  9700. }
  9701. }
  9702. includeAllInBundle() {
  9703. this.ast.include(createInclusionContext(), true);
  9704. }
  9705. isIncluded() {
  9706. return this.ast.included || this.namespace.included;
  9707. }
  9708. linkImports() {
  9709. this.addModulesToImportDescriptions(this.importDescriptions);
  9710. this.addModulesToImportDescriptions(this.reexportDescriptions);
  9711. for (const name in this.exports) {
  9712. if (name !== 'default' && name !== this.info.syntheticNamedExports) {
  9713. this.exportsAll[name] = this.id;
  9714. }
  9715. }
  9716. const externalExportAllModules = [];
  9717. for (const source of this.exportAllSources) {
  9718. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  9719. if (module instanceof ExternalModule) {
  9720. externalExportAllModules.push(module);
  9721. continue;
  9722. }
  9723. this.exportAllModules.push(module);
  9724. for (const name in module.exportsAll) {
  9725. if (name in this.exportsAll) {
  9726. this.options.onwarn(errNamespaceConflict(name, this, module));
  9727. }
  9728. else {
  9729. this.exportsAll[name] = module.exportsAll[name];
  9730. }
  9731. }
  9732. }
  9733. this.exportAllModules.push(...externalExportAllModules);
  9734. }
  9735. render(options) {
  9736. const magicString = this.magicString.clone();
  9737. this.ast.render(magicString, options);
  9738. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  9739. return magicString;
  9740. }
  9741. setSource({ alwaysRemovedCode, ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  9742. this.info.code = code;
  9743. this.originalCode = originalCode;
  9744. this.originalSourcemap = originalSourcemap;
  9745. this.sourcemapChain = sourcemapChain;
  9746. if (transformFiles) {
  9747. this.transformFiles = transformFiles;
  9748. }
  9749. this.transformDependencies = transformDependencies;
  9750. this.customTransformCache = customTransformCache;
  9751. this.updateOptions(moduleOptions);
  9752. timeStart('generate ast', 3);
  9753. this.alwaysRemovedCode = alwaysRemovedCode || [];
  9754. if (!ast) {
  9755. ast = tryParse(this, this.graph.acornParser, this.options.acorn);
  9756. for (const comment of this.comments) {
  9757. if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
  9758. this.alwaysRemovedCode.push([comment.start, comment.end]);
  9759. }
  9760. }
  9761. markPureCallExpressions(this.comments, ast);
  9762. }
  9763. timeEnd('generate ast', 3);
  9764. this.resolvedIds = resolvedIds || Object.create(null);
  9765. // By default, `id` is the file name. Custom resolvers and loaders
  9766. // can change that, but it makes sense to use it for the source file name
  9767. const fileName = this.id;
  9768. this.magicString = new MagicString(code, {
  9769. filename: (this.excludeFromSourcemap ? null : fileName),
  9770. indentExclusionRanges: []
  9771. });
  9772. for (const [start, end] of this.alwaysRemovedCode) {
  9773. this.magicString.remove(start, end);
  9774. }
  9775. timeStart('analyse ast', 3);
  9776. this.astContext = {
  9777. addDynamicImport: this.addDynamicImport.bind(this),
  9778. addExport: this.addExport.bind(this),
  9779. addImport: this.addImport.bind(this),
  9780. addImportMeta: this.addImportMeta.bind(this),
  9781. code,
  9782. deoptimizationTracker: this.graph.deoptimizationTracker,
  9783. error: this.error.bind(this),
  9784. fileName,
  9785. getExports: this.getExports.bind(this),
  9786. getModuleExecIndex: () => this.execIndex,
  9787. getModuleName: this.basename.bind(this),
  9788. getReexports: this.getReexports.bind(this),
  9789. importDescriptions: this.importDescriptions,
  9790. includeAllExports: () => this.includeAllExports(true),
  9791. includeDynamicImport: this.includeDynamicImport.bind(this),
  9792. includeVariableInModule: this.includeVariableInModule.bind(this),
  9793. magicString: this.magicString,
  9794. module: this,
  9795. moduleContext: this.context,
  9796. nodeConstructors,
  9797. options: this.options,
  9798. traceExport: this.getVariableForExportName.bind(this),
  9799. traceVariable: this.traceVariable.bind(this),
  9800. usesTopLevelAwait: false,
  9801. warn: this.warn.bind(this)
  9802. };
  9803. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  9804. this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
  9805. this.ast = new Program(ast, { type: 'Module', context: this.astContext }, this.scope);
  9806. this.info.ast = ast;
  9807. timeEnd('analyse ast', 3);
  9808. }
  9809. toJSON() {
  9810. return {
  9811. alwaysRemovedCode: this.alwaysRemovedCode,
  9812. ast: this.ast.esTreeNode,
  9813. code: this.info.code,
  9814. customTransformCache: this.customTransformCache,
  9815. dependencies: Array.from(this.dependencies, getId),
  9816. id: this.id,
  9817. meta: this.info.meta,
  9818. moduleSideEffects: this.info.hasModuleSideEffects,
  9819. originalCode: this.originalCode,
  9820. originalSourcemap: this.originalSourcemap,
  9821. resolvedIds: this.resolvedIds,
  9822. sourcemapChain: this.sourcemapChain,
  9823. syntheticNamedExports: this.info.syntheticNamedExports,
  9824. transformDependencies: this.transformDependencies,
  9825. transformFiles: this.transformFiles
  9826. };
  9827. }
  9828. traceVariable(name, importerForSideEffects) {
  9829. const localVariable = this.scope.variables.get(name);
  9830. if (localVariable) {
  9831. return localVariable;
  9832. }
  9833. if (name in this.importDescriptions) {
  9834. const importDeclaration = this.importDescriptions[name];
  9835. const otherModule = importDeclaration.module;
  9836. if (otherModule instanceof Module && importDeclaration.name === '*') {
  9837. return otherModule.namespace;
  9838. }
  9839. const declaration = otherModule.getVariableForExportName(importDeclaration.name, importerForSideEffects || this);
  9840. if (!declaration) {
  9841. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  9842. }
  9843. return declaration;
  9844. }
  9845. return null;
  9846. }
  9847. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  9848. if (moduleSideEffects != null) {
  9849. this.info.hasModuleSideEffects = moduleSideEffects;
  9850. }
  9851. if (syntheticNamedExports != null) {
  9852. this.info.syntheticNamedExports = syntheticNamedExports;
  9853. }
  9854. if (meta != null) {
  9855. this.info.meta = { ...this.info.meta, ...meta };
  9856. }
  9857. }
  9858. warn(props, pos) {
  9859. this.addLocationToLogProps(props, pos);
  9860. this.options.onwarn(props);
  9861. }
  9862. addDynamicImport(node) {
  9863. let argument = node.source;
  9864. if (argument instanceof TemplateLiteral) {
  9865. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  9866. argument = argument.quasis[0].value.cooked;
  9867. }
  9868. }
  9869. else if (argument instanceof Literal && typeof argument.value === 'string') {
  9870. argument = argument.value;
  9871. }
  9872. this.dynamicImports.push({ node, resolution: null, argument });
  9873. }
  9874. addExport(node) {
  9875. if (node instanceof ExportDefaultDeclaration) {
  9876. // export default foo;
  9877. this.exports.default = {
  9878. identifier: node.variable.getAssignedVariableName(),
  9879. localName: 'default'
  9880. };
  9881. }
  9882. else if (node instanceof ExportAllDeclaration) {
  9883. const source = node.source.value;
  9884. this.sources.add(source);
  9885. if (node.exported) {
  9886. // export * as name from './other'
  9887. const name = node.exported.name;
  9888. this.reexportDescriptions[name] = {
  9889. localName: '*',
  9890. module: null,
  9891. source,
  9892. start: node.start
  9893. };
  9894. }
  9895. else {
  9896. // export * from './other'
  9897. this.exportAllSources.add(source);
  9898. }
  9899. }
  9900. else if (node.source instanceof Literal) {
  9901. // export { name } from './other'
  9902. const source = node.source.value;
  9903. this.sources.add(source);
  9904. for (const specifier of node.specifiers) {
  9905. const name = specifier.exported.name;
  9906. this.reexportDescriptions[name] = {
  9907. localName: specifier.local.name,
  9908. module: null,
  9909. source,
  9910. start: specifier.start
  9911. };
  9912. }
  9913. }
  9914. else if (node.declaration) {
  9915. const declaration = node.declaration;
  9916. if (declaration instanceof VariableDeclaration) {
  9917. // export var { foo, bar } = ...
  9918. // export var foo = 1, bar = 2;
  9919. for (const declarator of declaration.declarations) {
  9920. for (const localName of extractAssignedNames(declarator.id)) {
  9921. this.exports[localName] = { identifier: null, localName };
  9922. }
  9923. }
  9924. }
  9925. else {
  9926. // export function foo () {}
  9927. const localName = declaration.id.name;
  9928. this.exports[localName] = { identifier: null, localName };
  9929. }
  9930. }
  9931. else {
  9932. // export { foo, bar, baz }
  9933. for (const specifier of node.specifiers) {
  9934. const localName = specifier.local.name;
  9935. const exportedName = specifier.exported.name;
  9936. this.exports[exportedName] = { identifier: null, localName };
  9937. }
  9938. }
  9939. }
  9940. addImport(node) {
  9941. const source = node.source.value;
  9942. this.sources.add(source);
  9943. for (const specifier of node.specifiers) {
  9944. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  9945. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  9946. const name = isDefault
  9947. ? 'default'
  9948. : isNamespace
  9949. ? '*'
  9950. : specifier.imported.name;
  9951. this.importDescriptions[specifier.local.name] = {
  9952. module: null,
  9953. name,
  9954. source,
  9955. start: specifier.start
  9956. };
  9957. }
  9958. }
  9959. addImportMeta(node) {
  9960. this.importMetas.push(node);
  9961. }
  9962. addLocationToLogProps(props, pos) {
  9963. props.id = this.id;
  9964. props.pos = pos;
  9965. let code = this.info.code;
  9966. let { column, line } = locate(code, pos, { offsetLine: 1 });
  9967. try {
  9968. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  9969. code = this.originalCode;
  9970. }
  9971. catch (e) {
  9972. this.options.onwarn({
  9973. code: 'SOURCEMAP_ERROR',
  9974. id: this.id,
  9975. loc: {
  9976. column,
  9977. file: this.id,
  9978. line
  9979. },
  9980. message: `Error when using sourcemap for reporting an error: ${e.message}`,
  9981. pos
  9982. });
  9983. }
  9984. augmentCodeLocation(props, { column, line }, code, this.id);
  9985. }
  9986. addModulesToImportDescriptions(importDescription) {
  9987. for (const name of Object.keys(importDescription)) {
  9988. const specifier = importDescription[name];
  9989. const id = this.resolvedIds[specifier.source].id;
  9990. specifier.module = this.graph.modulesById.get(id);
  9991. }
  9992. }
  9993. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  9994. const handledDependencies = new Set();
  9995. const addSideEffectDependencies = (possibleDependencies) => {
  9996. for (const dependency of possibleDependencies) {
  9997. if (handledDependencies.has(dependency)) {
  9998. continue;
  9999. }
  10000. handledDependencies.add(dependency);
  10001. if (necessaryDependencies.has(dependency)) {
  10002. relevantDependencies.add(dependency);
  10003. continue;
  10004. }
  10005. if (!(dependency.info.hasModuleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  10006. continue;
  10007. }
  10008. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  10009. relevantDependencies.add(dependency);
  10010. continue;
  10011. }
  10012. addSideEffectDependencies(dependency.dependencies);
  10013. }
  10014. };
  10015. addSideEffectDependencies(this.dependencies);
  10016. addSideEffectDependencies(alwaysCheckedDependencies);
  10017. }
  10018. includeAndGetAdditionalMergedNamespaces() {
  10019. const mergedNamespaces = [];
  10020. for (const module of this.exportAllModules) {
  10021. if (module instanceof ExternalModule) {
  10022. const externalVariable = module.getVariableForExportName('*');
  10023. externalVariable.include();
  10024. this.imports.add(externalVariable);
  10025. mergedNamespaces.push(externalVariable);
  10026. }
  10027. else if (module.info.syntheticNamedExports) {
  10028. const syntheticNamespace = module.getSyntheticNamespace();
  10029. syntheticNamespace.include();
  10030. this.imports.add(syntheticNamespace);
  10031. mergedNamespaces.push(syntheticNamespace);
  10032. }
  10033. }
  10034. return mergedNamespaces;
  10035. }
  10036. includeDynamicImport(node) {
  10037. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  10038. if (resolution instanceof Module) {
  10039. resolution.includedDynamicImporters.push(this);
  10040. resolution.includeAllExports(true);
  10041. }
  10042. }
  10043. includeVariable(variable) {
  10044. if (!variable.included) {
  10045. variable.include();
  10046. this.graph.needsTreeshakingPass = true;
  10047. const variableModule = variable.module;
  10048. if (variableModule && variableModule instanceof Module) {
  10049. if (!variableModule.isExecuted) {
  10050. markModuleAndImpureDependenciesAsExecuted(variableModule);
  10051. }
  10052. if (variableModule !== this) {
  10053. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  10054. for (const module of sideEffectModules) {
  10055. if (!module.isExecuted) {
  10056. markModuleAndImpureDependenciesAsExecuted(module);
  10057. }
  10058. }
  10059. }
  10060. }
  10061. }
  10062. }
  10063. includeVariableInModule(variable) {
  10064. this.includeVariable(variable);
  10065. const variableModule = variable.module;
  10066. if (variableModule && variableModule !== this) {
  10067. this.imports.add(variable);
  10068. }
  10069. }
  10070. shimMissingExport(name) {
  10071. this.options.onwarn({
  10072. code: 'SHIMMED_EXPORT',
  10073. exporter: relativeId(this.id),
  10074. exportName: name,
  10075. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  10076. });
  10077. this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
  10078. }
  10079. }
  10080. // if there is a cyclic import in the reexport chain, we should not
  10081. // import from the original module but from the cyclic module to not
  10082. // mess up execution order.
  10083. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  10084. if (variable.module instanceof Module && variable.module !== reexporter) {
  10085. const exporterCycles = variable.module.cycles;
  10086. if (exporterCycles.size > 0) {
  10087. const importerCycles = reexporter.cycles;
  10088. for (const cycleSymbol of importerCycles) {
  10089. if (exporterCycles.has(cycleSymbol)) {
  10090. importer.alternativeReexportModules.set(variable, reexporter);
  10091. break;
  10092. }
  10093. }
  10094. }
  10095. }
  10096. }
  10097. class Source {
  10098. constructor(filename, content) {
  10099. this.isOriginal = true;
  10100. this.filename = filename;
  10101. this.content = content;
  10102. }
  10103. traceSegment(line, column, name) {
  10104. return { line, column, name, source: this };
  10105. }
  10106. }
  10107. class Link {
  10108. constructor(map, sources) {
  10109. this.sources = sources;
  10110. this.names = map.names;
  10111. this.mappings = map.mappings;
  10112. }
  10113. traceMappings() {
  10114. const sources = [];
  10115. const sourcesContent = [];
  10116. const names = [];
  10117. const mappings = [];
  10118. for (const line of this.mappings) {
  10119. const tracedLine = [];
  10120. for (const segment of line) {
  10121. if (segment.length == 1)
  10122. continue;
  10123. const source = this.sources[segment[1]];
  10124. if (!source)
  10125. continue;
  10126. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  10127. if (traced) {
  10128. // newer sources are more likely to be used, so search backwards.
  10129. let sourceIndex = sources.lastIndexOf(traced.source.filename);
  10130. if (sourceIndex === -1) {
  10131. sourceIndex = sources.length;
  10132. sources.push(traced.source.filename);
  10133. sourcesContent[sourceIndex] = traced.source.content;
  10134. }
  10135. else if (sourcesContent[sourceIndex] == null) {
  10136. sourcesContent[sourceIndex] = traced.source.content;
  10137. }
  10138. else if (traced.source.content != null &&
  10139. sourcesContent[sourceIndex] !== traced.source.content) {
  10140. return error({
  10141. message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
  10142. });
  10143. }
  10144. const tracedSegment = [
  10145. segment[0],
  10146. sourceIndex,
  10147. traced.line,
  10148. traced.column
  10149. ];
  10150. if (traced.name) {
  10151. let nameIndex = names.indexOf(traced.name);
  10152. if (nameIndex === -1) {
  10153. nameIndex = names.length;
  10154. names.push(traced.name);
  10155. }
  10156. tracedSegment[4] = nameIndex;
  10157. }
  10158. tracedLine.push(tracedSegment);
  10159. }
  10160. }
  10161. mappings.push(tracedLine);
  10162. }
  10163. return { sources, sourcesContent, names, mappings };
  10164. }
  10165. traceSegment(line, column, name) {
  10166. const segments = this.mappings[line];
  10167. if (!segments)
  10168. return null;
  10169. // binary search through segments for the given column
  10170. let i = 0;
  10171. let j = segments.length - 1;
  10172. while (i <= j) {
  10173. const m = (i + j) >> 1;
  10174. const segment = segments[m];
  10175. if (segment[0] === column) {
  10176. if (segment.length == 1)
  10177. return null;
  10178. const source = this.sources[segment[1]];
  10179. if (!source)
  10180. return null;
  10181. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  10182. }
  10183. if (segment[0] > column) {
  10184. j = m - 1;
  10185. }
  10186. else {
  10187. i = m + 1;
  10188. }
  10189. }
  10190. return null;
  10191. }
  10192. }
  10193. function getLinkMap(warn) {
  10194. return function linkMap(source, map) {
  10195. if (map.mappings) {
  10196. return new Link(map, [source]);
  10197. }
  10198. warn({
  10199. code: 'SOURCEMAP_BROKEN',
  10200. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  10201. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  10202. 'documentation for help',
  10203. plugin: map.plugin,
  10204. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  10205. });
  10206. return new Link({
  10207. mappings: [],
  10208. names: []
  10209. }, [source]);
  10210. };
  10211. }
  10212. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  10213. let source;
  10214. if (!originalSourcemap) {
  10215. source = new Source(id, originalCode);
  10216. }
  10217. else {
  10218. const sources = originalSourcemap.sources;
  10219. const sourcesContent = originalSourcemap.sourcesContent || [];
  10220. const directory = dirname(id) || '.';
  10221. const sourceRoot = originalSourcemap.sourceRoot || '.';
  10222. const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
  10223. source = new Link(originalSourcemap, baseSources);
  10224. }
  10225. return sourcemapChain.reduce(linkMap, source);
  10226. }
  10227. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  10228. const linkMap = getLinkMap(warn);
  10229. const moduleSources = modules
  10230. .filter(module => !module.excludeFromSourcemap)
  10231. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  10232. // DecodedSourceMap (from magic-string) uses a number[] instead of the more
  10233. // correct SourceMapSegment tuples. Cast it here to gain type safety.
  10234. let source = new Link(map, moduleSources);
  10235. source = bundleSourcemapChain.reduce(linkMap, source);
  10236. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  10237. if (file) {
  10238. const directory = dirname(file);
  10239. sources = sources.map((source) => relative$1(directory, source));
  10240. file = basename(file);
  10241. }
  10242. sourcesContent = (excludeContent ? null : sourcesContent);
  10243. return new SourceMap({ file, sources, sourcesContent, names, mappings });
  10244. }
  10245. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  10246. if (!sourcemapChain.length) {
  10247. return originalSourcemap;
  10248. }
  10249. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  10250. const map = source.traceMappings();
  10251. return { version: 3, ...map };
  10252. }
  10253. const createHash = () => createHash$1('sha256');
  10254. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  10255. amd: deconflictImportsOther,
  10256. cjs: deconflictImportsOther,
  10257. es: deconflictImportsEsmOrSystem,
  10258. iife: deconflictImportsOther,
  10259. system: deconflictImportsEsmOrSystem,
  10260. umd: deconflictImportsOther
  10261. };
  10262. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  10263. const reversedModules = modules.slice().reverse();
  10264. for (const module of reversedModules) {
  10265. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  10266. }
  10267. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  10268. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  10269. for (const module of reversedModules) {
  10270. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10271. }
  10272. }
  10273. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  10274. // This is needed for namespace reexports
  10275. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  10276. if (preserveModules || dependency instanceof ExternalModule) {
  10277. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  10278. }
  10279. }
  10280. for (const variable of imports) {
  10281. const module = variable.module;
  10282. const name = variable.name;
  10283. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  10284. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  10285. }
  10286. else if (module instanceof ExternalModule && name === 'default') {
  10287. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  10288. ? module.suggestedVariableName + '__default'
  10289. : module.suggestedVariableName, usedNames));
  10290. }
  10291. else {
  10292. variable.setRenderNames(null, getSafeName(name, usedNames));
  10293. }
  10294. }
  10295. for (const variable of syntheticExports) {
  10296. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10297. }
  10298. }
  10299. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  10300. for (const chunkOrExternalModule of dependencies) {
  10301. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  10302. }
  10303. for (const externalModuleOrChunk of deconflictedNamespace) {
  10304. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  10305. }
  10306. for (const externalModule of deconflictedDefault) {
  10307. if (deconflictedNamespace.has(externalModule) &&
  10308. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  10309. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  10310. }
  10311. else {
  10312. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  10313. }
  10314. }
  10315. for (const variable of imports) {
  10316. const module = variable.module;
  10317. if (module instanceof ExternalModule) {
  10318. const name = variable.name;
  10319. if (name === 'default') {
  10320. const moduleInterop = String(interop(module.id));
  10321. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  10322. ? module.defaultVariableName
  10323. : module.variableName;
  10324. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  10325. variable.setRenderNames(variableName, 'default');
  10326. }
  10327. else {
  10328. variable.setRenderNames(null, variableName);
  10329. }
  10330. }
  10331. else if (name === '*') {
  10332. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  10333. ? module.namespaceVariableName
  10334. : module.variableName);
  10335. }
  10336. else {
  10337. // if the second parameter is `null`, it uses its "name" for the property name
  10338. variable.setRenderNames(module.variableName, null);
  10339. }
  10340. }
  10341. else {
  10342. const chunk = chunkByModule.get(module);
  10343. if (preserveModules && variable.isNamespace) {
  10344. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  10345. }
  10346. else if (chunk.exportMode === 'default') {
  10347. variable.setRenderNames(null, chunk.variableName);
  10348. }
  10349. else {
  10350. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  10351. }
  10352. }
  10353. }
  10354. }
  10355. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  10356. for (const module of modules) {
  10357. for (const variable of module.scope.variables.values()) {
  10358. if (variable.included &&
  10359. // this will only happen for exports in some formats
  10360. !(variable.renderBaseName ||
  10361. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  10362. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10363. }
  10364. }
  10365. if (includedNamespaces.has(module)) {
  10366. const namespace = module.namespace;
  10367. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  10368. }
  10369. }
  10370. }
  10371. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  10372. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  10373. const backSlashRegEx = /\\/g;
  10374. function escapeId(id) {
  10375. if (!id.match(needsEscapeRegEx))
  10376. return id;
  10377. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  10378. }
  10379. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  10380. let nameIndex = 0;
  10381. for (const variable of exports) {
  10382. let exportName = variable.name[0];
  10383. if (exportsByName[exportName]) {
  10384. do {
  10385. exportName = toBase64(++nameIndex);
  10386. // skip past leading number identifiers
  10387. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  10388. nameIndex += 9 * 64 ** (exportName.length - 1);
  10389. exportName = toBase64(nameIndex);
  10390. }
  10391. } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
  10392. }
  10393. exportsByName[exportName] = variable;
  10394. exportNamesByVariable.set(variable, [exportName]);
  10395. }
  10396. }
  10397. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  10398. for (const variable of exports) {
  10399. let nameIndex = 0;
  10400. let exportName = variable.name;
  10401. while (exportsByName[exportName]) {
  10402. exportName = variable.name + '$' + ++nameIndex;
  10403. }
  10404. exportsByName[exportName] = variable;
  10405. exportNamesByVariable.set(variable, [exportName]);
  10406. }
  10407. }
  10408. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  10409. const exportKeys = chunk.getExportNames();
  10410. if (exportMode === 'default') {
  10411. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  10412. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  10413. }
  10414. }
  10415. else if (exportMode === 'none' && exportKeys.length) {
  10416. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  10417. }
  10418. if (exportMode === 'auto') {
  10419. if (exportKeys.length === 0) {
  10420. exportMode = 'none';
  10421. }
  10422. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  10423. if (format === 'cjs' && unsetOptions.has('exports')) {
  10424. warn(errPreferNamedExports(facadeModuleId));
  10425. }
  10426. exportMode = 'default';
  10427. }
  10428. else {
  10429. if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
  10430. warn(errMixedExport(facadeModuleId, name));
  10431. }
  10432. exportMode = 'named';
  10433. }
  10434. }
  10435. return exportMode;
  10436. }
  10437. function guessIndentString(code) {
  10438. const lines = code.split('\n');
  10439. const tabbed = lines.filter(line => /^\t+/.test(line));
  10440. const spaced = lines.filter(line => /^ {2,}/.test(line));
  10441. if (tabbed.length === 0 && spaced.length === 0) {
  10442. return null;
  10443. }
  10444. // More lines tabbed than spaced? Assume tabs, and
  10445. // default to tabs in the case of a tie (or nothing
  10446. // to go on)
  10447. if (tabbed.length >= spaced.length) {
  10448. return '\t';
  10449. }
  10450. // Otherwise, we need to guess the multiple
  10451. const min = spaced.reduce((previous, current) => {
  10452. const numSpaces = /^ +/.exec(current)[0].length;
  10453. return Math.min(numSpaces, previous);
  10454. }, Infinity);
  10455. return new Array(min + 1).join(' ');
  10456. }
  10457. function getIndentString(modules, options) {
  10458. if (options.indent !== true)
  10459. return options.indent;
  10460. for (let i = 0; i < modules.length; i++) {
  10461. const indent = guessIndentString(modules[i].originalCode);
  10462. if (indent !== null)
  10463. return indent;
  10464. }
  10465. return '\t';
  10466. }
  10467. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  10468. const staticDependencyBlocks = [];
  10469. const handledDependencies = new Set();
  10470. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  10471. const module = orderedModules[modulePos];
  10472. if (!handledDependencies.has(module)) {
  10473. const staticDependencies = [];
  10474. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  10475. staticDependencyBlocks.unshift(staticDependencies);
  10476. }
  10477. }
  10478. const dependencies = new Set();
  10479. for (const block of staticDependencyBlocks) {
  10480. for (const dependency of block) {
  10481. dependencies.add(dependency);
  10482. }
  10483. }
  10484. return dependencies;
  10485. }
  10486. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  10487. const dependencies = module.getDependenciesToBeIncluded();
  10488. for (const dependency of dependencies) {
  10489. if (dependency instanceof ExternalModule) {
  10490. staticDependencies.push(dependency);
  10491. continue;
  10492. }
  10493. const dependencyChunk = chunkByModule.get(dependency);
  10494. if (dependencyChunk !== chunk) {
  10495. staticDependencies.push(dependencyChunk);
  10496. continue;
  10497. }
  10498. if (!handledModules.has(dependency)) {
  10499. handledModules.add(dependency);
  10500. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  10501. }
  10502. }
  10503. }
  10504. function decodedSourcemap(map) {
  10505. if (!map)
  10506. return null;
  10507. if (typeof map === 'string') {
  10508. map = JSON.parse(map);
  10509. }
  10510. if (map.mappings === '') {
  10511. return {
  10512. mappings: [],
  10513. names: [],
  10514. sources: [],
  10515. version: 3
  10516. };
  10517. }
  10518. let mappings;
  10519. if (typeof map.mappings === 'string') {
  10520. mappings = decode(map.mappings);
  10521. }
  10522. else {
  10523. mappings = map.mappings;
  10524. }
  10525. return { ...map, mappings };
  10526. }
  10527. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  10528. const renderChunkReducer = (code, result, plugin) => {
  10529. if (result == null)
  10530. return code;
  10531. if (typeof result === 'string')
  10532. result = {
  10533. code: result,
  10534. map: undefined
  10535. };
  10536. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  10537. if (result.map !== null) {
  10538. const map = decodedSourcemap(result.map);
  10539. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  10540. }
  10541. return result.code;
  10542. };
  10543. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  10544. }
  10545. function renderNamePattern(pattern, patternName, replacements) {
  10546. if (!isPlainPathFragment(pattern))
  10547. return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
  10548. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  10549. if (!replacements.hasOwnProperty(type)) {
  10550. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  10551. }
  10552. const replacement = replacements[type]();
  10553. if (!isPlainPathFragment(replacement))
  10554. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  10555. return replacement;
  10556. });
  10557. }
  10558. function makeUnique(name, existingNames) {
  10559. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  10560. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  10561. return name;
  10562. const ext = extname(name);
  10563. name = name.substr(0, name.length - ext.length);
  10564. let uniqueName, uniqueIndex = 1;
  10565. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  10566. ;
  10567. return uniqueName;
  10568. }
  10569. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  10570. function getGlobalName(module, globals, hasExports, warn) {
  10571. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  10572. if (globalName) {
  10573. return globalName;
  10574. }
  10575. if (hasExports) {
  10576. warn({
  10577. code: 'MISSING_GLOBAL_NAME',
  10578. guess: module.variableName,
  10579. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  10580. source: module.id
  10581. });
  10582. return module.variableName;
  10583. }
  10584. }
  10585. class Chunk {
  10586. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  10587. this.orderedModules = orderedModules;
  10588. this.inputOptions = inputOptions;
  10589. this.outputOptions = outputOptions;
  10590. this.unsetOptions = unsetOptions;
  10591. this.pluginDriver = pluginDriver;
  10592. this.modulesById = modulesById;
  10593. this.chunkByModule = chunkByModule;
  10594. this.facadeChunkByModule = facadeChunkByModule;
  10595. this.includedNamespaces = includedNamespaces;
  10596. this.manualChunkAlias = manualChunkAlias;
  10597. this.entryModules = [];
  10598. this.exportMode = 'named';
  10599. this.facadeModule = null;
  10600. this.id = null;
  10601. this.namespaceVariableName = '';
  10602. this.variableName = '';
  10603. this.accessedGlobalsByScope = new Map();
  10604. this.dependencies = new Set();
  10605. this.dynamicDependencies = new Set();
  10606. this.dynamicEntryModules = [];
  10607. this.exportNamesByVariable = new Map();
  10608. this.exports = new Set();
  10609. this.exportsByName = Object.create(null);
  10610. this.fileName = null;
  10611. this.implicitEntryModules = [];
  10612. this.implicitlyLoadedBefore = new Set();
  10613. this.imports = new Set();
  10614. this.indentString = undefined;
  10615. this.isEmpty = true;
  10616. this.name = null;
  10617. this.needsExportsShim = false;
  10618. this.renderedDependencies = null;
  10619. this.renderedExports = null;
  10620. this.renderedHash = undefined;
  10621. this.renderedModules = Object.create(null);
  10622. this.renderedModuleSources = new Map();
  10623. this.renderedSource = null;
  10624. this.sortedExportNames = null;
  10625. this.strictFacade = false;
  10626. this.usedModules = undefined;
  10627. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  10628. const chunkModules = new Set(orderedModules);
  10629. for (const module of orderedModules) {
  10630. if (module.namespace.included) {
  10631. includedNamespaces.add(module);
  10632. }
  10633. if (this.isEmpty && module.isIncluded()) {
  10634. this.isEmpty = false;
  10635. }
  10636. if (module.info.isEntry || outputOptions.preserveModules) {
  10637. this.entryModules.push(module);
  10638. }
  10639. for (const importer of module.includedDynamicImporters) {
  10640. if (!chunkModules.has(importer)) {
  10641. this.dynamicEntryModules.push(module);
  10642. // Modules with synthetic exports need an artificial namespace for dynamic imports
  10643. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  10644. includedNamespaces.add(module);
  10645. this.exports.add(module.namespace);
  10646. }
  10647. }
  10648. }
  10649. if (module.implicitlyLoadedAfter.size > 0) {
  10650. this.implicitEntryModules.push(module);
  10651. }
  10652. }
  10653. this.suggestedVariableName = makeLegal(this.generateVariableName());
  10654. }
  10655. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  10656. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  10657. chunk.assignFacadeName(facadeName, facadedModule);
  10658. if (!facadeChunkByModule.has(facadedModule)) {
  10659. facadeChunkByModule.set(facadedModule, chunk);
  10660. }
  10661. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  10662. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  10663. }
  10664. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  10665. facadedModule.info.hasModuleSideEffects &&
  10666. facadedModule.hasEffects()) {
  10667. chunk.dependencies.add(chunkByModule.get(facadedModule));
  10668. }
  10669. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  10670. chunk.facadeModule = facadedModule;
  10671. chunk.strictFacade = true;
  10672. return chunk;
  10673. }
  10674. canModuleBeFacade(module, exposedVariables) {
  10675. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  10676. for (const exposedVariable of this.exports) {
  10677. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  10678. if (moduleExportNamesByVariable.size === 0 &&
  10679. module.isUserDefinedEntryPoint &&
  10680. module.preserveSignature === 'strict' &&
  10681. this.unsetOptions.has('preserveEntrySignatures')) {
  10682. this.inputOptions.onwarn({
  10683. code: 'EMPTY_FACADE',
  10684. id: module.id,
  10685. 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.`,
  10686. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  10687. });
  10688. }
  10689. return false;
  10690. }
  10691. }
  10692. for (const exposedVariable of exposedVariables) {
  10693. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  10694. return false;
  10695. }
  10696. }
  10697. return true;
  10698. }
  10699. generateExports() {
  10700. this.sortedExportNames = null;
  10701. const remainingExports = new Set(this.exports);
  10702. if (this.facadeModule !== null &&
  10703. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  10704. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  10705. for (const [variable, exportNames] of exportNamesByVariable) {
  10706. this.exportNamesByVariable.set(variable, [...exportNames]);
  10707. for (const exportName of exportNames) {
  10708. this.exportsByName[exportName] = variable;
  10709. }
  10710. remainingExports.delete(variable);
  10711. }
  10712. }
  10713. if (this.outputOptions.minifyInternalExports) {
  10714. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  10715. }
  10716. else {
  10717. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  10718. }
  10719. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  10720. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  10721. }
  10722. generateFacades() {
  10723. var _a;
  10724. const facades = [];
  10725. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  10726. const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
  10727. for (const module of entryModules) {
  10728. if (module.preserveSignature) {
  10729. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  10730. exposedVariables.add(exportedVariable);
  10731. }
  10732. }
  10733. }
  10734. for (const module of entryModules) {
  10735. const requiredFacades = Array.from(module.userChunkNames, name => ({
  10736. name
  10737. }));
  10738. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  10739. requiredFacades.push({});
  10740. }
  10741. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  10742. if (requiredFacades.length === 0) {
  10743. requiredFacades.push({});
  10744. }
  10745. if (!this.facadeModule) {
  10746. const needsStrictFacade = module.preserveSignature === 'strict' ||
  10747. (module.preserveSignature === 'exports-only' &&
  10748. module.getExportNamesByVariable().size !== 0);
  10749. if (!needsStrictFacade ||
  10750. this.outputOptions.preserveModules ||
  10751. this.canModuleBeFacade(module, exposedVariables)) {
  10752. this.facadeModule = module;
  10753. this.facadeChunkByModule.set(module, this);
  10754. if (module.preserveSignature) {
  10755. this.strictFacade = needsStrictFacade;
  10756. }
  10757. this.assignFacadeName(requiredFacades.shift(), module);
  10758. }
  10759. }
  10760. for (const facadeName of requiredFacades) {
  10761. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  10762. }
  10763. }
  10764. for (const module of this.dynamicEntryModules) {
  10765. if (module.info.syntheticNamedExports)
  10766. continue;
  10767. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  10768. this.facadeModule = module;
  10769. this.facadeChunkByModule.set(module, this);
  10770. this.strictFacade = true;
  10771. this.assignFacadeName({}, module);
  10772. }
  10773. else if (this.facadeModule === module &&
  10774. !this.strictFacade &&
  10775. this.canModuleBeFacade(module, exposedVariables)) {
  10776. this.strictFacade = true;
  10777. }
  10778. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  10779. this.includedNamespaces.add(module);
  10780. this.exports.add(module.namespace);
  10781. }
  10782. }
  10783. return facades;
  10784. }
  10785. generateId(addons, options, existingNames, includeHash) {
  10786. if (this.fileName !== null) {
  10787. return this.fileName;
  10788. }
  10789. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  10790. ? [options.entryFileNames, 'output.entryFileNames']
  10791. : [options.chunkFileNames, 'output.chunkFileNames'];
  10792. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  10793. format: () => options.format,
  10794. hash: () => includeHash
  10795. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  10796. : '[hash]',
  10797. name: () => this.getChunkName()
  10798. }), existingNames);
  10799. }
  10800. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  10801. const id = this.orderedModules[0].id;
  10802. const sanitizedId = sanitizeFileName(id);
  10803. let path;
  10804. if (isAbsolute(id)) {
  10805. const extension = extname(id);
  10806. const pattern = unsetOptions.has('entryFileNames')
  10807. ? NON_ASSET_EXTENSIONS.includes(extension)
  10808. ? '[name].js'
  10809. : '[name][extname].js'
  10810. : options.entryFileNames;
  10811. const currentDir = dirname(sanitizedId);
  10812. const fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, 'output.entryFileNames', {
  10813. ext: () => extension.substr(1),
  10814. extname: () => extension,
  10815. format: () => options.format,
  10816. name: () => this.getChunkName()
  10817. });
  10818. const currentPath = `${currentDir}/${fileName}`;
  10819. const { preserveModulesRoot } = options;
  10820. if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
  10821. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  10822. }
  10823. else {
  10824. path = relative(preserveModulesRelativeDir, currentPath);
  10825. }
  10826. }
  10827. else {
  10828. path = `_virtual/${basename(sanitizedId)}`;
  10829. }
  10830. return makeUnique(normalize(path), existingNames);
  10831. }
  10832. getChunkInfo() {
  10833. const facadeModule = this.facadeModule;
  10834. const getChunkName = this.getChunkName.bind(this);
  10835. return {
  10836. exports: this.getExportNames(),
  10837. facadeModuleId: facadeModule && facadeModule.id,
  10838. isDynamicEntry: this.dynamicEntryModules.length > 0,
  10839. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  10840. isImplicitEntry: this.implicitEntryModules.length > 0,
  10841. modules: this.renderedModules,
  10842. get name() {
  10843. return getChunkName();
  10844. },
  10845. type: 'chunk'
  10846. };
  10847. }
  10848. getChunkInfoWithFileNames() {
  10849. return Object.assign(this.getChunkInfo(), {
  10850. code: undefined,
  10851. dynamicImports: Array.from(this.dynamicDependencies, getId),
  10852. fileName: this.id,
  10853. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  10854. importedBindings: this.getImportedBindingsPerDependency(),
  10855. imports: Array.from(this.dependencies, getId),
  10856. map: undefined,
  10857. referencedFiles: this.getReferencedFiles()
  10858. });
  10859. }
  10860. getChunkName() {
  10861. return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
  10862. }
  10863. getExportNames() {
  10864. return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
  10865. }
  10866. getRenderedHash() {
  10867. if (this.renderedHash)
  10868. return this.renderedHash;
  10869. const hash = createHash();
  10870. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  10871. if (pluginHash) {
  10872. augmentation += pluginHash;
  10873. }
  10874. return augmentation;
  10875. });
  10876. hash.update(hashAugmentation);
  10877. hash.update(this.renderedSource.toString());
  10878. hash.update(this.getExportNames()
  10879. .map(exportName => {
  10880. const variable = this.exportsByName[exportName];
  10881. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  10882. })
  10883. .join(','));
  10884. return (this.renderedHash = hash.digest('hex'));
  10885. }
  10886. getVariableExportName(variable) {
  10887. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  10888. return '*';
  10889. }
  10890. return this.exportNamesByVariable.get(variable)[0];
  10891. }
  10892. link() {
  10893. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  10894. for (const module of this.orderedModules) {
  10895. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  10896. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  10897. this.setUpChunkImportsAndExportsForModule(module);
  10898. }
  10899. }
  10900. // prerender allows chunk hashes and names to be generated before finalizing
  10901. preRender(options, inputBase) {
  10902. const magicString = new Bundle$1({ separator: options.compact ? '' : '\n\n' });
  10903. this.usedModules = [];
  10904. this.indentString = getIndentString(this.orderedModules, options);
  10905. const n = options.compact ? '' : '\n';
  10906. const _ = options.compact ? '' : ' ';
  10907. const renderOptions = {
  10908. compact: options.compact,
  10909. dynamicImportFunction: options.dynamicImportFunction,
  10910. exportNamesByVariable: this.exportNamesByVariable,
  10911. format: options.format,
  10912. freeze: options.freeze,
  10913. indent: this.indentString,
  10914. namespaceToStringTag: options.namespaceToStringTag,
  10915. outputPluginDriver: this.pluginDriver,
  10916. varOrConst: options.preferConst ? 'const' : 'var'
  10917. };
  10918. // for static and dynamic entry points, inline the execution list to avoid loading latency
  10919. if (options.hoistTransitiveImports &&
  10920. !this.outputOptions.preserveModules &&
  10921. this.facadeModule !== null) {
  10922. for (const dep of this.dependencies) {
  10923. if (dep instanceof Chunk)
  10924. this.inlineChunkDependencies(dep);
  10925. }
  10926. }
  10927. this.prepareDynamicImportsAndImportMetas();
  10928. this.setIdentifierRenderResolutions(options);
  10929. let hoistedSource = '';
  10930. const renderedModules = this.renderedModules;
  10931. for (const module of this.orderedModules) {
  10932. let renderedLength = 0;
  10933. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  10934. const source = module.render(renderOptions).trim();
  10935. renderedLength = source.length();
  10936. if (renderedLength) {
  10937. if (options.compact && source.lastLine().indexOf('//') !== -1)
  10938. source.append('\n');
  10939. this.renderedModuleSources.set(module, source);
  10940. magicString.addSource(source);
  10941. this.usedModules.push(module);
  10942. }
  10943. const namespace = module.namespace;
  10944. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  10945. const rendered = namespace.renderBlock(renderOptions);
  10946. if (namespace.renderFirst())
  10947. hoistedSource += n + rendered;
  10948. else
  10949. magicString.addSource(new MagicString(rendered));
  10950. }
  10951. }
  10952. const { renderedExports, removedExports } = module.getRenderedExports();
  10953. renderedModules[module.id] = {
  10954. originalLength: module.originalCode.length,
  10955. removedExports,
  10956. renderedExports,
  10957. renderedLength
  10958. };
  10959. }
  10960. if (hoistedSource)
  10961. magicString.prepend(hoistedSource + n + n);
  10962. if (this.needsExportsShim) {
  10963. magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  10964. }
  10965. if (options.compact) {
  10966. this.renderedSource = magicString;
  10967. }
  10968. else {
  10969. this.renderedSource = magicString.trim();
  10970. }
  10971. this.renderedHash = undefined;
  10972. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  10973. const chunkName = this.getChunkName();
  10974. this.inputOptions.onwarn({
  10975. chunkName,
  10976. code: 'EMPTY_BUNDLE',
  10977. message: `Generated an empty chunk: "${chunkName}"`
  10978. });
  10979. }
  10980. this.setExternalRenderPaths(options, inputBase);
  10981. this.renderedDependencies = this.getChunkDependencyDeclarations(options);
  10982. this.renderedExports =
  10983. this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
  10984. }
  10985. async render(options, addons, outputChunk) {
  10986. timeStart('render format', 2);
  10987. const format = options.format;
  10988. const finalise = finalisers[format];
  10989. if (options.dynamicImportFunction && format !== 'es') {
  10990. this.inputOptions.onwarn({
  10991. code: 'INVALID_OPTION',
  10992. message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
  10993. });
  10994. }
  10995. // populate ids in the rendered declarations only here
  10996. // as chunk ids known only after prerender
  10997. for (const dependency of this.dependencies) {
  10998. const renderedDependency = this.renderedDependencies.get(dependency);
  10999. if (dependency instanceof ExternalModule) {
  11000. const originalId = dependency.renderPath;
  11001. renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
  11002. }
  11003. else {
  11004. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  11005. renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
  11006. }
  11007. }
  11008. this.finaliseDynamicImports(options);
  11009. this.finaliseImportMetas(format);
  11010. const hasExports = this.renderedExports.length !== 0 ||
  11011. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  11012. let usesTopLevelAwait = false;
  11013. const accessedGlobals = new Set();
  11014. for (const module of this.orderedModules) {
  11015. if (module.usesTopLevelAwait) {
  11016. usesTopLevelAwait = true;
  11017. }
  11018. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  11019. if (accessedGlobalVariables) {
  11020. for (const name of accessedGlobalVariables) {
  11021. accessedGlobals.add(name);
  11022. }
  11023. }
  11024. }
  11025. if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
  11026. return error({
  11027. code: 'INVALID_TLA_FORMAT',
  11028. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  11029. });
  11030. }
  11031. /* istanbul ignore next */
  11032. if (!this.id) {
  11033. throw new Error('Internal Error: expecting chunk id');
  11034. }
  11035. const magicString = finalise(this.renderedSource, {
  11036. accessedGlobals,
  11037. dependencies: [...this.renderedDependencies.values()],
  11038. exports: this.renderedExports,
  11039. hasExports,
  11040. id: this.id,
  11041. indentString: this.indentString,
  11042. intro: addons.intro,
  11043. isEntryFacade: this.outputOptions.preserveModules ||
  11044. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  11045. isModuleFacade: this.facadeModule !== null,
  11046. namedExportsMode: this.exportMode !== 'default',
  11047. outro: addons.outro,
  11048. usesTopLevelAwait,
  11049. varOrConst: options.preferConst ? 'const' : 'var',
  11050. warn: this.inputOptions.onwarn
  11051. }, options);
  11052. if (addons.banner)
  11053. magicString.prepend(addons.banner);
  11054. if (addons.footer)
  11055. magicString.append(addons.footer);
  11056. const prevCode = magicString.toString();
  11057. timeEnd('render format', 2);
  11058. let map = null;
  11059. const chunkSourcemapChain = [];
  11060. let code = await renderChunk({
  11061. code: prevCode,
  11062. options,
  11063. outputPluginDriver: this.pluginDriver,
  11064. renderChunk: outputChunk,
  11065. sourcemapChain: chunkSourcemapChain
  11066. });
  11067. if (options.sourcemap) {
  11068. timeStart('sourcemap', 2);
  11069. let file;
  11070. if (options.file)
  11071. file = resolve(options.sourcemapFile || options.file);
  11072. else if (options.dir)
  11073. file = resolve(options.dir, this.id);
  11074. else
  11075. file = resolve(this.id);
  11076. const decodedMap = magicString.generateDecodedMap({});
  11077. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  11078. map.sources = map.sources
  11079. .map(sourcePath => {
  11080. const { sourcemapPathTransform } = options;
  11081. if (sourcemapPathTransform) {
  11082. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  11083. if (typeof newSourcePath !== 'string') {
  11084. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  11085. }
  11086. return newSourcePath;
  11087. }
  11088. return sourcePath;
  11089. })
  11090. .map(normalize);
  11091. timeEnd('sourcemap', 2);
  11092. }
  11093. if (!options.compact && code[code.length - 1] !== '\n')
  11094. code += '\n';
  11095. return { code, map };
  11096. }
  11097. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  11098. for (const module of moduleDependencies) {
  11099. if (module instanceof Module) {
  11100. const chunk = this.chunkByModule.get(module);
  11101. if (chunk && chunk !== this) {
  11102. chunkDependencies.add(chunk);
  11103. }
  11104. }
  11105. else {
  11106. chunkDependencies.add(module);
  11107. }
  11108. }
  11109. }
  11110. assignFacadeName({ fileName, name }, facadedModule) {
  11111. if (fileName) {
  11112. this.fileName = fileName;
  11113. }
  11114. else {
  11115. this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
  11116. }
  11117. }
  11118. checkCircularDependencyImport(variable, importingModule) {
  11119. const variableModule = variable.module;
  11120. if (variableModule instanceof Module) {
  11121. const exportChunk = this.chunkByModule.get(variableModule);
  11122. let alternativeReexportModule;
  11123. do {
  11124. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  11125. if (alternativeReexportModule) {
  11126. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  11127. if (exportingChunk && exportingChunk !== exportChunk) {
  11128. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  11129. }
  11130. importingModule = alternativeReexportModule;
  11131. }
  11132. } while (alternativeReexportModule);
  11133. }
  11134. }
  11135. computeContentHashWithDependencies(addons, options, existingNames) {
  11136. const hash = createHash();
  11137. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
  11138. hash.update(options.format);
  11139. const dependenciesForHashing = new Set([this]);
  11140. for (const current of dependenciesForHashing) {
  11141. if (current instanceof ExternalModule) {
  11142. hash.update(':' + current.renderPath);
  11143. }
  11144. else {
  11145. hash.update(current.getRenderedHash());
  11146. hash.update(current.generateId(addons, options, existingNames, false));
  11147. }
  11148. if (current instanceof ExternalModule)
  11149. continue;
  11150. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  11151. dependenciesForHashing.add(dependency);
  11152. }
  11153. }
  11154. return hash.digest('hex').substr(0, 8);
  11155. }
  11156. ensureReexportsAreAvailableForModule(module) {
  11157. const map = module.getExportNamesByVariable();
  11158. for (const exportedVariable of map.keys()) {
  11159. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  11160. const importedVariable = isSynthetic
  11161. ? exportedVariable.getBaseVariable()
  11162. : exportedVariable;
  11163. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  11164. this.checkCircularDependencyImport(importedVariable, module);
  11165. const exportingModule = importedVariable.module;
  11166. if (exportingModule instanceof Module) {
  11167. const chunk = this.chunkByModule.get(exportingModule);
  11168. if (chunk && chunk !== this) {
  11169. chunk.exports.add(importedVariable);
  11170. if (isSynthetic) {
  11171. this.imports.add(importedVariable);
  11172. }
  11173. }
  11174. }
  11175. }
  11176. }
  11177. }
  11178. finaliseDynamicImports(options) {
  11179. const stripKnownJsExtensions = options.format === 'amd';
  11180. for (const [module, code] of this.renderedModuleSources) {
  11181. for (const { node, resolution } of module.dynamicImports) {
  11182. const chunk = this.chunkByModule.get(resolution);
  11183. const facadeChunk = this.facadeChunkByModule.get(resolution);
  11184. if (!resolution || !node.included || chunk === this) {
  11185. continue;
  11186. }
  11187. const renderedResolution = resolution instanceof Module
  11188. ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
  11189. : resolution instanceof ExternalModule
  11190. ? `'${resolution.renormalizeRenderPath
  11191. ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
  11192. : resolution.renderPath}'`
  11193. : resolution;
  11194. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  11195. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  11196. chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
  11197. }
  11198. }
  11199. }
  11200. finaliseImportMetas(format) {
  11201. for (const [module, code] of this.renderedModuleSources) {
  11202. for (const importMeta of module.importMetas) {
  11203. importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
  11204. }
  11205. }
  11206. }
  11207. generateVariableName() {
  11208. if (this.manualChunkAlias) {
  11209. return this.manualChunkAlias;
  11210. }
  11211. const moduleForNaming = this.entryModules[0] ||
  11212. this.implicitEntryModules[0] ||
  11213. this.dynamicEntryModules[0] ||
  11214. this.orderedModules[this.orderedModules.length - 1];
  11215. if (moduleForNaming) {
  11216. return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
  11217. }
  11218. return 'chunk';
  11219. }
  11220. getChunkDependencyDeclarations(options) {
  11221. const importSpecifiers = this.getImportSpecifiers();
  11222. const reexportSpecifiers = this.getReexportSpecifiers();
  11223. const dependencyDeclaration = new Map();
  11224. for (const dep of this.dependencies) {
  11225. const imports = importSpecifiers.get(dep) || null;
  11226. const reexports = reexportSpecifiers.get(dep) || null;
  11227. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  11228. dependencyDeclaration.set(dep, {
  11229. defaultVariableName: dep.defaultVariableName,
  11230. globalName: (dep instanceof ExternalModule &&
  11231. (options.format === 'umd' || options.format === 'iife') &&
  11232. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  11233. id: undefined,
  11234. imports,
  11235. isChunk: dep instanceof Chunk,
  11236. name: dep.variableName,
  11237. namedExportsMode,
  11238. namespaceVariableName: dep.namespaceVariableName,
  11239. reexports
  11240. });
  11241. }
  11242. return dependencyDeclaration;
  11243. }
  11244. getChunkExportDeclarations(format) {
  11245. const exports = [];
  11246. for (const exportName of this.getExportNames()) {
  11247. if (exportName[0] === '*')
  11248. continue;
  11249. const variable = this.exportsByName[exportName];
  11250. if (!(variable instanceof SyntheticNamedExportVariable)) {
  11251. const module = variable.module;
  11252. if (module && this.chunkByModule.get(module) !== this)
  11253. continue;
  11254. }
  11255. let expression = null;
  11256. let hoisted = false;
  11257. let uninitialized = false;
  11258. let local = variable.getName();
  11259. if (variable instanceof LocalVariable) {
  11260. if (variable.init === UNDEFINED_EXPRESSION) {
  11261. uninitialized = true;
  11262. }
  11263. for (const declaration of variable.declarations) {
  11264. if (declaration.parent instanceof FunctionDeclaration ||
  11265. (declaration instanceof ExportDefaultDeclaration &&
  11266. declaration.declaration instanceof FunctionDeclaration)) {
  11267. hoisted = true;
  11268. break;
  11269. }
  11270. }
  11271. }
  11272. else if (variable instanceof SyntheticNamedExportVariable) {
  11273. expression = local;
  11274. if (format === 'es' && exportName !== 'default') {
  11275. local = variable.renderName;
  11276. }
  11277. }
  11278. exports.push({
  11279. exported: exportName,
  11280. expression,
  11281. hoisted,
  11282. local,
  11283. uninitialized
  11284. });
  11285. }
  11286. return exports;
  11287. }
  11288. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  11289. const dependencies = new Set();
  11290. const deconflictedDefault = new Set();
  11291. const deconflictedNamespace = new Set();
  11292. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  11293. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  11294. const module = variable.module;
  11295. if (module instanceof ExternalModule) {
  11296. dependencies.add(module);
  11297. if (addNonNamespacesAndInteropHelpers) {
  11298. if (variable.name === 'default') {
  11299. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  11300. deconflictedDefault.add(module);
  11301. }
  11302. }
  11303. else if (variable.name === '*') {
  11304. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  11305. deconflictedNamespace.add(module);
  11306. }
  11307. }
  11308. }
  11309. }
  11310. else {
  11311. const chunk = this.chunkByModule.get(module);
  11312. if (chunk !== this) {
  11313. dependencies.add(chunk);
  11314. if (addNonNamespacesAndInteropHelpers &&
  11315. chunk.exportMode === 'default' &&
  11316. variable.isNamespace) {
  11317. deconflictedNamespace.add(chunk);
  11318. }
  11319. }
  11320. }
  11321. }
  11322. }
  11323. if (addDependenciesWithoutBindings) {
  11324. for (const dependency of this.dependencies) {
  11325. dependencies.add(dependency);
  11326. }
  11327. }
  11328. return { deconflictedDefault, deconflictedNamespace, dependencies };
  11329. }
  11330. getFallbackChunkName() {
  11331. if (this.manualChunkAlias) {
  11332. return this.manualChunkAlias;
  11333. }
  11334. if (this.fileName) {
  11335. return getAliasName(this.fileName);
  11336. }
  11337. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  11338. }
  11339. getImportedBindingsPerDependency() {
  11340. const importSpecifiers = {};
  11341. for (const [dependency, declaration] of this.renderedDependencies) {
  11342. const specifiers = new Set();
  11343. if (declaration.imports) {
  11344. for (const { imported } of declaration.imports) {
  11345. specifiers.add(imported);
  11346. }
  11347. }
  11348. if (declaration.reexports) {
  11349. for (const { imported } of declaration.reexports) {
  11350. specifiers.add(imported);
  11351. }
  11352. }
  11353. importSpecifiers[dependency.id] = [...specifiers];
  11354. }
  11355. return importSpecifiers;
  11356. }
  11357. getImportSpecifiers() {
  11358. const { interop } = this.outputOptions;
  11359. const importsByDependency = new Map();
  11360. for (const variable of this.imports) {
  11361. const module = variable.module;
  11362. let dependency;
  11363. let imported;
  11364. if (module instanceof ExternalModule) {
  11365. dependency = module;
  11366. imported = variable.name;
  11367. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  11368. return error(errUnexpectedNamedImport(module.id, imported, false));
  11369. }
  11370. }
  11371. else {
  11372. dependency = this.chunkByModule.get(module);
  11373. imported = dependency.getVariableExportName(variable);
  11374. }
  11375. getOrCreate(importsByDependency, dependency, () => []).push({
  11376. imported,
  11377. local: variable.getName()
  11378. });
  11379. }
  11380. return importsByDependency;
  11381. }
  11382. getReexportSpecifiers() {
  11383. const { externalLiveBindings, interop } = this.outputOptions;
  11384. const reexportSpecifiers = new Map();
  11385. for (let exportName of this.getExportNames()) {
  11386. let dependency;
  11387. let imported;
  11388. let needsLiveBinding = false;
  11389. if (exportName[0] === '*') {
  11390. const id = exportName.substr(1);
  11391. if (interop(id) === 'defaultOnly') {
  11392. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  11393. }
  11394. needsLiveBinding = externalLiveBindings;
  11395. dependency = this.modulesById.get(id);
  11396. imported = exportName = '*';
  11397. }
  11398. else {
  11399. const variable = this.exportsByName[exportName];
  11400. if (variable instanceof SyntheticNamedExportVariable)
  11401. continue;
  11402. const module = variable.module;
  11403. if (module instanceof Module) {
  11404. dependency = this.chunkByModule.get(module);
  11405. if (dependency === this)
  11406. continue;
  11407. imported = dependency.getVariableExportName(variable);
  11408. needsLiveBinding = variable.isReassigned;
  11409. }
  11410. else {
  11411. dependency = module;
  11412. imported = variable.name;
  11413. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  11414. return error(errUnexpectedNamedImport(module.id, imported, true));
  11415. }
  11416. needsLiveBinding =
  11417. externalLiveBindings &&
  11418. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  11419. }
  11420. }
  11421. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  11422. imported,
  11423. needsLiveBinding,
  11424. reexported: exportName
  11425. });
  11426. }
  11427. return reexportSpecifiers;
  11428. }
  11429. getReferencedFiles() {
  11430. const referencedFiles = [];
  11431. for (const module of this.orderedModules) {
  11432. for (const meta of module.importMetas) {
  11433. const fileName = meta.getReferencedFileName(this.pluginDriver);
  11434. if (fileName) {
  11435. referencedFiles.push(fileName);
  11436. }
  11437. }
  11438. }
  11439. return referencedFiles;
  11440. }
  11441. getRelativePath(targetPath, stripJsExtension) {
  11442. let relativePath = normalize(relative(dirname(this.id), targetPath));
  11443. if (stripJsExtension && relativePath.endsWith('.js')) {
  11444. relativePath = relativePath.slice(0, -3);
  11445. }
  11446. if (relativePath === '..')
  11447. return '../../' + basename(targetPath);
  11448. if (relativePath === '')
  11449. return '../' + basename(targetPath);
  11450. return relativePath.startsWith('../') ? relativePath : './' + relativePath;
  11451. }
  11452. inlineChunkDependencies(chunk) {
  11453. for (const dep of chunk.dependencies) {
  11454. if (this.dependencies.has(dep))
  11455. continue;
  11456. this.dependencies.add(dep);
  11457. if (dep instanceof Chunk) {
  11458. this.inlineChunkDependencies(dep);
  11459. }
  11460. }
  11461. }
  11462. prepareDynamicImportsAndImportMetas() {
  11463. var _a;
  11464. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  11465. for (const module of this.orderedModules) {
  11466. for (const { node, resolution } of module.dynamicImports) {
  11467. if (node.included) {
  11468. if (resolution instanceof Module) {
  11469. const chunk = this.chunkByModule.get(resolution);
  11470. if (chunk === this) {
  11471. node.setInternalResolution(resolution.namespace);
  11472. }
  11473. else {
  11474. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  11475. }
  11476. }
  11477. else {
  11478. node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  11479. }
  11480. }
  11481. }
  11482. for (const importMeta of module.importMetas) {
  11483. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  11484. }
  11485. }
  11486. }
  11487. setExternalRenderPaths(options, inputBase) {
  11488. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  11489. if (dependency instanceof ExternalModule) {
  11490. dependency.setRenderPath(options, inputBase);
  11491. }
  11492. }
  11493. }
  11494. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  11495. const syntheticExports = new Set();
  11496. for (const exportName of this.getExportNames()) {
  11497. const exportVariable = this.exportsByName[exportName];
  11498. if (exportVariable instanceof ExportShimVariable) {
  11499. this.needsExportsShim = true;
  11500. }
  11501. if (format !== 'es' &&
  11502. format !== 'system' &&
  11503. exportVariable.isReassigned &&
  11504. !exportVariable.isId) {
  11505. exportVariable.setRenderNames('exports', exportName);
  11506. }
  11507. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  11508. syntheticExports.add(exportVariable);
  11509. }
  11510. else {
  11511. exportVariable.setRenderNames(null, null);
  11512. }
  11513. }
  11514. const usedNames = new Set(['Object', 'Promise']);
  11515. if (this.needsExportsShim) {
  11516. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  11517. }
  11518. if (namespaceToStringTag) {
  11519. usedNames.add('Symbol');
  11520. }
  11521. switch (format) {
  11522. case 'system':
  11523. usedNames.add('module').add('exports');
  11524. break;
  11525. case 'es':
  11526. break;
  11527. case 'cjs':
  11528. usedNames.add('module').add('require').add('__filename').add('__dirname');
  11529. // fallthrough
  11530. default:
  11531. usedNames.add('exports');
  11532. for (const helper of HELPER_NAMES) {
  11533. usedNames.add(helper);
  11534. }
  11535. }
  11536. 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);
  11537. }
  11538. setUpChunkImportsAndExportsForModule(module) {
  11539. const moduleImports = new Set(module.imports);
  11540. // when we are not preserving modules, we need to make all namespace variables available for
  11541. // rendering the namespace object
  11542. if (!this.outputOptions.preserveModules) {
  11543. if (this.includedNamespaces.has(module)) {
  11544. const memberVariables = module.namespace.getMemberVariables();
  11545. for (const name of Object.keys(memberVariables)) {
  11546. moduleImports.add(memberVariables[name]);
  11547. }
  11548. }
  11549. }
  11550. for (let variable of moduleImports) {
  11551. if (variable instanceof ExportDefaultVariable) {
  11552. variable = variable.getOriginalVariable();
  11553. }
  11554. if (variable instanceof SyntheticNamedExportVariable) {
  11555. variable = variable.getBaseVariable();
  11556. }
  11557. const chunk = this.chunkByModule.get(variable.module);
  11558. if (chunk !== this) {
  11559. this.imports.add(variable);
  11560. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  11561. variable.module instanceof Module) {
  11562. chunk.exports.add(variable);
  11563. this.checkCircularDependencyImport(variable, module);
  11564. }
  11565. }
  11566. }
  11567. if (this.includedNamespaces.has(module) ||
  11568. (module.info.isEntry && module.preserveSignature !== false) ||
  11569. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  11570. this.ensureReexportsAreAvailableForModule(module);
  11571. }
  11572. for (const { node, resolution } of module.dynamicImports) {
  11573. if (node.included &&
  11574. resolution instanceof Module &&
  11575. this.chunkByModule.get(resolution) === this &&
  11576. !this.includedNamespaces.has(resolution)) {
  11577. this.includedNamespaces.add(resolution);
  11578. this.ensureReexportsAreAvailableForModule(resolution);
  11579. }
  11580. }
  11581. }
  11582. }
  11583. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  11584. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  11585. async function createAddons(options, outputPluginDriver) {
  11586. try {
  11587. let [banner, footer, intro, outro] = await Promise.all([
  11588. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  11589. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  11590. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  11591. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  11592. ]);
  11593. if (intro)
  11594. intro += '\n\n';
  11595. if (outro)
  11596. outro = `\n\n${outro}`;
  11597. if (banner.length)
  11598. banner += '\n';
  11599. if (footer.length)
  11600. footer = '\n' + footer;
  11601. return { intro, outro, banner, footer };
  11602. }
  11603. catch (err) {
  11604. return error({
  11605. code: 'ADDON_ERROR',
  11606. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  11607. \tError Message: ${err.message}`
  11608. });
  11609. }
  11610. }
  11611. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  11612. const chunkDefinitions = [];
  11613. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  11614. const manualChunkModulesByAlias = Object.create(null);
  11615. for (const [entry, alias] of manualChunkAliasByEntry) {
  11616. const chunkModules = (manualChunkModulesByAlias[alias] =
  11617. manualChunkModulesByAlias[alias] || []);
  11618. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  11619. }
  11620. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  11621. chunkDefinitions.push({ alias, modules });
  11622. }
  11623. const assignedEntryPointsByModule = new Map();
  11624. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  11625. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  11626. const staticEntries = new Set(entryModules);
  11627. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  11628. const modulesToHandle = new Set([entry]);
  11629. for (const module of modulesToHandle) {
  11630. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  11631. if (dynamicDependentEntryPoints &&
  11632. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  11633. continue;
  11634. }
  11635. else {
  11636. assignedEntryPoints.add(entry);
  11637. }
  11638. for (const dependency of module.getDependenciesToBeIncluded()) {
  11639. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  11640. modulesToHandle.add(dependency);
  11641. }
  11642. }
  11643. }
  11644. }
  11645. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  11646. const entriesToCheck = new Set(entryPoints);
  11647. for (const entry of entriesToCheck) {
  11648. if (!containedIn.has(entry)) {
  11649. if (staticEntries.has(entry))
  11650. return false;
  11651. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  11652. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  11653. entriesToCheck.add(dependentEntry);
  11654. }
  11655. }
  11656. }
  11657. return true;
  11658. }
  11659. for (const entry of entryModules) {
  11660. if (!modulesInManualChunks.has(entry)) {
  11661. assignEntryToStaticDependencies(entry, null);
  11662. }
  11663. }
  11664. for (const entry of dynamicEntryModules) {
  11665. if (!modulesInManualChunks.has(entry)) {
  11666. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  11667. }
  11668. }
  11669. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  11670. return chunkDefinitions;
  11671. }
  11672. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  11673. const modulesToHandle = new Set([entry]);
  11674. for (const module of modulesToHandle) {
  11675. modulesInManualChunks.add(module);
  11676. manualChunkModules.push(module);
  11677. for (const dependency of module.dependencies) {
  11678. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  11679. modulesToHandle.add(dependency);
  11680. }
  11681. }
  11682. }
  11683. }
  11684. function analyzeModuleGraph(entryModules) {
  11685. const dynamicEntryModules = new Set();
  11686. const dependentEntryPointsByModule = new Map();
  11687. const entriesToHandle = new Set(entryModules);
  11688. for (const currentEntry of entriesToHandle) {
  11689. const modulesToHandle = new Set([currentEntry]);
  11690. for (const module of modulesToHandle) {
  11691. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  11692. for (const dependency of module.getDependenciesToBeIncluded()) {
  11693. if (!(dependency instanceof ExternalModule)) {
  11694. modulesToHandle.add(dependency);
  11695. }
  11696. }
  11697. for (const { resolution } of module.dynamicImports) {
  11698. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  11699. dynamicEntryModules.add(resolution);
  11700. entriesToHandle.add(resolution);
  11701. }
  11702. }
  11703. for (const dependency of module.implicitlyLoadedBefore) {
  11704. dynamicEntryModules.add(dependency);
  11705. entriesToHandle.add(dependency);
  11706. }
  11707. }
  11708. }
  11709. return { dependentEntryPointsByModule, dynamicEntryModules };
  11710. }
  11711. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  11712. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  11713. for (const dynamicEntry of dynamicEntryModules) {
  11714. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  11715. for (const importer of [
  11716. ...dynamicEntry.includedDynamicImporters,
  11717. ...dynamicEntry.implicitlyLoadedAfter
  11718. ]) {
  11719. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  11720. dynamicDependentEntryPoints.add(entryPoint);
  11721. }
  11722. }
  11723. }
  11724. return dynamicallyDependentEntryPointsByDynamicEntry;
  11725. }
  11726. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  11727. const chunkModules = Object.create(null);
  11728. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  11729. let chunkSignature = '';
  11730. for (const entry of allEntryPoints) {
  11731. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  11732. }
  11733. const chunk = chunkModules[chunkSignature];
  11734. if (chunk) {
  11735. chunk.push(module);
  11736. }
  11737. else {
  11738. chunkModules[chunkSignature] = [module];
  11739. }
  11740. }
  11741. return Object.keys(chunkModules).map(chunkSignature => ({
  11742. alias: null,
  11743. modules: chunkModules[chunkSignature]
  11744. }));
  11745. }
  11746. // ported from https://github.com/substack/node-commondir
  11747. function commondir(files) {
  11748. if (files.length === 0)
  11749. return '/';
  11750. if (files.length === 1)
  11751. return dirname(files[0]);
  11752. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  11753. const pathSegements = file.split(/\/+|\\+/);
  11754. let i;
  11755. for (i = 0; commonSegments[i] === pathSegements[i] &&
  11756. i < Math.min(commonSegments.length, pathSegements.length); i++)
  11757. ;
  11758. return commonSegments.slice(0, i);
  11759. }, files[0].split(/\/+|\\+/));
  11760. // Windows correctly handles paths with forward-slashes
  11761. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  11762. }
  11763. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  11764. function sortByExecutionOrder(units) {
  11765. units.sort(compareExecIndex);
  11766. }
  11767. function analyseModuleExecution(entryModules) {
  11768. let nextExecIndex = 0;
  11769. const cyclePaths = [];
  11770. const analysedModules = new Set();
  11771. const dynamicImports = new Set();
  11772. const parents = new Map();
  11773. const orderedModules = [];
  11774. const analyseModule = (module) => {
  11775. if (module instanceof Module) {
  11776. for (const dependency of module.dependencies) {
  11777. if (parents.has(dependency)) {
  11778. if (!analysedModules.has(dependency)) {
  11779. cyclePaths.push(getCyclePath(dependency, module, parents));
  11780. }
  11781. continue;
  11782. }
  11783. parents.set(dependency, module);
  11784. analyseModule(dependency);
  11785. }
  11786. for (const dependency of module.implicitlyLoadedBefore) {
  11787. dynamicImports.add(dependency);
  11788. }
  11789. for (const { resolution } of module.dynamicImports) {
  11790. if (resolution instanceof Module) {
  11791. dynamicImports.add(resolution);
  11792. }
  11793. }
  11794. orderedModules.push(module);
  11795. }
  11796. module.execIndex = nextExecIndex++;
  11797. analysedModules.add(module);
  11798. };
  11799. for (const curEntry of entryModules) {
  11800. if (!parents.has(curEntry)) {
  11801. parents.set(curEntry, null);
  11802. analyseModule(curEntry);
  11803. }
  11804. }
  11805. for (const curEntry of dynamicImports) {
  11806. if (!parents.has(curEntry)) {
  11807. parents.set(curEntry, null);
  11808. analyseModule(curEntry);
  11809. }
  11810. }
  11811. return { orderedModules, cyclePaths };
  11812. }
  11813. function getCyclePath(module, parent, parents) {
  11814. const cycleSymbol = Symbol(module.id);
  11815. const path = [relativeId(module.id)];
  11816. let nextModule = parent;
  11817. module.cycles.add(cycleSymbol);
  11818. while (nextModule !== module) {
  11819. nextModule.cycles.add(cycleSymbol);
  11820. path.push(relativeId(nextModule.id));
  11821. nextModule = parents.get(nextModule);
  11822. }
  11823. path.push(path[0]);
  11824. path.reverse();
  11825. return path;
  11826. }
  11827. var BuildPhase;
  11828. (function (BuildPhase) {
  11829. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11830. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11831. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11832. })(BuildPhase || (BuildPhase = {}));
  11833. function generateAssetFileName(name, source, output) {
  11834. const emittedName = name || 'asset';
  11835. return makeUnique(renderNamePattern(typeof output.assetFileNames === 'function'
  11836. ? output.assetFileNames({ name, source, type: 'asset' })
  11837. : output.assetFileNames, 'output.assetFileNames', {
  11838. hash() {
  11839. const hash = createHash();
  11840. hash.update(emittedName);
  11841. hash.update(':');
  11842. hash.update(source);
  11843. return hash.digest('hex').substr(0, 8);
  11844. },
  11845. ext: () => extname(emittedName).substr(1),
  11846. extname: () => extname(emittedName),
  11847. name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length)
  11848. }), output.bundle);
  11849. }
  11850. function reserveFileNameInBundle(fileName, bundle, warn) {
  11851. if (fileName in bundle) {
  11852. warn(errFileNameConflict(fileName));
  11853. }
  11854. bundle[fileName] = FILE_PLACEHOLDER;
  11855. }
  11856. const FILE_PLACEHOLDER = {
  11857. type: 'placeholder'
  11858. };
  11859. function hasValidType(emittedFile) {
  11860. return Boolean(emittedFile &&
  11861. (emittedFile.type === 'asset' ||
  11862. emittedFile.type === 'chunk'));
  11863. }
  11864. function hasValidName(emittedFile) {
  11865. const validatedName = emittedFile.fileName || emittedFile.name;
  11866. return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
  11867. }
  11868. function getValidSource(source, emittedFile, fileReferenceId) {
  11869. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  11870. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  11871. 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.`));
  11872. }
  11873. return source;
  11874. }
  11875. function getAssetFileName(file, referenceId) {
  11876. if (typeof file.fileName !== 'string') {
  11877. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  11878. }
  11879. return file.fileName;
  11880. }
  11881. function getChunkFileName(file, facadeChunkByModule) {
  11882. var _a;
  11883. 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));
  11884. if (!fileName)
  11885. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  11886. return fileName;
  11887. }
  11888. class FileEmitter {
  11889. constructor(graph, options, baseFileEmitter) {
  11890. this.graph = graph;
  11891. this.options = options;
  11892. this.facadeChunkByModule = null;
  11893. this.output = null;
  11894. this.assertAssetsFinalized = () => {
  11895. for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
  11896. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  11897. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  11898. }
  11899. };
  11900. this.emitFile = (emittedFile) => {
  11901. if (!hasValidType(emittedFile)) {
  11902. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  11903. }
  11904. if (!hasValidName(emittedFile)) {
  11905. 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}".`));
  11906. }
  11907. if (emittedFile.type === 'chunk') {
  11908. return this.emitChunk(emittedFile);
  11909. }
  11910. else {
  11911. return this.emitAsset(emittedFile);
  11912. }
  11913. };
  11914. this.getFileName = (fileReferenceId) => {
  11915. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  11916. if (!emittedFile)
  11917. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  11918. if (emittedFile.type === 'chunk') {
  11919. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  11920. }
  11921. else {
  11922. return getAssetFileName(emittedFile, fileReferenceId);
  11923. }
  11924. };
  11925. this.setAssetSource = (referenceId, requestedSource) => {
  11926. const consumedFile = this.filesByReferenceId.get(referenceId);
  11927. if (!consumedFile)
  11928. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  11929. if (consumedFile.type !== 'asset') {
  11930. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  11931. }
  11932. if (consumedFile.source !== undefined) {
  11933. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  11934. }
  11935. const source = getValidSource(requestedSource, consumedFile, referenceId);
  11936. if (this.output) {
  11937. this.finalizeAsset(consumedFile, source, referenceId, this.output);
  11938. }
  11939. else {
  11940. consumedFile.source = source;
  11941. }
  11942. };
  11943. this.setOutputBundle = (outputBundle, assetFileNames, facadeChunkByModule) => {
  11944. this.output = {
  11945. assetFileNames,
  11946. bundle: outputBundle
  11947. };
  11948. this.facadeChunkByModule = facadeChunkByModule;
  11949. for (const emittedFile of this.filesByReferenceId.values()) {
  11950. if (emittedFile.fileName) {
  11951. reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.options.onwarn);
  11952. }
  11953. }
  11954. for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
  11955. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  11956. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
  11957. }
  11958. }
  11959. };
  11960. this.filesByReferenceId = baseFileEmitter
  11961. ? new Map(baseFileEmitter.filesByReferenceId)
  11962. : new Map();
  11963. }
  11964. assignReferenceId(file, idBase) {
  11965. let referenceId;
  11966. do {
  11967. const hash = createHash();
  11968. if (referenceId) {
  11969. hash.update(referenceId);
  11970. }
  11971. else {
  11972. hash.update(idBase);
  11973. }
  11974. referenceId = hash.digest('hex').substr(0, 8);
  11975. } while (this.filesByReferenceId.has(referenceId));
  11976. this.filesByReferenceId.set(referenceId, file);
  11977. return referenceId;
  11978. }
  11979. emitAsset(emittedAsset) {
  11980. const source = typeof emittedAsset.source !== 'undefined'
  11981. ? getValidSource(emittedAsset.source, emittedAsset, null)
  11982. : undefined;
  11983. const consumedAsset = {
  11984. fileName: emittedAsset.fileName,
  11985. name: emittedAsset.name,
  11986. source,
  11987. type: 'asset'
  11988. };
  11989. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  11990. if (this.output) {
  11991. if (emittedAsset.fileName) {
  11992. reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.options.onwarn);
  11993. }
  11994. if (source !== undefined) {
  11995. this.finalizeAsset(consumedAsset, source, referenceId, this.output);
  11996. }
  11997. }
  11998. return referenceId;
  11999. }
  12000. emitChunk(emittedChunk) {
  12001. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  12002. return error(errInvalidRollupPhaseForChunkEmission());
  12003. }
  12004. if (typeof emittedChunk.id !== 'string') {
  12005. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  12006. }
  12007. const consumedChunk = {
  12008. fileName: emittedChunk.fileName,
  12009. module: null,
  12010. name: emittedChunk.name || emittedChunk.id,
  12011. type: 'chunk'
  12012. };
  12013. this.graph.moduleLoader
  12014. .emitChunk(emittedChunk)
  12015. .then(module => (consumedChunk.module = module))
  12016. .catch(() => {
  12017. // Avoid unhandled Promise rejection as the error will be thrown later
  12018. // once module loading has finished
  12019. });
  12020. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  12021. }
  12022. finalizeAsset(consumedFile, source, referenceId, output) {
  12023. const fileName = consumedFile.fileName ||
  12024. findExistingAssetFileNameWithSource(output.bundle, source) ||
  12025. generateAssetFileName(consumedFile.name, source, output);
  12026. // We must not modify the original assets to avoid interaction between outputs
  12027. const assetWithFileName = { ...consumedFile, source, fileName };
  12028. this.filesByReferenceId.set(referenceId, assetWithFileName);
  12029. const options = this.options;
  12030. output.bundle[fileName] = {
  12031. fileName,
  12032. name: consumedFile.name,
  12033. get isAsset() {
  12034. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  12035. return true;
  12036. },
  12037. source,
  12038. type: 'asset'
  12039. };
  12040. }
  12041. }
  12042. function findExistingAssetFileNameWithSource(bundle, source) {
  12043. for (const fileName of Object.keys(bundle)) {
  12044. const outputFile = bundle[fileName];
  12045. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  12046. return fileName;
  12047. }
  12048. return null;
  12049. }
  12050. function areSourcesEqual(sourceA, sourceB) {
  12051. if (typeof sourceA === 'string') {
  12052. return sourceA === sourceB;
  12053. }
  12054. if (typeof sourceB === 'string') {
  12055. return false;
  12056. }
  12057. if ('equals' in sourceA) {
  12058. return sourceA.equals(sourceB);
  12059. }
  12060. if (sourceA.length !== sourceB.length) {
  12061. return false;
  12062. }
  12063. for (let index = 0; index < sourceA.length; index++) {
  12064. if (sourceA[index] !== sourceB[index]) {
  12065. return false;
  12066. }
  12067. }
  12068. return true;
  12069. }
  12070. class Bundle {
  12071. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  12072. this.outputOptions = outputOptions;
  12073. this.unsetOptions = unsetOptions;
  12074. this.inputOptions = inputOptions;
  12075. this.pluginDriver = pluginDriver;
  12076. this.graph = graph;
  12077. this.facadeChunkByModule = new Map();
  12078. this.includedNamespaces = new Set();
  12079. }
  12080. async generate(isWrite) {
  12081. timeStart('GENERATE', 1);
  12082. const outputBundle = Object.create(null);
  12083. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions.assetFileNames, this.facadeChunkByModule);
  12084. try {
  12085. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  12086. timeStart('generate chunks', 2);
  12087. const chunks = await this.generateChunks();
  12088. if (chunks.length > 1) {
  12089. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  12090. }
  12091. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  12092. timeEnd('generate chunks', 2);
  12093. timeStart('render modules', 2);
  12094. // We need to create addons before prerender because at the moment, there
  12095. // can be no async code between prerender and render due to internal state
  12096. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  12097. this.prerenderChunks(chunks, inputBase);
  12098. timeEnd('render modules', 2);
  12099. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
  12100. }
  12101. catch (error) {
  12102. await this.pluginDriver.hookParallel('renderError', [error]);
  12103. throw error;
  12104. }
  12105. await this.pluginDriver.hookSeq('generateBundle', [
  12106. this.outputOptions,
  12107. outputBundle,
  12108. isWrite
  12109. ]);
  12110. this.finaliseAssets(outputBundle);
  12111. timeEnd('GENERATE', 1);
  12112. return outputBundle;
  12113. }
  12114. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
  12115. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  12116. for (const chunk of chunks) {
  12117. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  12118. }
  12119. await Promise.all(chunks.map(async (chunk) => {
  12120. const outputChunk = outputBundle[chunk.id];
  12121. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
  12122. }));
  12123. }
  12124. async addManualChunks(manualChunks) {
  12125. const manualChunkAliasByEntry = new Map();
  12126. const chunkEntries = await Promise.all(Object.keys(manualChunks).map(async (alias) => ({
  12127. alias,
  12128. entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
  12129. })));
  12130. for (const { alias, entries } of chunkEntries) {
  12131. for (const entry of entries) {
  12132. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  12133. }
  12134. }
  12135. return manualChunkAliasByEntry;
  12136. }
  12137. assignChunkIds(chunks, inputBase, addons, bundle) {
  12138. const entryChunks = [];
  12139. const otherChunks = [];
  12140. for (const chunk of chunks) {
  12141. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  12142. ? entryChunks
  12143. : otherChunks).push(chunk);
  12144. }
  12145. // make sure entry chunk names take precedence with regard to deconflicting
  12146. const chunksForNaming = entryChunks.concat(otherChunks);
  12147. for (const chunk of chunksForNaming) {
  12148. if (this.outputOptions.file) {
  12149. chunk.id = basename(this.outputOptions.file);
  12150. }
  12151. else if (this.outputOptions.preserveModules) {
  12152. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  12153. }
  12154. else {
  12155. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  12156. }
  12157. bundle[chunk.id] = FILE_PLACEHOLDER;
  12158. }
  12159. }
  12160. assignManualChunks(getManualChunk) {
  12161. const manualChunkAliasByEntry = new Map();
  12162. const manualChunksApi = {
  12163. getModuleIds: () => this.graph.modulesById.keys(),
  12164. getModuleInfo: this.graph.getModuleInfo
  12165. };
  12166. for (const module of this.graph.modulesById.values()) {
  12167. if (module instanceof Module) {
  12168. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  12169. if (typeof manualChunkAlias === 'string') {
  12170. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  12171. }
  12172. }
  12173. }
  12174. return manualChunkAliasByEntry;
  12175. }
  12176. finaliseAssets(outputBundle) {
  12177. for (const key of Object.keys(outputBundle)) {
  12178. const file = outputBundle[key];
  12179. if (!file.type) {
  12180. 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);
  12181. file.type = 'asset';
  12182. }
  12183. if (this.outputOptions.validate && typeof file.code == 'string') {
  12184. try {
  12185. this.graph.contextParse(file.code, {
  12186. allowHashBang: true,
  12187. ecmaVersion: 'latest'
  12188. });
  12189. }
  12190. catch (exception) {
  12191. this.inputOptions.onwarn(errChunkInvalid(file, exception));
  12192. }
  12193. }
  12194. }
  12195. this.pluginDriver.finaliseAssets();
  12196. }
  12197. async generateChunks() {
  12198. const { manualChunks } = this.outputOptions;
  12199. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  12200. ? await this.addManualChunks(manualChunks)
  12201. : this.assignManualChunks(manualChunks);
  12202. const chunks = [];
  12203. const chunkByModule = new Map();
  12204. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  12205. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  12206. : this.outputOptions.preserveModules
  12207. ? getIncludedModules(this.graph.modulesById).map(module => ({
  12208. alias: null,
  12209. modules: [module]
  12210. }))
  12211. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  12212. sortByExecutionOrder(modules);
  12213. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  12214. chunks.push(chunk);
  12215. for (const module of modules) {
  12216. chunkByModule.set(module, chunk);
  12217. }
  12218. }
  12219. for (const chunk of chunks) {
  12220. chunk.link();
  12221. }
  12222. const facades = [];
  12223. for (const chunk of chunks) {
  12224. facades.push(...chunk.generateFacades());
  12225. }
  12226. return [...chunks, ...facades];
  12227. }
  12228. prerenderChunks(chunks, inputBase) {
  12229. for (const chunk of chunks) {
  12230. chunk.generateExports();
  12231. }
  12232. for (const chunk of chunks) {
  12233. chunk.preRender(this.outputOptions, inputBase);
  12234. }
  12235. }
  12236. }
  12237. function getAbsoluteEntryModulePaths(chunks) {
  12238. const absoluteEntryModulePaths = [];
  12239. for (const chunk of chunks) {
  12240. for (const entryModule of chunk.entryModules) {
  12241. if (isAbsolute(entryModule.id)) {
  12242. absoluteEntryModulePaths.push(entryModule.id);
  12243. }
  12244. }
  12245. }
  12246. return absoluteEntryModulePaths;
  12247. }
  12248. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  12249. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  12250. return error({
  12251. code: 'INVALID_OPTION',
  12252. message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
  12253. });
  12254. if (typeof outputOptions.file === 'string')
  12255. return error({
  12256. code: 'INVALID_OPTION',
  12257. message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
  12258. 'To inline dynamic imports, set the "inlineDynamicImports" option.'
  12259. });
  12260. if (outputOptions.sourcemapFile)
  12261. return error({
  12262. code: 'INVALID_OPTION',
  12263. message: '"output.sourcemapFile" is only supported for single-file builds.'
  12264. });
  12265. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  12266. onWarn({
  12267. code: 'INVALID_OPTION',
  12268. message: '"output.amd.id" is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath".'
  12269. });
  12270. }
  12271. function getIncludedModules(modulesById) {
  12272. return [...modulesById.values()].filter(module => module instanceof Module &&
  12273. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  12274. }
  12275. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  12276. const existingAlias = manualChunkAliasByEntry.get(module);
  12277. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  12278. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  12279. }
  12280. manualChunkAliasByEntry.set(module, alias);
  12281. }
  12282. // Reserved word lists for various dialects of the language
  12283. var reservedWords = {
  12284. 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",
  12285. 5: "class enum extends super const export import",
  12286. 6: "enum",
  12287. strict: "implements interface let package private protected public static yield",
  12288. strictBind: "eval arguments"
  12289. };
  12290. // And the keywords
  12291. 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";
  12292. var keywords = {
  12293. 5: ecma5AndLessKeywords,
  12294. "5module": ecma5AndLessKeywords + " export import",
  12295. 6: ecma5AndLessKeywords + " const class extends export import super"
  12296. };
  12297. var keywordRelationalOperator = /^in(stanceof)?$/;
  12298. // ## Character categories
  12299. // Big ugly regular expressions that match characters in the
  12300. // whitespace, identifier, and identifier-start categories. These
  12301. // are only applied when a character is found to actually have a
  12302. // code point above 128.
  12303. // Generated by `bin/generate-identifier-regex.js`.
  12304. 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";
  12305. 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";
  12306. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  12307. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  12308. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  12309. // These are a run-length and offset encoded representation of the
  12310. // >0xffff code points that are a valid part of identifiers. The
  12311. // offset starts at 0x10000, and each pair of numbers represents an
  12312. // offset to the next range, and then a size of the range. They were
  12313. // generated by bin/generate-identifier-regex.js
  12314. // eslint-disable-next-line comma-spacing
  12315. 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];
  12316. // eslint-disable-next-line comma-spacing
  12317. 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];
  12318. // This has a complexity linear to the value of the code. The
  12319. // assumption is that looking up astral identifier characters is
  12320. // rare.
  12321. function isInAstralSet(code, set) {
  12322. var pos = 0x10000;
  12323. for (var i = 0; i < set.length; i += 2) {
  12324. pos += set[i];
  12325. if (pos > code) { return false }
  12326. pos += set[i + 1];
  12327. if (pos >= code) { return true }
  12328. }
  12329. }
  12330. // Test whether a given character code starts an identifier.
  12331. function isIdentifierStart(code, astral) {
  12332. if (code < 65) { return code === 36 }
  12333. if (code < 91) { return true }
  12334. if (code < 97) { return code === 95 }
  12335. if (code < 123) { return true }
  12336. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  12337. if (astral === false) { return false }
  12338. return isInAstralSet(code, astralIdentifierStartCodes)
  12339. }
  12340. // Test whether a given character is part of an identifier.
  12341. function isIdentifierChar(code, astral) {
  12342. if (code < 48) { return code === 36 }
  12343. if (code < 58) { return true }
  12344. if (code < 65) { return false }
  12345. if (code < 91) { return true }
  12346. if (code < 97) { return code === 95 }
  12347. if (code < 123) { return true }
  12348. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  12349. if (astral === false) { return false }
  12350. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  12351. }
  12352. // ## Token types
  12353. // The assignment of fine-grained, information-carrying type objects
  12354. // allows the tokenizer to store the information it has about a
  12355. // token in a way that is very cheap for the parser to look up.
  12356. // All token type variables start with an underscore, to make them
  12357. // easy to recognize.
  12358. // The `beforeExpr` property is used to disambiguate between regular
  12359. // expressions and divisions. It is set on all token types that can
  12360. // be followed by an expression (thus, a slash after them would be a
  12361. // regular expression).
  12362. //
  12363. // The `startsExpr` property is used to check if the token ends a
  12364. // `yield` expression. It is set on all token types that either can
  12365. // directly start an expression (like a quotation mark) or can
  12366. // continue an expression (like the body of a string).
  12367. //
  12368. // `isLoop` marks a keyword as starting a loop, which is important
  12369. // to know when parsing a label, in order to allow or disallow
  12370. // continue jumps to that label.
  12371. var TokenType = function TokenType(label, conf) {
  12372. if ( conf === void 0 ) conf = {};
  12373. this.label = label;
  12374. this.keyword = conf.keyword;
  12375. this.beforeExpr = !!conf.beforeExpr;
  12376. this.startsExpr = !!conf.startsExpr;
  12377. this.isLoop = !!conf.isLoop;
  12378. this.isAssign = !!conf.isAssign;
  12379. this.prefix = !!conf.prefix;
  12380. this.postfix = !!conf.postfix;
  12381. this.binop = conf.binop || null;
  12382. this.updateContext = null;
  12383. };
  12384. function binop(name, prec) {
  12385. return new TokenType(name, {beforeExpr: true, binop: prec})
  12386. }
  12387. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  12388. // Map keyword names to token types.
  12389. var keywords$1 = {};
  12390. // Succinct definitions of keyword token types
  12391. function kw(name, options) {
  12392. if ( options === void 0 ) options = {};
  12393. options.keyword = name;
  12394. return keywords$1[name] = new TokenType(name, options)
  12395. }
  12396. var types = {
  12397. num: new TokenType("num", startsExpr),
  12398. regexp: new TokenType("regexp", startsExpr),
  12399. string: new TokenType("string", startsExpr),
  12400. name: new TokenType("name", startsExpr),
  12401. eof: new TokenType("eof"),
  12402. // Punctuation token types.
  12403. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  12404. bracketR: new TokenType("]"),
  12405. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  12406. braceR: new TokenType("}"),
  12407. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  12408. parenR: new TokenType(")"),
  12409. comma: new TokenType(",", beforeExpr),
  12410. semi: new TokenType(";", beforeExpr),
  12411. colon: new TokenType(":", beforeExpr),
  12412. dot: new TokenType("."),
  12413. question: new TokenType("?", beforeExpr),
  12414. questionDot: new TokenType("?."),
  12415. arrow: new TokenType("=>", beforeExpr),
  12416. template: new TokenType("template"),
  12417. invalidTemplate: new TokenType("invalidTemplate"),
  12418. ellipsis: new TokenType("...", beforeExpr),
  12419. backQuote: new TokenType("`", startsExpr),
  12420. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  12421. // Operators. These carry several kinds of properties to help the
  12422. // parser use them properly (the presence of these properties is
  12423. // what categorizes them as operators).
  12424. //
  12425. // `binop`, when present, specifies that this operator is a binary
  12426. // operator, and will refer to its precedence.
  12427. //
  12428. // `prefix` and `postfix` mark the operator as a prefix or postfix
  12429. // unary operator.
  12430. //
  12431. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  12432. // binary operators with a very low precedence, that should result
  12433. // in AssignmentExpression nodes.
  12434. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  12435. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  12436. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  12437. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  12438. logicalOR: binop("||", 1),
  12439. logicalAND: binop("&&", 2),
  12440. bitwiseOR: binop("|", 3),
  12441. bitwiseXOR: binop("^", 4),
  12442. bitwiseAND: binop("&", 5),
  12443. equality: binop("==/!=/===/!==", 6),
  12444. relational: binop("</>/<=/>=", 7),
  12445. bitShift: binop("<</>>/>>>", 8),
  12446. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  12447. modulo: binop("%", 10),
  12448. star: binop("*", 10),
  12449. slash: binop("/", 10),
  12450. starstar: new TokenType("**", {beforeExpr: true}),
  12451. coalesce: binop("??", 1),
  12452. // Keyword token types.
  12453. _break: kw("break"),
  12454. _case: kw("case", beforeExpr),
  12455. _catch: kw("catch"),
  12456. _continue: kw("continue"),
  12457. _debugger: kw("debugger"),
  12458. _default: kw("default", beforeExpr),
  12459. _do: kw("do", {isLoop: true, beforeExpr: true}),
  12460. _else: kw("else", beforeExpr),
  12461. _finally: kw("finally"),
  12462. _for: kw("for", {isLoop: true}),
  12463. _function: kw("function", startsExpr),
  12464. _if: kw("if"),
  12465. _return: kw("return", beforeExpr),
  12466. _switch: kw("switch"),
  12467. _throw: kw("throw", beforeExpr),
  12468. _try: kw("try"),
  12469. _var: kw("var"),
  12470. _const: kw("const"),
  12471. _while: kw("while", {isLoop: true}),
  12472. _with: kw("with"),
  12473. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  12474. _this: kw("this", startsExpr),
  12475. _super: kw("super", startsExpr),
  12476. _class: kw("class", startsExpr),
  12477. _extends: kw("extends", beforeExpr),
  12478. _export: kw("export"),
  12479. _import: kw("import", startsExpr),
  12480. _null: kw("null", startsExpr),
  12481. _true: kw("true", startsExpr),
  12482. _false: kw("false", startsExpr),
  12483. _in: kw("in", {beforeExpr: true, binop: 7}),
  12484. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  12485. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  12486. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  12487. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  12488. };
  12489. // Matches a whole line break (where CRLF is considered a single
  12490. // line break). Used to count lines.
  12491. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  12492. var lineBreakG = new RegExp(lineBreak.source, "g");
  12493. function isNewLine(code, ecma2019String) {
  12494. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  12495. }
  12496. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  12497. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  12498. var ref = Object.prototype;
  12499. var hasOwnProperty = ref.hasOwnProperty;
  12500. var toString = ref.toString;
  12501. // Checks if an object has a property.
  12502. function has(obj, propName) {
  12503. return hasOwnProperty.call(obj, propName)
  12504. }
  12505. var isArray = Array.isArray || (function (obj) { return (
  12506. toString.call(obj) === "[object Array]"
  12507. ); });
  12508. function wordsRegexp(words) {
  12509. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  12510. }
  12511. // These are used when `options.locations` is on, for the
  12512. // `startLoc` and `endLoc` properties.
  12513. var Position = function Position(line, col) {
  12514. this.line = line;
  12515. this.column = col;
  12516. };
  12517. Position.prototype.offset = function offset (n) {
  12518. return new Position(this.line, this.column + n)
  12519. };
  12520. var SourceLocation = function SourceLocation(p, start, end) {
  12521. this.start = start;
  12522. this.end = end;
  12523. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  12524. };
  12525. // The `getLineInfo` function is mostly useful when the
  12526. // `locations` option is off (for performance reasons) and you
  12527. // want to find the line/column position for a given character
  12528. // offset. `input` should be the code string that the offset refers
  12529. // into.
  12530. function getLineInfo(input, offset) {
  12531. for (var line = 1, cur = 0;;) {
  12532. lineBreakG.lastIndex = cur;
  12533. var match = lineBreakG.exec(input);
  12534. if (match && match.index < offset) {
  12535. ++line;
  12536. cur = match.index + match[0].length;
  12537. } else {
  12538. return new Position(line, offset - cur)
  12539. }
  12540. }
  12541. }
  12542. // A second argument must be given to configure the parser process.
  12543. // These options are recognized (only `ecmaVersion` is required):
  12544. var defaultOptions = {
  12545. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  12546. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  12547. // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version
  12548. // the library supports). This influences support for strict mode,
  12549. // the set of reserved words, and support for new syntax features.
  12550. ecmaVersion: null,
  12551. // `sourceType` indicates the mode the code should be parsed in.
  12552. // Can be either `"script"` or `"module"`. This influences global
  12553. // strict mode and parsing of `import` and `export` declarations.
  12554. sourceType: "script",
  12555. // `onInsertedSemicolon` can be a callback that will be called
  12556. // when a semicolon is automatically inserted. It will be passed
  12557. // the position of the comma as an offset, and if `locations` is
  12558. // enabled, it is given the location as a `{line, column}` object
  12559. // as second argument.
  12560. onInsertedSemicolon: null,
  12561. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  12562. // trailing commas.
  12563. onTrailingComma: null,
  12564. // By default, reserved words are only enforced if ecmaVersion >= 5.
  12565. // Set `allowReserved` to a boolean value to explicitly turn this on
  12566. // an off. When this option has the value "never", reserved words
  12567. // and keywords can also not be used as property names.
  12568. allowReserved: null,
  12569. // When enabled, a return at the top level is not considered an
  12570. // error.
  12571. allowReturnOutsideFunction: false,
  12572. // When enabled, import/export statements are not constrained to
  12573. // appearing at the top of the program.
  12574. allowImportExportEverywhere: false,
  12575. // When enabled, await identifiers are allowed to appear at the top-level scope,
  12576. // but they are still not allowed in non-async functions.
  12577. allowAwaitOutsideFunction: false,
  12578. // When enabled, hashbang directive in the beginning of file
  12579. // is allowed and treated as a line comment.
  12580. allowHashBang: false,
  12581. // When `locations` is on, `loc` properties holding objects with
  12582. // `start` and `end` properties in `{line, column}` form (with
  12583. // line being 1-based and column 0-based) will be attached to the
  12584. // nodes.
  12585. locations: false,
  12586. // A function can be passed as `onToken` option, which will
  12587. // cause Acorn to call that function with object in the same
  12588. // format as tokens returned from `tokenizer().getToken()`. Note
  12589. // that you are not allowed to call the parser from the
  12590. // callback—that will corrupt its internal state.
  12591. onToken: null,
  12592. // A function can be passed as `onComment` option, which will
  12593. // cause Acorn to call that function with `(block, text, start,
  12594. // end)` parameters whenever a comment is skipped. `block` is a
  12595. // boolean indicating whether this is a block (`/* */`) comment,
  12596. // `text` is the content of the comment, and `start` and `end` are
  12597. // character offsets that denote the start and end of the comment.
  12598. // When the `locations` option is on, two more parameters are
  12599. // passed, the full `{line, column}` locations of the start and
  12600. // end of the comments. Note that you are not allowed to call the
  12601. // parser from the callback—that will corrupt its internal state.
  12602. onComment: null,
  12603. // Nodes have their start and end characters offsets recorded in
  12604. // `start` and `end` properties (directly on the node, rather than
  12605. // the `loc` object, which holds line/column data. To also add a
  12606. // [semi-standardized][range] `range` property holding a `[start,
  12607. // end]` array with the same numbers, set the `ranges` option to
  12608. // `true`.
  12609. //
  12610. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  12611. ranges: false,
  12612. // It is possible to parse multiple files into a single AST by
  12613. // passing the tree produced by parsing the first file as
  12614. // `program` option in subsequent parses. This will add the
  12615. // toplevel forms of the parsed file to the `Program` (top) node
  12616. // of an existing parse tree.
  12617. program: null,
  12618. // When `locations` is on, you can pass this to record the source
  12619. // file in every node's `loc` object.
  12620. sourceFile: null,
  12621. // This value, if given, is stored in every node, whether
  12622. // `locations` is on or off.
  12623. directSourceFile: null,
  12624. // When enabled, parenthesized expressions are represented by
  12625. // (non-standard) ParenthesizedExpression nodes
  12626. preserveParens: false
  12627. };
  12628. // Interpret and default an options object
  12629. var warnedAboutEcmaVersion = false;
  12630. function getOptions(opts) {
  12631. var options = {};
  12632. for (var opt in defaultOptions)
  12633. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  12634. if (options.ecmaVersion === "latest") {
  12635. options.ecmaVersion = 1e8;
  12636. } else if (options.ecmaVersion == null) {
  12637. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  12638. warnedAboutEcmaVersion = true;
  12639. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  12640. }
  12641. options.ecmaVersion = 11;
  12642. } else if (options.ecmaVersion >= 2015) {
  12643. options.ecmaVersion -= 2009;
  12644. }
  12645. if (options.allowReserved == null)
  12646. { options.allowReserved = options.ecmaVersion < 5; }
  12647. if (isArray(options.onToken)) {
  12648. var tokens = options.onToken;
  12649. options.onToken = function (token) { return tokens.push(token); };
  12650. }
  12651. if (isArray(options.onComment))
  12652. { options.onComment = pushComment(options, options.onComment); }
  12653. return options
  12654. }
  12655. function pushComment(options, array) {
  12656. return function(block, text, start, end, startLoc, endLoc) {
  12657. var comment = {
  12658. type: block ? "Block" : "Line",
  12659. value: text,
  12660. start: start,
  12661. end: end
  12662. };
  12663. if (options.locations)
  12664. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  12665. if (options.ranges)
  12666. { comment.range = [start, end]; }
  12667. array.push(comment);
  12668. }
  12669. }
  12670. // Each scope gets a bitset that may contain these flags
  12671. var
  12672. SCOPE_TOP = 1,
  12673. SCOPE_FUNCTION = 2,
  12674. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  12675. SCOPE_ASYNC = 4,
  12676. SCOPE_GENERATOR = 8,
  12677. SCOPE_ARROW = 16,
  12678. SCOPE_SIMPLE_CATCH = 32,
  12679. SCOPE_SUPER = 64,
  12680. SCOPE_DIRECT_SUPER = 128;
  12681. function functionFlags(async, generator) {
  12682. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  12683. }
  12684. // Used in checkLVal* and declareName to determine the type of a binding
  12685. var
  12686. BIND_NONE = 0, // Not a binding
  12687. BIND_VAR = 1, // Var-style binding
  12688. BIND_LEXICAL = 2, // Let- or const-style binding
  12689. BIND_FUNCTION = 3, // Function declaration
  12690. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  12691. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  12692. var Parser = function Parser(options, input, startPos) {
  12693. this.options = options = getOptions(options);
  12694. this.sourceFile = options.sourceFile;
  12695. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  12696. var reserved = "";
  12697. if (options.allowReserved !== true) {
  12698. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  12699. if (options.sourceType === "module") { reserved += " await"; }
  12700. }
  12701. this.reservedWords = wordsRegexp(reserved);
  12702. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  12703. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  12704. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  12705. this.input = String(input);
  12706. // Used to signal to callers of `readWord1` whether the word
  12707. // contained any escape sequences. This is needed because words with
  12708. // escape sequences must not be interpreted as keywords.
  12709. this.containsEsc = false;
  12710. // Set up token state
  12711. // The current position of the tokenizer in the input.
  12712. if (startPos) {
  12713. this.pos = startPos;
  12714. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  12715. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  12716. } else {
  12717. this.pos = this.lineStart = 0;
  12718. this.curLine = 1;
  12719. }
  12720. // Properties of the current token:
  12721. // Its type
  12722. this.type = types.eof;
  12723. // For tokens that include more information than their type, the value
  12724. this.value = null;
  12725. // Its start and end offset
  12726. this.start = this.end = this.pos;
  12727. // And, if locations are used, the {line, column} object
  12728. // corresponding to those offsets
  12729. this.startLoc = this.endLoc = this.curPosition();
  12730. // Position information for the previous token
  12731. this.lastTokEndLoc = this.lastTokStartLoc = null;
  12732. this.lastTokStart = this.lastTokEnd = this.pos;
  12733. // The context stack is used to superficially track syntactic
  12734. // context to predict whether a regular expression is allowed in a
  12735. // given position.
  12736. this.context = this.initialContext();
  12737. this.exprAllowed = true;
  12738. // Figure out if it's a module code.
  12739. this.inModule = options.sourceType === "module";
  12740. this.strict = this.inModule || this.strictDirective(this.pos);
  12741. // Used to signify the start of a potential arrow function
  12742. this.potentialArrowAt = -1;
  12743. // Positions to delayed-check that yield/await does not exist in default parameters.
  12744. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  12745. // Labels in scope.
  12746. this.labels = [];
  12747. // Thus-far undefined exports.
  12748. this.undefinedExports = Object.create(null);
  12749. // If enabled, skip leading hashbang line.
  12750. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  12751. { this.skipLineComment(2); }
  12752. // Scope tracking for duplicate variable names (see scope.js)
  12753. this.scopeStack = [];
  12754. this.enterScope(SCOPE_TOP);
  12755. // For RegExp validation
  12756. this.regexpState = null;
  12757. };
  12758. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  12759. Parser.prototype.parse = function parse () {
  12760. var node = this.options.program || this.startNode();
  12761. this.nextToken();
  12762. return this.parseTopLevel(node)
  12763. };
  12764. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  12765. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
  12766. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
  12767. prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
  12768. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  12769. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  12770. prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
  12771. Parser.extend = function extend () {
  12772. var plugins = [], len = arguments.length;
  12773. while ( len-- ) plugins[ len ] = arguments[ len ];
  12774. var cls = this;
  12775. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  12776. return cls
  12777. };
  12778. Parser.parse = function parse (input, options) {
  12779. return new this(options, input).parse()
  12780. };
  12781. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  12782. var parser = new this(options, input, pos);
  12783. parser.nextToken();
  12784. return parser.parseExpression()
  12785. };
  12786. Parser.tokenizer = function tokenizer (input, options) {
  12787. return new this(options, input)
  12788. };
  12789. Object.defineProperties( Parser.prototype, prototypeAccessors );
  12790. var pp = Parser.prototype;
  12791. // ## Parser utilities
  12792. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  12793. pp.strictDirective = function(start) {
  12794. for (;;) {
  12795. // Try to find string literal.
  12796. skipWhiteSpace.lastIndex = start;
  12797. start += skipWhiteSpace.exec(this.input)[0].length;
  12798. var match = literal.exec(this.input.slice(start));
  12799. if (!match) { return false }
  12800. if ((match[1] || match[2]) === "use strict") {
  12801. skipWhiteSpace.lastIndex = start + match[0].length;
  12802. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  12803. var next = this.input.charAt(end);
  12804. return next === ";" || next === "}" ||
  12805. (lineBreak.test(spaceAfter[0]) &&
  12806. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  12807. }
  12808. start += match[0].length;
  12809. // Skip semicolon, if any.
  12810. skipWhiteSpace.lastIndex = start;
  12811. start += skipWhiteSpace.exec(this.input)[0].length;
  12812. if (this.input[start] === ";")
  12813. { start++; }
  12814. }
  12815. };
  12816. // Predicate that tests whether the next token is of the given
  12817. // type, and if yes, consumes it as a side effect.
  12818. pp.eat = function(type) {
  12819. if (this.type === type) {
  12820. this.next();
  12821. return true
  12822. } else {
  12823. return false
  12824. }
  12825. };
  12826. // Tests whether parsed token is a contextual keyword.
  12827. pp.isContextual = function(name) {
  12828. return this.type === types.name && this.value === name && !this.containsEsc
  12829. };
  12830. // Consumes contextual keyword if possible.
  12831. pp.eatContextual = function(name) {
  12832. if (!this.isContextual(name)) { return false }
  12833. this.next();
  12834. return true
  12835. };
  12836. // Asserts that following token is given contextual keyword.
  12837. pp.expectContextual = function(name) {
  12838. if (!this.eatContextual(name)) { this.unexpected(); }
  12839. };
  12840. // Test whether a semicolon can be inserted at the current position.
  12841. pp.canInsertSemicolon = function() {
  12842. return this.type === types.eof ||
  12843. this.type === types.braceR ||
  12844. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  12845. };
  12846. pp.insertSemicolon = function() {
  12847. if (this.canInsertSemicolon()) {
  12848. if (this.options.onInsertedSemicolon)
  12849. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  12850. return true
  12851. }
  12852. };
  12853. // Consume a semicolon, or, failing that, see if we are allowed to
  12854. // pretend that there is a semicolon at this position.
  12855. pp.semicolon = function() {
  12856. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  12857. };
  12858. pp.afterTrailingComma = function(tokType, notNext) {
  12859. if (this.type === tokType) {
  12860. if (this.options.onTrailingComma)
  12861. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  12862. if (!notNext)
  12863. { this.next(); }
  12864. return true
  12865. }
  12866. };
  12867. // Expect a token of a given type. If found, consume it, otherwise,
  12868. // raise an unexpected token error.
  12869. pp.expect = function(type) {
  12870. this.eat(type) || this.unexpected();
  12871. };
  12872. // Raise an unexpected token error.
  12873. pp.unexpected = function(pos) {
  12874. this.raise(pos != null ? pos : this.start, "Unexpected token");
  12875. };
  12876. function DestructuringErrors() {
  12877. this.shorthandAssign =
  12878. this.trailingComma =
  12879. this.parenthesizedAssign =
  12880. this.parenthesizedBind =
  12881. this.doubleProto =
  12882. -1;
  12883. }
  12884. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  12885. if (!refDestructuringErrors) { return }
  12886. if (refDestructuringErrors.trailingComma > -1)
  12887. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  12888. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  12889. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  12890. };
  12891. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  12892. if (!refDestructuringErrors) { return false }
  12893. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  12894. var doubleProto = refDestructuringErrors.doubleProto;
  12895. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  12896. if (shorthandAssign >= 0)
  12897. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  12898. if (doubleProto >= 0)
  12899. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  12900. };
  12901. pp.checkYieldAwaitInDefaultParams = function() {
  12902. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  12903. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  12904. if (this.awaitPos)
  12905. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  12906. };
  12907. pp.isSimpleAssignTarget = function(expr) {
  12908. if (expr.type === "ParenthesizedExpression")
  12909. { return this.isSimpleAssignTarget(expr.expression) }
  12910. return expr.type === "Identifier" || expr.type === "MemberExpression"
  12911. };
  12912. var pp$1 = Parser.prototype;
  12913. // ### Statement parsing
  12914. // Parse a program. Initializes the parser, reads any number of
  12915. // statements, and wraps them in a Program node. Optionally takes a
  12916. // `program` argument. If present, the statements will be appended
  12917. // to its body instead of creating a new node.
  12918. pp$1.parseTopLevel = function(node) {
  12919. var exports = Object.create(null);
  12920. if (!node.body) { node.body = []; }
  12921. while (this.type !== types.eof) {
  12922. var stmt = this.parseStatement(null, true, exports);
  12923. node.body.push(stmt);
  12924. }
  12925. if (this.inModule)
  12926. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  12927. {
  12928. var name = list[i];
  12929. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  12930. } }
  12931. this.adaptDirectivePrologue(node.body);
  12932. this.next();
  12933. node.sourceType = this.options.sourceType;
  12934. return this.finishNode(node, "Program")
  12935. };
  12936. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  12937. pp$1.isLet = function(context) {
  12938. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  12939. skipWhiteSpace.lastIndex = this.pos;
  12940. var skip = skipWhiteSpace.exec(this.input);
  12941. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  12942. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  12943. // Statement) is allowed here. If context is not empty then only a Statement
  12944. // is allowed. However, `let [` is an explicit negative lookahead for
  12945. // ExpressionStatement, so special-case it first.
  12946. if (nextCh === 91) { return true } // '['
  12947. if (context) { return false }
  12948. if (nextCh === 123) { return true } // '{'
  12949. if (isIdentifierStart(nextCh, true)) {
  12950. var pos = next + 1;
  12951. while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
  12952. var ident = this.input.slice(next, pos);
  12953. if (!keywordRelationalOperator.test(ident)) { return true }
  12954. }
  12955. return false
  12956. };
  12957. // check 'async [no LineTerminator here] function'
  12958. // - 'async /*foo*/ function' is OK.
  12959. // - 'async /*\n*/ function' is invalid.
  12960. pp$1.isAsyncFunction = function() {
  12961. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  12962. { return false }
  12963. skipWhiteSpace.lastIndex = this.pos;
  12964. var skip = skipWhiteSpace.exec(this.input);
  12965. var next = this.pos + skip[0].length;
  12966. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  12967. this.input.slice(next, next + 8) === "function" &&
  12968. (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
  12969. };
  12970. // Parse a single statement.
  12971. //
  12972. // If expecting a statement and finding a slash operator, parse a
  12973. // regular expression literal. This is to handle cases like
  12974. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  12975. // does not help.
  12976. pp$1.parseStatement = function(context, topLevel, exports) {
  12977. var starttype = this.type, node = this.startNode(), kind;
  12978. if (this.isLet(context)) {
  12979. starttype = types._var;
  12980. kind = "let";
  12981. }
  12982. // Most types of statements are recognized by the keyword they
  12983. // start with. Many are trivial to parse, some require a bit of
  12984. // complexity.
  12985. switch (starttype) {
  12986. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  12987. case types._debugger: return this.parseDebuggerStatement(node)
  12988. case types._do: return this.parseDoStatement(node)
  12989. case types._for: return this.parseForStatement(node)
  12990. case types._function:
  12991. // Function as sole body of either an if statement or a labeled statement
  12992. // works, but not when it is part of a labeled statement that is the sole
  12993. // body of an if statement.
  12994. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  12995. return this.parseFunctionStatement(node, false, !context)
  12996. case types._class:
  12997. if (context) { this.unexpected(); }
  12998. return this.parseClass(node, true)
  12999. case types._if: return this.parseIfStatement(node)
  13000. case types._return: return this.parseReturnStatement(node)
  13001. case types._switch: return this.parseSwitchStatement(node)
  13002. case types._throw: return this.parseThrowStatement(node)
  13003. case types._try: return this.parseTryStatement(node)
  13004. case types._const: case types._var:
  13005. kind = kind || this.value;
  13006. if (context && kind !== "var") { this.unexpected(); }
  13007. return this.parseVarStatement(node, kind)
  13008. case types._while: return this.parseWhileStatement(node)
  13009. case types._with: return this.parseWithStatement(node)
  13010. case types.braceL: return this.parseBlock(true, node)
  13011. case types.semi: return this.parseEmptyStatement(node)
  13012. case types._export:
  13013. case types._import:
  13014. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  13015. skipWhiteSpace.lastIndex = this.pos;
  13016. var skip = skipWhiteSpace.exec(this.input);
  13017. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13018. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  13019. { return this.parseExpressionStatement(node, this.parseExpression()) }
  13020. }
  13021. if (!this.options.allowImportExportEverywhere) {
  13022. if (!topLevel)
  13023. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  13024. if (!this.inModule)
  13025. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  13026. }
  13027. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  13028. // If the statement does not start with a statement keyword or a
  13029. // brace, it's an ExpressionStatement or LabeledStatement. We
  13030. // simply start parsing an expression, and afterwards, if the
  13031. // next token is a colon and the expression was a simple
  13032. // Identifier node, we switch to interpreting it as a label.
  13033. default:
  13034. if (this.isAsyncFunction()) {
  13035. if (context) { this.unexpected(); }
  13036. this.next();
  13037. return this.parseFunctionStatement(node, true, !context)
  13038. }
  13039. var maybeName = this.value, expr = this.parseExpression();
  13040. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  13041. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  13042. else { return this.parseExpressionStatement(node, expr) }
  13043. }
  13044. };
  13045. pp$1.parseBreakContinueStatement = function(node, keyword) {
  13046. var isBreak = keyword === "break";
  13047. this.next();
  13048. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  13049. else if (this.type !== types.name) { this.unexpected(); }
  13050. else {
  13051. node.label = this.parseIdent();
  13052. this.semicolon();
  13053. }
  13054. // Verify that there is an actual destination to break or
  13055. // continue to.
  13056. var i = 0;
  13057. for (; i < this.labels.length; ++i) {
  13058. var lab = this.labels[i];
  13059. if (node.label == null || lab.name === node.label.name) {
  13060. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  13061. if (node.label && isBreak) { break }
  13062. }
  13063. }
  13064. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  13065. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  13066. };
  13067. pp$1.parseDebuggerStatement = function(node) {
  13068. this.next();
  13069. this.semicolon();
  13070. return this.finishNode(node, "DebuggerStatement")
  13071. };
  13072. pp$1.parseDoStatement = function(node) {
  13073. this.next();
  13074. this.labels.push(loopLabel);
  13075. node.body = this.parseStatement("do");
  13076. this.labels.pop();
  13077. this.expect(types._while);
  13078. node.test = this.parseParenExpression();
  13079. if (this.options.ecmaVersion >= 6)
  13080. { this.eat(types.semi); }
  13081. else
  13082. { this.semicolon(); }
  13083. return this.finishNode(node, "DoWhileStatement")
  13084. };
  13085. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  13086. // loop is non-trivial. Basically, we have to parse the init `var`
  13087. // statement or expression, disallowing the `in` operator (see
  13088. // the second parameter to `parseExpression`), and then check
  13089. // whether the next token is `in` or `of`. When there is no init
  13090. // part (semicolon immediately after the opening parenthesis), it
  13091. // is a regular `for` loop.
  13092. pp$1.parseForStatement = function(node) {
  13093. this.next();
  13094. var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
  13095. this.labels.push(loopLabel);
  13096. this.enterScope(0);
  13097. this.expect(types.parenL);
  13098. if (this.type === types.semi) {
  13099. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13100. return this.parseFor(node, null)
  13101. }
  13102. var isLet = this.isLet();
  13103. if (this.type === types._var || this.type === types._const || isLet) {
  13104. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  13105. this.next();
  13106. this.parseVar(init$1, true, kind);
  13107. this.finishNode(init$1, "VariableDeclaration");
  13108. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  13109. if (this.options.ecmaVersion >= 9) {
  13110. if (this.type === types._in) {
  13111. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13112. } else { node.await = awaitAt > -1; }
  13113. }
  13114. return this.parseForIn(node, init$1)
  13115. }
  13116. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13117. return this.parseFor(node, init$1)
  13118. }
  13119. var refDestructuringErrors = new DestructuringErrors;
  13120. var init = this.parseExpression(true, refDestructuringErrors);
  13121. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  13122. if (this.options.ecmaVersion >= 9) {
  13123. if (this.type === types._in) {
  13124. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13125. } else { node.await = awaitAt > -1; }
  13126. }
  13127. this.toAssignable(init, false, refDestructuringErrors);
  13128. this.checkLValPattern(init);
  13129. return this.parseForIn(node, init)
  13130. } else {
  13131. this.checkExpressionErrors(refDestructuringErrors, true);
  13132. }
  13133. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13134. return this.parseFor(node, init)
  13135. };
  13136. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  13137. this.next();
  13138. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  13139. };
  13140. pp$1.parseIfStatement = function(node) {
  13141. this.next();
  13142. node.test = this.parseParenExpression();
  13143. // allow function declarations in branches, but only in non-strict mode
  13144. node.consequent = this.parseStatement("if");
  13145. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  13146. return this.finishNode(node, "IfStatement")
  13147. };
  13148. pp$1.parseReturnStatement = function(node) {
  13149. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  13150. { this.raise(this.start, "'return' outside of function"); }
  13151. this.next();
  13152. // In `return` (and `break`/`continue`), the keywords with
  13153. // optional arguments, we eagerly look for a semicolon or the
  13154. // possibility to insert one.
  13155. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  13156. else { node.argument = this.parseExpression(); this.semicolon(); }
  13157. return this.finishNode(node, "ReturnStatement")
  13158. };
  13159. pp$1.parseSwitchStatement = function(node) {
  13160. this.next();
  13161. node.discriminant = this.parseParenExpression();
  13162. node.cases = [];
  13163. this.expect(types.braceL);
  13164. this.labels.push(switchLabel);
  13165. this.enterScope(0);
  13166. // Statements under must be grouped (by label) in SwitchCase
  13167. // nodes. `cur` is used to keep the node that we are currently
  13168. // adding statements to.
  13169. var cur;
  13170. for (var sawDefault = false; this.type !== types.braceR;) {
  13171. if (this.type === types._case || this.type === types._default) {
  13172. var isCase = this.type === types._case;
  13173. if (cur) { this.finishNode(cur, "SwitchCase"); }
  13174. node.cases.push(cur = this.startNode());
  13175. cur.consequent = [];
  13176. this.next();
  13177. if (isCase) {
  13178. cur.test = this.parseExpression();
  13179. } else {
  13180. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  13181. sawDefault = true;
  13182. cur.test = null;
  13183. }
  13184. this.expect(types.colon);
  13185. } else {
  13186. if (!cur) { this.unexpected(); }
  13187. cur.consequent.push(this.parseStatement(null));
  13188. }
  13189. }
  13190. this.exitScope();
  13191. if (cur) { this.finishNode(cur, "SwitchCase"); }
  13192. this.next(); // Closing brace
  13193. this.labels.pop();
  13194. return this.finishNode(node, "SwitchStatement")
  13195. };
  13196. pp$1.parseThrowStatement = function(node) {
  13197. this.next();
  13198. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  13199. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  13200. node.argument = this.parseExpression();
  13201. this.semicolon();
  13202. return this.finishNode(node, "ThrowStatement")
  13203. };
  13204. // Reused empty array added for node fields that are always empty.
  13205. var empty = [];
  13206. pp$1.parseTryStatement = function(node) {
  13207. this.next();
  13208. node.block = this.parseBlock();
  13209. node.handler = null;
  13210. if (this.type === types._catch) {
  13211. var clause = this.startNode();
  13212. this.next();
  13213. if (this.eat(types.parenL)) {
  13214. clause.param = this.parseBindingAtom();
  13215. var simple = clause.param.type === "Identifier";
  13216. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  13217. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  13218. this.expect(types.parenR);
  13219. } else {
  13220. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  13221. clause.param = null;
  13222. this.enterScope(0);
  13223. }
  13224. clause.body = this.parseBlock(false);
  13225. this.exitScope();
  13226. node.handler = this.finishNode(clause, "CatchClause");
  13227. }
  13228. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  13229. if (!node.handler && !node.finalizer)
  13230. { this.raise(node.start, "Missing catch or finally clause"); }
  13231. return this.finishNode(node, "TryStatement")
  13232. };
  13233. pp$1.parseVarStatement = function(node, kind) {
  13234. this.next();
  13235. this.parseVar(node, false, kind);
  13236. this.semicolon();
  13237. return this.finishNode(node, "VariableDeclaration")
  13238. };
  13239. pp$1.parseWhileStatement = function(node) {
  13240. this.next();
  13241. node.test = this.parseParenExpression();
  13242. this.labels.push(loopLabel);
  13243. node.body = this.parseStatement("while");
  13244. this.labels.pop();
  13245. return this.finishNode(node, "WhileStatement")
  13246. };
  13247. pp$1.parseWithStatement = function(node) {
  13248. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  13249. this.next();
  13250. node.object = this.parseParenExpression();
  13251. node.body = this.parseStatement("with");
  13252. return this.finishNode(node, "WithStatement")
  13253. };
  13254. pp$1.parseEmptyStatement = function(node) {
  13255. this.next();
  13256. return this.finishNode(node, "EmptyStatement")
  13257. };
  13258. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  13259. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  13260. {
  13261. var label = list[i$1];
  13262. if (label.name === maybeName)
  13263. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  13264. } }
  13265. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  13266. for (var i = this.labels.length - 1; i >= 0; i--) {
  13267. var label$1 = this.labels[i];
  13268. if (label$1.statementStart === node.start) {
  13269. // Update information about previous labels on this node
  13270. label$1.statementStart = this.start;
  13271. label$1.kind = kind;
  13272. } else { break }
  13273. }
  13274. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  13275. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  13276. this.labels.pop();
  13277. node.label = expr;
  13278. return this.finishNode(node, "LabeledStatement")
  13279. };
  13280. pp$1.parseExpressionStatement = function(node, expr) {
  13281. node.expression = expr;
  13282. this.semicolon();
  13283. return this.finishNode(node, "ExpressionStatement")
  13284. };
  13285. // Parse a semicolon-enclosed block of statements, handling `"use
  13286. // strict"` declarations when `allowStrict` is true (used for
  13287. // function bodies).
  13288. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  13289. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  13290. if ( node === void 0 ) node = this.startNode();
  13291. node.body = [];
  13292. this.expect(types.braceL);
  13293. if (createNewLexicalScope) { this.enterScope(0); }
  13294. while (this.type !== types.braceR) {
  13295. var stmt = this.parseStatement(null);
  13296. node.body.push(stmt);
  13297. }
  13298. if (exitStrict) { this.strict = false; }
  13299. this.next();
  13300. if (createNewLexicalScope) { this.exitScope(); }
  13301. return this.finishNode(node, "BlockStatement")
  13302. };
  13303. // Parse a regular `for` loop. The disambiguation code in
  13304. // `parseStatement` will already have parsed the init statement or
  13305. // expression.
  13306. pp$1.parseFor = function(node, init) {
  13307. node.init = init;
  13308. this.expect(types.semi);
  13309. node.test = this.type === types.semi ? null : this.parseExpression();
  13310. this.expect(types.semi);
  13311. node.update = this.type === types.parenR ? null : this.parseExpression();
  13312. this.expect(types.parenR);
  13313. node.body = this.parseStatement("for");
  13314. this.exitScope();
  13315. this.labels.pop();
  13316. return this.finishNode(node, "ForStatement")
  13317. };
  13318. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  13319. // same from parser's perspective.
  13320. pp$1.parseForIn = function(node, init) {
  13321. var isForIn = this.type === types._in;
  13322. this.next();
  13323. if (
  13324. init.type === "VariableDeclaration" &&
  13325. init.declarations[0].init != null &&
  13326. (
  13327. !isForIn ||
  13328. this.options.ecmaVersion < 8 ||
  13329. this.strict ||
  13330. init.kind !== "var" ||
  13331. init.declarations[0].id.type !== "Identifier"
  13332. )
  13333. ) {
  13334. this.raise(
  13335. init.start,
  13336. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  13337. );
  13338. }
  13339. node.left = init;
  13340. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  13341. this.expect(types.parenR);
  13342. node.body = this.parseStatement("for");
  13343. this.exitScope();
  13344. this.labels.pop();
  13345. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  13346. };
  13347. // Parse a list of variable declarations.
  13348. pp$1.parseVar = function(node, isFor, kind) {
  13349. node.declarations = [];
  13350. node.kind = kind;
  13351. for (;;) {
  13352. var decl = this.startNode();
  13353. this.parseVarId(decl, kind);
  13354. if (this.eat(types.eq)) {
  13355. decl.init = this.parseMaybeAssign(isFor);
  13356. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  13357. this.unexpected();
  13358. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  13359. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  13360. } else {
  13361. decl.init = null;
  13362. }
  13363. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  13364. if (!this.eat(types.comma)) { break }
  13365. }
  13366. return node
  13367. };
  13368. pp$1.parseVarId = function(decl, kind) {
  13369. decl.id = this.parseBindingAtom();
  13370. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  13371. };
  13372. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  13373. // Parse a function declaration or literal (depending on the
  13374. // `statement & FUNC_STATEMENT`).
  13375. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  13376. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  13377. this.initFunction(node);
  13378. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  13379. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  13380. { this.unexpected(); }
  13381. node.generator = this.eat(types.star);
  13382. }
  13383. if (this.options.ecmaVersion >= 8)
  13384. { node.async = !!isAsync; }
  13385. if (statement & FUNC_STATEMENT) {
  13386. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  13387. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  13388. // If it is a regular function declaration in sloppy mode, then it is
  13389. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  13390. // mode depends on properties of the current scope (see
  13391. // treatFunctionsAsVar).
  13392. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  13393. }
  13394. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  13395. this.yieldPos = 0;
  13396. this.awaitPos = 0;
  13397. this.awaitIdentPos = 0;
  13398. this.enterScope(functionFlags(node.async, node.generator));
  13399. if (!(statement & FUNC_STATEMENT))
  13400. { node.id = this.type === types.name ? this.parseIdent() : null; }
  13401. this.parseFunctionParams(node);
  13402. this.parseFunctionBody(node, allowExpressionBody, false);
  13403. this.yieldPos = oldYieldPos;
  13404. this.awaitPos = oldAwaitPos;
  13405. this.awaitIdentPos = oldAwaitIdentPos;
  13406. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  13407. };
  13408. pp$1.parseFunctionParams = function(node) {
  13409. this.expect(types.parenL);
  13410. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  13411. this.checkYieldAwaitInDefaultParams();
  13412. };
  13413. // Parse a class declaration or literal (depending on the
  13414. // `isStatement` parameter).
  13415. pp$1.parseClass = function(node, isStatement) {
  13416. this.next();
  13417. // ecma-262 14.6 Class Definitions
  13418. // A class definition is always strict mode code.
  13419. var oldStrict = this.strict;
  13420. this.strict = true;
  13421. this.parseClassId(node, isStatement);
  13422. this.parseClassSuper(node);
  13423. var classBody = this.startNode();
  13424. var hadConstructor = false;
  13425. classBody.body = [];
  13426. this.expect(types.braceL);
  13427. while (this.type !== types.braceR) {
  13428. var element = this.parseClassElement(node.superClass !== null);
  13429. if (element) {
  13430. classBody.body.push(element);
  13431. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  13432. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  13433. hadConstructor = true;
  13434. }
  13435. }
  13436. }
  13437. this.strict = oldStrict;
  13438. this.next();
  13439. node.body = this.finishNode(classBody, "ClassBody");
  13440. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  13441. };
  13442. pp$1.parseClassElement = function(constructorAllowsSuper) {
  13443. var this$1 = this;
  13444. if (this.eat(types.semi)) { return null }
  13445. var method = this.startNode();
  13446. var tryContextual = function (k, noLineBreak) {
  13447. if ( noLineBreak === void 0 ) noLineBreak = false;
  13448. var start = this$1.start, startLoc = this$1.startLoc;
  13449. if (!this$1.eatContextual(k)) { return false }
  13450. if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
  13451. if (method.key) { this$1.unexpected(); }
  13452. method.computed = false;
  13453. method.key = this$1.startNodeAt(start, startLoc);
  13454. method.key.name = k;
  13455. this$1.finishNode(method.key, "Identifier");
  13456. return false
  13457. };
  13458. method.kind = "method";
  13459. method.static = tryContextual("static");
  13460. var isGenerator = this.eat(types.star);
  13461. var isAsync = false;
  13462. if (!isGenerator) {
  13463. if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
  13464. isAsync = true;
  13465. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  13466. } else if (tryContextual("get")) {
  13467. method.kind = "get";
  13468. } else if (tryContextual("set")) {
  13469. method.kind = "set";
  13470. }
  13471. }
  13472. if (!method.key) { this.parsePropertyName(method); }
  13473. var key = method.key;
  13474. var allowsDirectSuper = false;
  13475. if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
  13476. key.type === "Literal" && key.value === "constructor")) {
  13477. if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
  13478. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  13479. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  13480. method.kind = "constructor";
  13481. allowsDirectSuper = constructorAllowsSuper;
  13482. } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
  13483. this.raise(key.start, "Classes may not have a static property named prototype");
  13484. }
  13485. this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
  13486. if (method.kind === "get" && method.value.params.length !== 0)
  13487. { this.raiseRecoverable(method.value.start, "getter should have no params"); }
  13488. if (method.kind === "set" && method.value.params.length !== 1)
  13489. { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
  13490. if (method.kind === "set" && method.value.params[0].type === "RestElement")
  13491. { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
  13492. return method
  13493. };
  13494. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  13495. method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  13496. return this.finishNode(method, "MethodDefinition")
  13497. };
  13498. pp$1.parseClassId = function(node, isStatement) {
  13499. if (this.type === types.name) {
  13500. node.id = this.parseIdent();
  13501. if (isStatement)
  13502. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  13503. } else {
  13504. if (isStatement === true)
  13505. { this.unexpected(); }
  13506. node.id = null;
  13507. }
  13508. };
  13509. pp$1.parseClassSuper = function(node) {
  13510. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  13511. };
  13512. // Parses module export declaration.
  13513. pp$1.parseExport = function(node, exports) {
  13514. this.next();
  13515. // export * from '...'
  13516. if (this.eat(types.star)) {
  13517. if (this.options.ecmaVersion >= 11) {
  13518. if (this.eatContextual("as")) {
  13519. node.exported = this.parseIdent(true);
  13520. this.checkExport(exports, node.exported.name, this.lastTokStart);
  13521. } else {
  13522. node.exported = null;
  13523. }
  13524. }
  13525. this.expectContextual("from");
  13526. if (this.type !== types.string) { this.unexpected(); }
  13527. node.source = this.parseExprAtom();
  13528. this.semicolon();
  13529. return this.finishNode(node, "ExportAllDeclaration")
  13530. }
  13531. if (this.eat(types._default)) { // export default ...
  13532. this.checkExport(exports, "default", this.lastTokStart);
  13533. var isAsync;
  13534. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  13535. var fNode = this.startNode();
  13536. this.next();
  13537. if (isAsync) { this.next(); }
  13538. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  13539. } else if (this.type === types._class) {
  13540. var cNode = this.startNode();
  13541. node.declaration = this.parseClass(cNode, "nullableID");
  13542. } else {
  13543. node.declaration = this.parseMaybeAssign();
  13544. this.semicolon();
  13545. }
  13546. return this.finishNode(node, "ExportDefaultDeclaration")
  13547. }
  13548. // export var|const|let|function|class ...
  13549. if (this.shouldParseExportStatement()) {
  13550. node.declaration = this.parseStatement(null);
  13551. if (node.declaration.type === "VariableDeclaration")
  13552. { this.checkVariableExport(exports, node.declaration.declarations); }
  13553. else
  13554. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  13555. node.specifiers = [];
  13556. node.source = null;
  13557. } else { // export { x, y as z } [from '...']
  13558. node.declaration = null;
  13559. node.specifiers = this.parseExportSpecifiers(exports);
  13560. if (this.eatContextual("from")) {
  13561. if (this.type !== types.string) { this.unexpected(); }
  13562. node.source = this.parseExprAtom();
  13563. } else {
  13564. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  13565. // check for keywords used as local names
  13566. var spec = list[i];
  13567. this.checkUnreserved(spec.local);
  13568. // check if export is defined
  13569. this.checkLocalExport(spec.local);
  13570. }
  13571. node.source = null;
  13572. }
  13573. this.semicolon();
  13574. }
  13575. return this.finishNode(node, "ExportNamedDeclaration")
  13576. };
  13577. pp$1.checkExport = function(exports, name, pos) {
  13578. if (!exports) { return }
  13579. if (has(exports, name))
  13580. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  13581. exports[name] = true;
  13582. };
  13583. pp$1.checkPatternExport = function(exports, pat) {
  13584. var type = pat.type;
  13585. if (type === "Identifier")
  13586. { this.checkExport(exports, pat.name, pat.start); }
  13587. else if (type === "ObjectPattern")
  13588. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  13589. {
  13590. var prop = list[i];
  13591. this.checkPatternExport(exports, prop);
  13592. } }
  13593. else if (type === "ArrayPattern")
  13594. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  13595. var elt = list$1[i$1];
  13596. if (elt) { this.checkPatternExport(exports, elt); }
  13597. } }
  13598. else if (type === "Property")
  13599. { this.checkPatternExport(exports, pat.value); }
  13600. else if (type === "AssignmentPattern")
  13601. { this.checkPatternExport(exports, pat.left); }
  13602. else if (type === "RestElement")
  13603. { this.checkPatternExport(exports, pat.argument); }
  13604. else if (type === "ParenthesizedExpression")
  13605. { this.checkPatternExport(exports, pat.expression); }
  13606. };
  13607. pp$1.checkVariableExport = function(exports, decls) {
  13608. if (!exports) { return }
  13609. for (var i = 0, list = decls; i < list.length; i += 1)
  13610. {
  13611. var decl = list[i];
  13612. this.checkPatternExport(exports, decl.id);
  13613. }
  13614. };
  13615. pp$1.shouldParseExportStatement = function() {
  13616. return this.type.keyword === "var" ||
  13617. this.type.keyword === "const" ||
  13618. this.type.keyword === "class" ||
  13619. this.type.keyword === "function" ||
  13620. this.isLet() ||
  13621. this.isAsyncFunction()
  13622. };
  13623. // Parses a comma-separated list of module exports.
  13624. pp$1.parseExportSpecifiers = function(exports) {
  13625. var nodes = [], first = true;
  13626. // export { x, y as z } [from '...']
  13627. this.expect(types.braceL);
  13628. while (!this.eat(types.braceR)) {
  13629. if (!first) {
  13630. this.expect(types.comma);
  13631. if (this.afterTrailingComma(types.braceR)) { break }
  13632. } else { first = false; }
  13633. var node = this.startNode();
  13634. node.local = this.parseIdent(true);
  13635. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  13636. this.checkExport(exports, node.exported.name, node.exported.start);
  13637. nodes.push(this.finishNode(node, "ExportSpecifier"));
  13638. }
  13639. return nodes
  13640. };
  13641. // Parses import declaration.
  13642. pp$1.parseImport = function(node) {
  13643. this.next();
  13644. // import '...'
  13645. if (this.type === types.string) {
  13646. node.specifiers = empty;
  13647. node.source = this.parseExprAtom();
  13648. } else {
  13649. node.specifiers = this.parseImportSpecifiers();
  13650. this.expectContextual("from");
  13651. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  13652. }
  13653. this.semicolon();
  13654. return this.finishNode(node, "ImportDeclaration")
  13655. };
  13656. // Parses a comma-separated list of module imports.
  13657. pp$1.parseImportSpecifiers = function() {
  13658. var nodes = [], first = true;
  13659. if (this.type === types.name) {
  13660. // import defaultObj, { x, y as z } from '...'
  13661. var node = this.startNode();
  13662. node.local = this.parseIdent();
  13663. this.checkLValSimple(node.local, BIND_LEXICAL);
  13664. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  13665. if (!this.eat(types.comma)) { return nodes }
  13666. }
  13667. if (this.type === types.star) {
  13668. var node$1 = this.startNode();
  13669. this.next();
  13670. this.expectContextual("as");
  13671. node$1.local = this.parseIdent();
  13672. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  13673. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  13674. return nodes
  13675. }
  13676. this.expect(types.braceL);
  13677. while (!this.eat(types.braceR)) {
  13678. if (!first) {
  13679. this.expect(types.comma);
  13680. if (this.afterTrailingComma(types.braceR)) { break }
  13681. } else { first = false; }
  13682. var node$2 = this.startNode();
  13683. node$2.imported = this.parseIdent(true);
  13684. if (this.eatContextual("as")) {
  13685. node$2.local = this.parseIdent();
  13686. } else {
  13687. this.checkUnreserved(node$2.imported);
  13688. node$2.local = node$2.imported;
  13689. }
  13690. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  13691. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  13692. }
  13693. return nodes
  13694. };
  13695. // Set `ExpressionStatement#directive` property for directive prologues.
  13696. pp$1.adaptDirectivePrologue = function(statements) {
  13697. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  13698. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  13699. }
  13700. };
  13701. pp$1.isDirectiveCandidate = function(statement) {
  13702. return (
  13703. statement.type === "ExpressionStatement" &&
  13704. statement.expression.type === "Literal" &&
  13705. typeof statement.expression.value === "string" &&
  13706. // Reject parenthesized strings.
  13707. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  13708. )
  13709. };
  13710. var pp$2 = Parser.prototype;
  13711. // Convert existing expression atom to assignable pattern
  13712. // if possible.
  13713. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  13714. if (this.options.ecmaVersion >= 6 && node) {
  13715. switch (node.type) {
  13716. case "Identifier":
  13717. if (this.inAsync && node.name === "await")
  13718. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  13719. break
  13720. case "ObjectPattern":
  13721. case "ArrayPattern":
  13722. case "AssignmentPattern":
  13723. case "RestElement":
  13724. break
  13725. case "ObjectExpression":
  13726. node.type = "ObjectPattern";
  13727. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13728. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  13729. var prop = list[i];
  13730. this.toAssignable(prop, isBinding);
  13731. // Early error:
  13732. // AssignmentRestProperty[Yield, Await] :
  13733. // `...` DestructuringAssignmentTarget[Yield, Await]
  13734. //
  13735. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  13736. if (
  13737. prop.type === "RestElement" &&
  13738. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  13739. ) {
  13740. this.raise(prop.argument.start, "Unexpected token");
  13741. }
  13742. }
  13743. break
  13744. case "Property":
  13745. // AssignmentProperty has type === "Property"
  13746. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  13747. this.toAssignable(node.value, isBinding);
  13748. break
  13749. case "ArrayExpression":
  13750. node.type = "ArrayPattern";
  13751. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13752. this.toAssignableList(node.elements, isBinding);
  13753. break
  13754. case "SpreadElement":
  13755. node.type = "RestElement";
  13756. this.toAssignable(node.argument, isBinding);
  13757. if (node.argument.type === "AssignmentPattern")
  13758. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  13759. break
  13760. case "AssignmentExpression":
  13761. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  13762. node.type = "AssignmentPattern";
  13763. delete node.operator;
  13764. this.toAssignable(node.left, isBinding);
  13765. break
  13766. case "ParenthesizedExpression":
  13767. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  13768. break
  13769. case "ChainExpression":
  13770. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  13771. break
  13772. case "MemberExpression":
  13773. if (!isBinding) { break }
  13774. default:
  13775. this.raise(node.start, "Assigning to rvalue");
  13776. }
  13777. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13778. return node
  13779. };
  13780. // Convert list of expression atoms to binding list.
  13781. pp$2.toAssignableList = function(exprList, isBinding) {
  13782. var end = exprList.length;
  13783. for (var i = 0; i < end; i++) {
  13784. var elt = exprList[i];
  13785. if (elt) { this.toAssignable(elt, isBinding); }
  13786. }
  13787. if (end) {
  13788. var last = exprList[end - 1];
  13789. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  13790. { this.unexpected(last.argument.start); }
  13791. }
  13792. return exprList
  13793. };
  13794. // Parses spread element.
  13795. pp$2.parseSpread = function(refDestructuringErrors) {
  13796. var node = this.startNode();
  13797. this.next();
  13798. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  13799. return this.finishNode(node, "SpreadElement")
  13800. };
  13801. pp$2.parseRestBinding = function() {
  13802. var node = this.startNode();
  13803. this.next();
  13804. // RestElement inside of a function parameter must be an identifier
  13805. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  13806. { this.unexpected(); }
  13807. node.argument = this.parseBindingAtom();
  13808. return this.finishNode(node, "RestElement")
  13809. };
  13810. // Parses lvalue (assignable) atom.
  13811. pp$2.parseBindingAtom = function() {
  13812. if (this.options.ecmaVersion >= 6) {
  13813. switch (this.type) {
  13814. case types.bracketL:
  13815. var node = this.startNode();
  13816. this.next();
  13817. node.elements = this.parseBindingList(types.bracketR, true, true);
  13818. return this.finishNode(node, "ArrayPattern")
  13819. case types.braceL:
  13820. return this.parseObj(true)
  13821. }
  13822. }
  13823. return this.parseIdent()
  13824. };
  13825. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  13826. var elts = [], first = true;
  13827. while (!this.eat(close)) {
  13828. if (first) { first = false; }
  13829. else { this.expect(types.comma); }
  13830. if (allowEmpty && this.type === types.comma) {
  13831. elts.push(null);
  13832. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  13833. break
  13834. } else if (this.type === types.ellipsis) {
  13835. var rest = this.parseRestBinding();
  13836. this.parseBindingListItem(rest);
  13837. elts.push(rest);
  13838. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  13839. this.expect(close);
  13840. break
  13841. } else {
  13842. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  13843. this.parseBindingListItem(elem);
  13844. elts.push(elem);
  13845. }
  13846. }
  13847. return elts
  13848. };
  13849. pp$2.parseBindingListItem = function(param) {
  13850. return param
  13851. };
  13852. // Parses assignment pattern around given atom if possible.
  13853. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  13854. left = left || this.parseBindingAtom();
  13855. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  13856. var node = this.startNodeAt(startPos, startLoc);
  13857. node.left = left;
  13858. node.right = this.parseMaybeAssign();
  13859. return this.finishNode(node, "AssignmentPattern")
  13860. };
  13861. // The following three functions all verify that a node is an lvalue —
  13862. // something that can be bound, or assigned to. In order to do so, they perform
  13863. // a variety of checks:
  13864. //
  13865. // - Check that none of the bound/assigned-to identifiers are reserved words.
  13866. // - Record name declarations for bindings in the appropriate scope.
  13867. // - Check duplicate argument names, if checkClashes is set.
  13868. //
  13869. // If a complex binding pattern is encountered (e.g., object and array
  13870. // destructuring), the entire pattern is recursively checked.
  13871. //
  13872. // There are three versions of checkLVal*() appropriate for different
  13873. // circumstances:
  13874. //
  13875. // - checkLValSimple() shall be used if the syntactic construct supports
  13876. // nothing other than identifiers and member expressions. Parenthesized
  13877. // expressions are also correctly handled. This is generally appropriate for
  13878. // constructs for which the spec says
  13879. //
  13880. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  13881. // > simple.
  13882. //
  13883. // It is also appropriate for checking if an identifier is valid and not
  13884. // defined elsewhere, like import declarations or function/class identifiers.
  13885. //
  13886. // Examples where this is used include:
  13887. // a += …;
  13888. // import a from '…';
  13889. // where a is the node to be checked.
  13890. //
  13891. // - checkLValPattern() shall be used if the syntactic construct supports
  13892. // anything checkLValSimple() supports, as well as object and array
  13893. // destructuring patterns. This is generally appropriate for constructs for
  13894. // which the spec says
  13895. //
  13896. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  13897. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  13898. // > simple.
  13899. //
  13900. // Examples where this is used include:
  13901. // (a = …);
  13902. // const a = …;
  13903. // try { … } catch (a) { … }
  13904. // where a is the node to be checked.
  13905. //
  13906. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  13907. // anything checkLValPattern() supports, as well as default assignment
  13908. // patterns, rest elements, and other constructs that may appear within an
  13909. // object or array destructuring pattern.
  13910. //
  13911. // As a special case, function parameters also use checkLValInnerPattern(),
  13912. // as they also support defaults and rest constructs.
  13913. //
  13914. // These functions deliberately support both assignment and binding constructs,
  13915. // as the logic for both is exceedingly similar. If the node is the target of
  13916. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  13917. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  13918. // BIND_LEXICAL.
  13919. //
  13920. // If the function is called with a non-BIND_NONE bindingType, then
  13921. // additionally a checkClashes object may be specified to allow checking for
  13922. // duplicate argument names. checkClashes is ignored if the provided construct
  13923. // is an assignment (i.e., bindingType is BIND_NONE).
  13924. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  13925. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13926. var isBind = bindingType !== BIND_NONE;
  13927. switch (expr.type) {
  13928. case "Identifier":
  13929. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  13930. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  13931. if (isBind) {
  13932. if (bindingType === BIND_LEXICAL && expr.name === "let")
  13933. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  13934. if (checkClashes) {
  13935. if (has(checkClashes, expr.name))
  13936. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  13937. checkClashes[expr.name] = true;
  13938. }
  13939. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  13940. }
  13941. break
  13942. case "ChainExpression":
  13943. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  13944. break
  13945. case "MemberExpression":
  13946. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  13947. break
  13948. case "ParenthesizedExpression":
  13949. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  13950. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  13951. default:
  13952. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  13953. }
  13954. };
  13955. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  13956. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13957. switch (expr.type) {
  13958. case "ObjectPattern":
  13959. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  13960. var prop = list[i];
  13961. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  13962. }
  13963. break
  13964. case "ArrayPattern":
  13965. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  13966. var elem = list$1[i$1];
  13967. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  13968. }
  13969. break
  13970. default:
  13971. this.checkLValSimple(expr, bindingType, checkClashes);
  13972. }
  13973. };
  13974. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  13975. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13976. switch (expr.type) {
  13977. case "Property":
  13978. // AssignmentProperty has type === "Property"
  13979. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  13980. break
  13981. case "AssignmentPattern":
  13982. this.checkLValPattern(expr.left, bindingType, checkClashes);
  13983. break
  13984. case "RestElement":
  13985. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  13986. break
  13987. default:
  13988. this.checkLValPattern(expr, bindingType, checkClashes);
  13989. }
  13990. };
  13991. // A recursive descent parser operates by defining functions for all
  13992. var pp$3 = Parser.prototype;
  13993. // Check if property name clashes with already added.
  13994. // Object/class getters and setters are not allowed to clash —
  13995. // either with each other or with an init property — and in
  13996. // strict mode, init properties are also not allowed to be repeated.
  13997. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  13998. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  13999. { return }
  14000. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  14001. { return }
  14002. var key = prop.key;
  14003. var name;
  14004. switch (key.type) {
  14005. case "Identifier": name = key.name; break
  14006. case "Literal": name = String(key.value); break
  14007. default: return
  14008. }
  14009. var kind = prop.kind;
  14010. if (this.options.ecmaVersion >= 6) {
  14011. if (name === "__proto__" && kind === "init") {
  14012. if (propHash.proto) {
  14013. if (refDestructuringErrors) {
  14014. if (refDestructuringErrors.doubleProto < 0)
  14015. { refDestructuringErrors.doubleProto = key.start; }
  14016. // Backwards-compat kludge. Can be removed in version 6.0
  14017. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  14018. }
  14019. propHash.proto = true;
  14020. }
  14021. return
  14022. }
  14023. name = "$" + name;
  14024. var other = propHash[name];
  14025. if (other) {
  14026. var redefinition;
  14027. if (kind === "init") {
  14028. redefinition = this.strict && other.init || other.get || other.set;
  14029. } else {
  14030. redefinition = other.init || other[kind];
  14031. }
  14032. if (redefinition)
  14033. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  14034. } else {
  14035. other = propHash[name] = {
  14036. init: false,
  14037. get: false,
  14038. set: false
  14039. };
  14040. }
  14041. other[kind] = true;
  14042. };
  14043. // ### Expression parsing
  14044. // These nest, from the most general expression type at the top to
  14045. // 'atomic', nondivisible expression types at the bottom. Most of
  14046. // the functions will simply let the function(s) below them parse,
  14047. // and, *if* the syntactic construct they handle is present, wrap
  14048. // the AST node that the inner parser gave them in another node.
  14049. // Parse a full expression. The optional arguments are used to
  14050. // forbid the `in` operator (in for loops initalization expressions)
  14051. // and provide reference for storing '=' operator inside shorthand
  14052. // property assignment in contexts where both object expression
  14053. // and object pattern might appear (so it's possible to raise
  14054. // delayed syntax error at correct position).
  14055. pp$3.parseExpression = function(noIn, refDestructuringErrors) {
  14056. var startPos = this.start, startLoc = this.startLoc;
  14057. var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
  14058. if (this.type === types.comma) {
  14059. var node = this.startNodeAt(startPos, startLoc);
  14060. node.expressions = [expr];
  14061. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
  14062. return this.finishNode(node, "SequenceExpression")
  14063. }
  14064. return expr
  14065. };
  14066. // Parse an assignment expression. This includes applications of
  14067. // operators like `+=`.
  14068. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  14069. if (this.isContextual("yield")) {
  14070. if (this.inGenerator) { return this.parseYield(noIn) }
  14071. // The tokenizer will assume an expression is allowed after
  14072. // `yield`, but this isn't that kind of yield
  14073. else { this.exprAllowed = false; }
  14074. }
  14075. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  14076. if (refDestructuringErrors) {
  14077. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  14078. oldTrailingComma = refDestructuringErrors.trailingComma;
  14079. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  14080. } else {
  14081. refDestructuringErrors = new DestructuringErrors;
  14082. ownDestructuringErrors = true;
  14083. }
  14084. var startPos = this.start, startLoc = this.startLoc;
  14085. if (this.type === types.parenL || this.type === types.name)
  14086. { this.potentialArrowAt = this.start; }
  14087. var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
  14088. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  14089. if (this.type.isAssign) {
  14090. var node = this.startNodeAt(startPos, startLoc);
  14091. node.operator = this.value;
  14092. if (this.type === types.eq)
  14093. { left = this.toAssignable(left, false, refDestructuringErrors); }
  14094. if (!ownDestructuringErrors) {
  14095. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  14096. }
  14097. if (refDestructuringErrors.shorthandAssign >= left.start)
  14098. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  14099. if (this.type === types.eq)
  14100. { this.checkLValPattern(left); }
  14101. else
  14102. { this.checkLValSimple(left); }
  14103. node.left = left;
  14104. this.next();
  14105. node.right = this.parseMaybeAssign(noIn);
  14106. return this.finishNode(node, "AssignmentExpression")
  14107. } else {
  14108. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  14109. }
  14110. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  14111. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  14112. return left
  14113. };
  14114. // Parse a ternary conditional (`?:`) operator.
  14115. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  14116. var startPos = this.start, startLoc = this.startLoc;
  14117. var expr = this.parseExprOps(noIn, refDestructuringErrors);
  14118. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  14119. if (this.eat(types.question)) {
  14120. var node = this.startNodeAt(startPos, startLoc);
  14121. node.test = expr;
  14122. node.consequent = this.parseMaybeAssign();
  14123. this.expect(types.colon);
  14124. node.alternate = this.parseMaybeAssign(noIn);
  14125. return this.finishNode(node, "ConditionalExpression")
  14126. }
  14127. return expr
  14128. };
  14129. // Start the precedence parser.
  14130. pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
  14131. var startPos = this.start, startLoc = this.startLoc;
  14132. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  14133. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  14134. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
  14135. };
  14136. // Parse binary operators with the operator precedence parsing
  14137. // algorithm. `left` is the left-hand side of the operator.
  14138. // `minPrec` provides context that allows the function to stop and
  14139. // defer further parser to one of its callers when it encounters an
  14140. // operator that has a lower precedence than the set it is parsing.
  14141. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  14142. var prec = this.type.binop;
  14143. if (prec != null && (!noIn || this.type !== types._in)) {
  14144. if (prec > minPrec) {
  14145. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  14146. var coalesce = this.type === types.coalesce;
  14147. if (coalesce) {
  14148. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  14149. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  14150. prec = types.logicalAND.binop;
  14151. }
  14152. var op = this.value;
  14153. this.next();
  14154. var startPos = this.start, startLoc = this.startLoc;
  14155. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
  14156. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  14157. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  14158. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  14159. }
  14160. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
  14161. }
  14162. }
  14163. return left
  14164. };
  14165. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  14166. var node = this.startNodeAt(startPos, startLoc);
  14167. node.left = left;
  14168. node.operator = op;
  14169. node.right = right;
  14170. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  14171. };
  14172. // Parse unary operators, both prefix and postfix.
  14173. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  14174. var startPos = this.start, startLoc = this.startLoc, expr;
  14175. if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
  14176. expr = this.parseAwait();
  14177. sawUnary = true;
  14178. } else if (this.type.prefix) {
  14179. var node = this.startNode(), update = this.type === types.incDec;
  14180. node.operator = this.value;
  14181. node.prefix = true;
  14182. this.next();
  14183. node.argument = this.parseMaybeUnary(null, true);
  14184. this.checkExpressionErrors(refDestructuringErrors, true);
  14185. if (update) { this.checkLValSimple(node.argument); }
  14186. else if (this.strict && node.operator === "delete" &&
  14187. node.argument.type === "Identifier")
  14188. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  14189. else { sawUnary = true; }
  14190. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  14191. } else {
  14192. expr = this.parseExprSubscripts(refDestructuringErrors);
  14193. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  14194. while (this.type.postfix && !this.canInsertSemicolon()) {
  14195. var node$1 = this.startNodeAt(startPos, startLoc);
  14196. node$1.operator = this.value;
  14197. node$1.prefix = false;
  14198. node$1.argument = expr;
  14199. this.checkLValSimple(expr);
  14200. this.next();
  14201. expr = this.finishNode(node$1, "UpdateExpression");
  14202. }
  14203. }
  14204. if (!sawUnary && this.eat(types.starstar))
  14205. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  14206. else
  14207. { return expr }
  14208. };
  14209. // Parse call, dot, and `[]`-subscript expressions.
  14210. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  14211. var startPos = this.start, startLoc = this.startLoc;
  14212. var expr = this.parseExprAtom(refDestructuringErrors);
  14213. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  14214. { return expr }
  14215. var result = this.parseSubscripts(expr, startPos, startLoc);
  14216. if (refDestructuringErrors && result.type === "MemberExpression") {
  14217. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  14218. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  14219. }
  14220. return result
  14221. };
  14222. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  14223. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  14224. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  14225. this.potentialArrowAt === base.start;
  14226. var optionalChained = false;
  14227. while (true) {
  14228. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  14229. if (element.optional) { optionalChained = true; }
  14230. if (element === base || element.type === "ArrowFunctionExpression") {
  14231. if (optionalChained) {
  14232. var chainNode = this.startNodeAt(startPos, startLoc);
  14233. chainNode.expression = element;
  14234. element = this.finishNode(chainNode, "ChainExpression");
  14235. }
  14236. return element
  14237. }
  14238. base = element;
  14239. }
  14240. };
  14241. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  14242. var optionalSupported = this.options.ecmaVersion >= 11;
  14243. var optional = optionalSupported && this.eat(types.questionDot);
  14244. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  14245. var computed = this.eat(types.bracketL);
  14246. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  14247. var node = this.startNodeAt(startPos, startLoc);
  14248. node.object = base;
  14249. node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
  14250. node.computed = !!computed;
  14251. if (computed) { this.expect(types.bracketR); }
  14252. if (optionalSupported) {
  14253. node.optional = optional;
  14254. }
  14255. base = this.finishNode(node, "MemberExpression");
  14256. } else if (!noCalls && this.eat(types.parenL)) {
  14257. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14258. this.yieldPos = 0;
  14259. this.awaitPos = 0;
  14260. this.awaitIdentPos = 0;
  14261. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  14262. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  14263. this.checkPatternErrors(refDestructuringErrors, false);
  14264. this.checkYieldAwaitInDefaultParams();
  14265. if (this.awaitIdentPos > 0)
  14266. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  14267. this.yieldPos = oldYieldPos;
  14268. this.awaitPos = oldAwaitPos;
  14269. this.awaitIdentPos = oldAwaitIdentPos;
  14270. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  14271. }
  14272. this.checkExpressionErrors(refDestructuringErrors, true);
  14273. this.yieldPos = oldYieldPos || this.yieldPos;
  14274. this.awaitPos = oldAwaitPos || this.awaitPos;
  14275. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  14276. var node$1 = this.startNodeAt(startPos, startLoc);
  14277. node$1.callee = base;
  14278. node$1.arguments = exprList;
  14279. if (optionalSupported) {
  14280. node$1.optional = optional;
  14281. }
  14282. base = this.finishNode(node$1, "CallExpression");
  14283. } else if (this.type === types.backQuote) {
  14284. if (optional || optionalChained) {
  14285. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  14286. }
  14287. var node$2 = this.startNodeAt(startPos, startLoc);
  14288. node$2.tag = base;
  14289. node$2.quasi = this.parseTemplate({isTagged: true});
  14290. base = this.finishNode(node$2, "TaggedTemplateExpression");
  14291. }
  14292. return base
  14293. };
  14294. // Parse an atomic expression — either a single token that is an
  14295. // expression, an expression started by a keyword like `function` or
  14296. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  14297. // or `{}`.
  14298. pp$3.parseExprAtom = function(refDestructuringErrors) {
  14299. // If a division operator appears in an expression position, the
  14300. // tokenizer got confused, and we force it to read a regexp instead.
  14301. if (this.type === types.slash) { this.readRegexp(); }
  14302. var node, canBeArrow = this.potentialArrowAt === this.start;
  14303. switch (this.type) {
  14304. case types._super:
  14305. if (!this.allowSuper)
  14306. { this.raise(this.start, "'super' keyword outside a method"); }
  14307. node = this.startNode();
  14308. this.next();
  14309. if (this.type === types.parenL && !this.allowDirectSuper)
  14310. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  14311. // The `super` keyword can appear at below:
  14312. // SuperProperty:
  14313. // super [ Expression ]
  14314. // super . IdentifierName
  14315. // SuperCall:
  14316. // super ( Arguments )
  14317. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  14318. { this.unexpected(); }
  14319. return this.finishNode(node, "Super")
  14320. case types._this:
  14321. node = this.startNode();
  14322. this.next();
  14323. return this.finishNode(node, "ThisExpression")
  14324. case types.name:
  14325. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  14326. var id = this.parseIdent(false);
  14327. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  14328. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  14329. if (canBeArrow && !this.canInsertSemicolon()) {
  14330. if (this.eat(types.arrow))
  14331. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  14332. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
  14333. id = this.parseIdent(false);
  14334. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  14335. { this.unexpected(); }
  14336. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  14337. }
  14338. }
  14339. return id
  14340. case types.regexp:
  14341. var value = this.value;
  14342. node = this.parseLiteral(value.value);
  14343. node.regex = {pattern: value.pattern, flags: value.flags};
  14344. return node
  14345. case types.num: case types.string:
  14346. return this.parseLiteral(this.value)
  14347. case types._null: case types._true: case types._false:
  14348. node = this.startNode();
  14349. node.value = this.type === types._null ? null : this.type === types._true;
  14350. node.raw = this.type.keyword;
  14351. this.next();
  14352. return this.finishNode(node, "Literal")
  14353. case types.parenL:
  14354. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  14355. if (refDestructuringErrors) {
  14356. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  14357. { refDestructuringErrors.parenthesizedAssign = start; }
  14358. if (refDestructuringErrors.parenthesizedBind < 0)
  14359. { refDestructuringErrors.parenthesizedBind = start; }
  14360. }
  14361. return expr
  14362. case types.bracketL:
  14363. node = this.startNode();
  14364. this.next();
  14365. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  14366. return this.finishNode(node, "ArrayExpression")
  14367. case types.braceL:
  14368. return this.parseObj(false, refDestructuringErrors)
  14369. case types._function:
  14370. node = this.startNode();
  14371. this.next();
  14372. return this.parseFunction(node, 0)
  14373. case types._class:
  14374. return this.parseClass(this.startNode(), false)
  14375. case types._new:
  14376. return this.parseNew()
  14377. case types.backQuote:
  14378. return this.parseTemplate()
  14379. case types._import:
  14380. if (this.options.ecmaVersion >= 11) {
  14381. return this.parseExprImport()
  14382. } else {
  14383. return this.unexpected()
  14384. }
  14385. default:
  14386. this.unexpected();
  14387. }
  14388. };
  14389. pp$3.parseExprImport = function() {
  14390. var node = this.startNode();
  14391. // Consume `import` as an identifier for `import.meta`.
  14392. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  14393. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  14394. var meta = this.parseIdent(true);
  14395. switch (this.type) {
  14396. case types.parenL:
  14397. return this.parseDynamicImport(node)
  14398. case types.dot:
  14399. node.meta = meta;
  14400. return this.parseImportMeta(node)
  14401. default:
  14402. this.unexpected();
  14403. }
  14404. };
  14405. pp$3.parseDynamicImport = function(node) {
  14406. this.next(); // skip `(`
  14407. // Parse node.source.
  14408. node.source = this.parseMaybeAssign();
  14409. // Verify ending.
  14410. if (!this.eat(types.parenR)) {
  14411. var errorPos = this.start;
  14412. if (this.eat(types.comma) && this.eat(types.parenR)) {
  14413. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  14414. } else {
  14415. this.unexpected(errorPos);
  14416. }
  14417. }
  14418. return this.finishNode(node, "ImportExpression")
  14419. };
  14420. pp$3.parseImportMeta = function(node) {
  14421. this.next(); // skip `.`
  14422. var containsEsc = this.containsEsc;
  14423. node.property = this.parseIdent(true);
  14424. if (node.property.name !== "meta")
  14425. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  14426. if (containsEsc)
  14427. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  14428. if (this.options.sourceType !== "module")
  14429. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  14430. return this.finishNode(node, "MetaProperty")
  14431. };
  14432. pp$3.parseLiteral = function(value) {
  14433. var node = this.startNode();
  14434. node.value = value;
  14435. node.raw = this.input.slice(this.start, this.end);
  14436. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  14437. this.next();
  14438. return this.finishNode(node, "Literal")
  14439. };
  14440. pp$3.parseParenExpression = function() {
  14441. this.expect(types.parenL);
  14442. var val = this.parseExpression();
  14443. this.expect(types.parenR);
  14444. return val
  14445. };
  14446. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  14447. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  14448. if (this.options.ecmaVersion >= 6) {
  14449. this.next();
  14450. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  14451. var exprList = [], first = true, lastIsComma = false;
  14452. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  14453. this.yieldPos = 0;
  14454. this.awaitPos = 0;
  14455. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  14456. while (this.type !== types.parenR) {
  14457. first ? first = false : this.expect(types.comma);
  14458. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  14459. lastIsComma = true;
  14460. break
  14461. } else if (this.type === types.ellipsis) {
  14462. spreadStart = this.start;
  14463. exprList.push(this.parseParenItem(this.parseRestBinding()));
  14464. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  14465. break
  14466. } else {
  14467. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  14468. }
  14469. }
  14470. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  14471. this.expect(types.parenR);
  14472. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  14473. this.checkPatternErrors(refDestructuringErrors, false);
  14474. this.checkYieldAwaitInDefaultParams();
  14475. this.yieldPos = oldYieldPos;
  14476. this.awaitPos = oldAwaitPos;
  14477. return this.parseParenArrowList(startPos, startLoc, exprList)
  14478. }
  14479. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  14480. if (spreadStart) { this.unexpected(spreadStart); }
  14481. this.checkExpressionErrors(refDestructuringErrors, true);
  14482. this.yieldPos = oldYieldPos || this.yieldPos;
  14483. this.awaitPos = oldAwaitPos || this.awaitPos;
  14484. if (exprList.length > 1) {
  14485. val = this.startNodeAt(innerStartPos, innerStartLoc);
  14486. val.expressions = exprList;
  14487. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  14488. } else {
  14489. val = exprList[0];
  14490. }
  14491. } else {
  14492. val = this.parseParenExpression();
  14493. }
  14494. if (this.options.preserveParens) {
  14495. var par = this.startNodeAt(startPos, startLoc);
  14496. par.expression = val;
  14497. return this.finishNode(par, "ParenthesizedExpression")
  14498. } else {
  14499. return val
  14500. }
  14501. };
  14502. pp$3.parseParenItem = function(item) {
  14503. return item
  14504. };
  14505. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  14506. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  14507. };
  14508. // New's precedence is slightly tricky. It must allow its argument to
  14509. // be a `[]` or dot subscript expression, but not a call — at least,
  14510. // not without wrapping it in parentheses. Thus, it uses the noCalls
  14511. // argument to parseSubscripts to prevent it from consuming the
  14512. // argument list.
  14513. var empty$1 = [];
  14514. pp$3.parseNew = function() {
  14515. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  14516. var node = this.startNode();
  14517. var meta = this.parseIdent(true);
  14518. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  14519. node.meta = meta;
  14520. var containsEsc = this.containsEsc;
  14521. node.property = this.parseIdent(true);
  14522. if (node.property.name !== "target")
  14523. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  14524. if (containsEsc)
  14525. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  14526. if (!this.inNonArrowFunction)
  14527. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  14528. return this.finishNode(node, "MetaProperty")
  14529. }
  14530. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  14531. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  14532. if (isImport && node.callee.type === "ImportExpression") {
  14533. this.raise(startPos, "Cannot use new with import()");
  14534. }
  14535. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  14536. else { node.arguments = empty$1; }
  14537. return this.finishNode(node, "NewExpression")
  14538. };
  14539. // Parse template expression.
  14540. pp$3.parseTemplateElement = function(ref) {
  14541. var isTagged = ref.isTagged;
  14542. var elem = this.startNode();
  14543. if (this.type === types.invalidTemplate) {
  14544. if (!isTagged) {
  14545. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  14546. }
  14547. elem.value = {
  14548. raw: this.value,
  14549. cooked: null
  14550. };
  14551. } else {
  14552. elem.value = {
  14553. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  14554. cooked: this.value
  14555. };
  14556. }
  14557. this.next();
  14558. elem.tail = this.type === types.backQuote;
  14559. return this.finishNode(elem, "TemplateElement")
  14560. };
  14561. pp$3.parseTemplate = function(ref) {
  14562. if ( ref === void 0 ) ref = {};
  14563. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  14564. var node = this.startNode();
  14565. this.next();
  14566. node.expressions = [];
  14567. var curElt = this.parseTemplateElement({isTagged: isTagged});
  14568. node.quasis = [curElt];
  14569. while (!curElt.tail) {
  14570. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  14571. this.expect(types.dollarBraceL);
  14572. node.expressions.push(this.parseExpression());
  14573. this.expect(types.braceR);
  14574. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  14575. }
  14576. this.next();
  14577. return this.finishNode(node, "TemplateLiteral")
  14578. };
  14579. pp$3.isAsyncProp = function(prop) {
  14580. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  14581. (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)) &&
  14582. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  14583. };
  14584. // Parse an object literal or binding pattern.
  14585. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  14586. var node = this.startNode(), first = true, propHash = {};
  14587. node.properties = [];
  14588. this.next();
  14589. while (!this.eat(types.braceR)) {
  14590. if (!first) {
  14591. this.expect(types.comma);
  14592. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  14593. } else { first = false; }
  14594. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  14595. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  14596. node.properties.push(prop);
  14597. }
  14598. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  14599. };
  14600. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  14601. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  14602. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  14603. if (isPattern) {
  14604. prop.argument = this.parseIdent(false);
  14605. if (this.type === types.comma) {
  14606. this.raise(this.start, "Comma is not permitted after the rest element");
  14607. }
  14608. return this.finishNode(prop, "RestElement")
  14609. }
  14610. // To disallow parenthesized identifier via `this.toAssignable()`.
  14611. if (this.type === types.parenL && refDestructuringErrors) {
  14612. if (refDestructuringErrors.parenthesizedAssign < 0) {
  14613. refDestructuringErrors.parenthesizedAssign = this.start;
  14614. }
  14615. if (refDestructuringErrors.parenthesizedBind < 0) {
  14616. refDestructuringErrors.parenthesizedBind = this.start;
  14617. }
  14618. }
  14619. // Parse argument.
  14620. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  14621. // To disallow trailing comma via `this.toAssignable()`.
  14622. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  14623. refDestructuringErrors.trailingComma = this.start;
  14624. }
  14625. // Finish
  14626. return this.finishNode(prop, "SpreadElement")
  14627. }
  14628. if (this.options.ecmaVersion >= 6) {
  14629. prop.method = false;
  14630. prop.shorthand = false;
  14631. if (isPattern || refDestructuringErrors) {
  14632. startPos = this.start;
  14633. startLoc = this.startLoc;
  14634. }
  14635. if (!isPattern)
  14636. { isGenerator = this.eat(types.star); }
  14637. }
  14638. var containsEsc = this.containsEsc;
  14639. this.parsePropertyName(prop);
  14640. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  14641. isAsync = true;
  14642. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  14643. this.parsePropertyName(prop, refDestructuringErrors);
  14644. } else {
  14645. isAsync = false;
  14646. }
  14647. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  14648. return this.finishNode(prop, "Property")
  14649. };
  14650. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  14651. if ((isGenerator || isAsync) && this.type === types.colon)
  14652. { this.unexpected(); }
  14653. if (this.eat(types.colon)) {
  14654. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  14655. prop.kind = "init";
  14656. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  14657. if (isPattern) { this.unexpected(); }
  14658. prop.kind = "init";
  14659. prop.method = true;
  14660. prop.value = this.parseMethod(isGenerator, isAsync);
  14661. } else if (!isPattern && !containsEsc &&
  14662. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  14663. (prop.key.name === "get" || prop.key.name === "set") &&
  14664. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  14665. if (isGenerator || isAsync) { this.unexpected(); }
  14666. prop.kind = prop.key.name;
  14667. this.parsePropertyName(prop);
  14668. prop.value = this.parseMethod(false);
  14669. var paramCount = prop.kind === "get" ? 0 : 1;
  14670. if (prop.value.params.length !== paramCount) {
  14671. var start = prop.value.start;
  14672. if (prop.kind === "get")
  14673. { this.raiseRecoverable(start, "getter should have no params"); }
  14674. else
  14675. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  14676. } else {
  14677. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  14678. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  14679. }
  14680. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  14681. if (isGenerator || isAsync) { this.unexpected(); }
  14682. this.checkUnreserved(prop.key);
  14683. if (prop.key.name === "await" && !this.awaitIdentPos)
  14684. { this.awaitIdentPos = startPos; }
  14685. prop.kind = "init";
  14686. if (isPattern) {
  14687. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  14688. } else if (this.type === types.eq && refDestructuringErrors) {
  14689. if (refDestructuringErrors.shorthandAssign < 0)
  14690. { refDestructuringErrors.shorthandAssign = this.start; }
  14691. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  14692. } else {
  14693. prop.value = this.copyNode(prop.key);
  14694. }
  14695. prop.shorthand = true;
  14696. } else { this.unexpected(); }
  14697. };
  14698. pp$3.parsePropertyName = function(prop) {
  14699. if (this.options.ecmaVersion >= 6) {
  14700. if (this.eat(types.bracketL)) {
  14701. prop.computed = true;
  14702. prop.key = this.parseMaybeAssign();
  14703. this.expect(types.bracketR);
  14704. return prop.key
  14705. } else {
  14706. prop.computed = false;
  14707. }
  14708. }
  14709. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  14710. };
  14711. // Initialize empty function node.
  14712. pp$3.initFunction = function(node) {
  14713. node.id = null;
  14714. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  14715. if (this.options.ecmaVersion >= 8) { node.async = false; }
  14716. };
  14717. // Parse object or class method.
  14718. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  14719. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14720. this.initFunction(node);
  14721. if (this.options.ecmaVersion >= 6)
  14722. { node.generator = isGenerator; }
  14723. if (this.options.ecmaVersion >= 8)
  14724. { node.async = !!isAsync; }
  14725. this.yieldPos = 0;
  14726. this.awaitPos = 0;
  14727. this.awaitIdentPos = 0;
  14728. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  14729. this.expect(types.parenL);
  14730. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  14731. this.checkYieldAwaitInDefaultParams();
  14732. this.parseFunctionBody(node, false, true);
  14733. this.yieldPos = oldYieldPos;
  14734. this.awaitPos = oldAwaitPos;
  14735. this.awaitIdentPos = oldAwaitIdentPos;
  14736. return this.finishNode(node, "FunctionExpression")
  14737. };
  14738. // Parse arrow function expression with given parameters.
  14739. pp$3.parseArrowExpression = function(node, params, isAsync) {
  14740. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14741. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  14742. this.initFunction(node);
  14743. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  14744. this.yieldPos = 0;
  14745. this.awaitPos = 0;
  14746. this.awaitIdentPos = 0;
  14747. node.params = this.toAssignableList(params, true);
  14748. this.parseFunctionBody(node, true, false);
  14749. this.yieldPos = oldYieldPos;
  14750. this.awaitPos = oldAwaitPos;
  14751. this.awaitIdentPos = oldAwaitIdentPos;
  14752. return this.finishNode(node, "ArrowFunctionExpression")
  14753. };
  14754. // Parse function body and check parameters.
  14755. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  14756. var isExpression = isArrowFunction && this.type !== types.braceL;
  14757. var oldStrict = this.strict, useStrict = false;
  14758. if (isExpression) {
  14759. node.body = this.parseMaybeAssign();
  14760. node.expression = true;
  14761. this.checkParams(node, false);
  14762. } else {
  14763. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  14764. if (!oldStrict || nonSimple) {
  14765. useStrict = this.strictDirective(this.end);
  14766. // If this is a strict mode function, verify that argument names
  14767. // are not repeated, and it does not try to bind the words `eval`
  14768. // or `arguments`.
  14769. if (useStrict && nonSimple)
  14770. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  14771. }
  14772. // Start a new scope with regard to labels and the `inFunction`
  14773. // flag (restore them to their old value afterwards).
  14774. var oldLabels = this.labels;
  14775. this.labels = [];
  14776. if (useStrict) { this.strict = true; }
  14777. // Add the params to varDeclaredNames to ensure that an error is thrown
  14778. // if a let/const declaration in the function clashes with one of the params.
  14779. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  14780. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  14781. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  14782. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  14783. node.expression = false;
  14784. this.adaptDirectivePrologue(node.body.body);
  14785. this.labels = oldLabels;
  14786. }
  14787. this.exitScope();
  14788. };
  14789. pp$3.isSimpleParamList = function(params) {
  14790. for (var i = 0, list = params; i < list.length; i += 1)
  14791. {
  14792. var param = list[i];
  14793. if (param.type !== "Identifier") { return false
  14794. } }
  14795. return true
  14796. };
  14797. // Checks function params for various disallowed patterns such as using "eval"
  14798. // or "arguments" and duplicate parameters.
  14799. pp$3.checkParams = function(node, allowDuplicates) {
  14800. var nameHash = Object.create(null);
  14801. for (var i = 0, list = node.params; i < list.length; i += 1)
  14802. {
  14803. var param = list[i];
  14804. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  14805. }
  14806. };
  14807. // Parses a comma-separated list of expressions, and returns them as
  14808. // an array. `close` is the token type that ends the list, and
  14809. // `allowEmpty` can be turned on to allow subsequent commas with
  14810. // nothing in between them to be parsed as `null` (which is needed
  14811. // for array literals).
  14812. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  14813. var elts = [], first = true;
  14814. while (!this.eat(close)) {
  14815. if (!first) {
  14816. this.expect(types.comma);
  14817. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  14818. } else { first = false; }
  14819. var elt = (void 0);
  14820. if (allowEmpty && this.type === types.comma)
  14821. { elt = null; }
  14822. else if (this.type === types.ellipsis) {
  14823. elt = this.parseSpread(refDestructuringErrors);
  14824. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  14825. { refDestructuringErrors.trailingComma = this.start; }
  14826. } else {
  14827. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  14828. }
  14829. elts.push(elt);
  14830. }
  14831. return elts
  14832. };
  14833. pp$3.checkUnreserved = function(ref) {
  14834. var start = ref.start;
  14835. var end = ref.end;
  14836. var name = ref.name;
  14837. if (this.inGenerator && name === "yield")
  14838. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  14839. if (this.inAsync && name === "await")
  14840. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  14841. if (this.keywords.test(name))
  14842. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  14843. if (this.options.ecmaVersion < 6 &&
  14844. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  14845. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  14846. if (re.test(name)) {
  14847. if (!this.inAsync && name === "await")
  14848. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  14849. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  14850. }
  14851. };
  14852. // Parse the next token as an identifier. If `liberal` is true (used
  14853. // when parsing properties), it will also convert keywords into
  14854. // identifiers.
  14855. pp$3.parseIdent = function(liberal, isBinding) {
  14856. var node = this.startNode();
  14857. if (this.type === types.name) {
  14858. node.name = this.value;
  14859. } else if (this.type.keyword) {
  14860. node.name = this.type.keyword;
  14861. // To fix https://github.com/acornjs/acorn/issues/575
  14862. // `class` and `function` keywords push new context into this.context.
  14863. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  14864. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  14865. if ((node.name === "class" || node.name === "function") &&
  14866. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  14867. this.context.pop();
  14868. }
  14869. } else {
  14870. this.unexpected();
  14871. }
  14872. this.next(!!liberal);
  14873. this.finishNode(node, "Identifier");
  14874. if (!liberal) {
  14875. this.checkUnreserved(node);
  14876. if (node.name === "await" && !this.awaitIdentPos)
  14877. { this.awaitIdentPos = node.start; }
  14878. }
  14879. return node
  14880. };
  14881. // Parses yield expression inside generator.
  14882. pp$3.parseYield = function(noIn) {
  14883. if (!this.yieldPos) { this.yieldPos = this.start; }
  14884. var node = this.startNode();
  14885. this.next();
  14886. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  14887. node.delegate = false;
  14888. node.argument = null;
  14889. } else {
  14890. node.delegate = this.eat(types.star);
  14891. node.argument = this.parseMaybeAssign(noIn);
  14892. }
  14893. return this.finishNode(node, "YieldExpression")
  14894. };
  14895. pp$3.parseAwait = function() {
  14896. if (!this.awaitPos) { this.awaitPos = this.start; }
  14897. var node = this.startNode();
  14898. this.next();
  14899. node.argument = this.parseMaybeUnary(null, true);
  14900. return this.finishNode(node, "AwaitExpression")
  14901. };
  14902. var pp$4 = Parser.prototype;
  14903. // This function is used to raise exceptions on parse errors. It
  14904. // takes an offset integer (into the current `input`) to indicate
  14905. // the location of the error, attaches the position to the end
  14906. // of the error message, and then raises a `SyntaxError` with that
  14907. // message.
  14908. pp$4.raise = function(pos, message) {
  14909. var loc = getLineInfo(this.input, pos);
  14910. message += " (" + loc.line + ":" + loc.column + ")";
  14911. var err = new SyntaxError(message);
  14912. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  14913. throw err
  14914. };
  14915. pp$4.raiseRecoverable = pp$4.raise;
  14916. pp$4.curPosition = function() {
  14917. if (this.options.locations) {
  14918. return new Position(this.curLine, this.pos - this.lineStart)
  14919. }
  14920. };
  14921. var pp$5 = Parser.prototype;
  14922. var Scope = function Scope(flags) {
  14923. this.flags = flags;
  14924. // A list of var-declared names in the current lexical scope
  14925. this.var = [];
  14926. // A list of lexically-declared names in the current lexical scope
  14927. this.lexical = [];
  14928. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  14929. this.functions = [];
  14930. };
  14931. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  14932. pp$5.enterScope = function(flags) {
  14933. this.scopeStack.push(new Scope(flags));
  14934. };
  14935. pp$5.exitScope = function() {
  14936. this.scopeStack.pop();
  14937. };
  14938. // The spec says:
  14939. // > At the top level of a function, or script, function declarations are
  14940. // > treated like var declarations rather than like lexical declarations.
  14941. pp$5.treatFunctionsAsVarInScope = function(scope) {
  14942. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  14943. };
  14944. pp$5.declareName = function(name, bindingType, pos) {
  14945. var redeclared = false;
  14946. if (bindingType === BIND_LEXICAL) {
  14947. var scope = this.currentScope();
  14948. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  14949. scope.lexical.push(name);
  14950. if (this.inModule && (scope.flags & SCOPE_TOP))
  14951. { delete this.undefinedExports[name]; }
  14952. } else if (bindingType === BIND_SIMPLE_CATCH) {
  14953. var scope$1 = this.currentScope();
  14954. scope$1.lexical.push(name);
  14955. } else if (bindingType === BIND_FUNCTION) {
  14956. var scope$2 = this.currentScope();
  14957. if (this.treatFunctionsAsVar)
  14958. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  14959. else
  14960. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  14961. scope$2.functions.push(name);
  14962. } else {
  14963. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  14964. var scope$3 = this.scopeStack[i];
  14965. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  14966. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  14967. redeclared = true;
  14968. break
  14969. }
  14970. scope$3.var.push(name);
  14971. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  14972. { delete this.undefinedExports[name]; }
  14973. if (scope$3.flags & SCOPE_VAR) { break }
  14974. }
  14975. }
  14976. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  14977. };
  14978. pp$5.checkLocalExport = function(id) {
  14979. // scope.functions must be empty as Module code is always strict.
  14980. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  14981. this.scopeStack[0].var.indexOf(id.name) === -1) {
  14982. this.undefinedExports[id.name] = id;
  14983. }
  14984. };
  14985. pp$5.currentScope = function() {
  14986. return this.scopeStack[this.scopeStack.length - 1]
  14987. };
  14988. pp$5.currentVarScope = function() {
  14989. for (var i = this.scopeStack.length - 1;; i--) {
  14990. var scope = this.scopeStack[i];
  14991. if (scope.flags & SCOPE_VAR) { return scope }
  14992. }
  14993. };
  14994. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  14995. pp$5.currentThisScope = function() {
  14996. for (var i = this.scopeStack.length - 1;; i--) {
  14997. var scope = this.scopeStack[i];
  14998. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  14999. }
  15000. };
  15001. var Node = function Node(parser, pos, loc) {
  15002. this.type = "";
  15003. this.start = pos;
  15004. this.end = 0;
  15005. if (parser.options.locations)
  15006. { this.loc = new SourceLocation(parser, loc); }
  15007. if (parser.options.directSourceFile)
  15008. { this.sourceFile = parser.options.directSourceFile; }
  15009. if (parser.options.ranges)
  15010. { this.range = [pos, 0]; }
  15011. };
  15012. // Start an AST node, attaching a start offset.
  15013. var pp$6 = Parser.prototype;
  15014. pp$6.startNode = function() {
  15015. return new Node(this, this.start, this.startLoc)
  15016. };
  15017. pp$6.startNodeAt = function(pos, loc) {
  15018. return new Node(this, pos, loc)
  15019. };
  15020. // Finish an AST node, adding `type` and `end` properties.
  15021. function finishNodeAt(node, type, pos, loc) {
  15022. node.type = type;
  15023. node.end = pos;
  15024. if (this.options.locations)
  15025. { node.loc.end = loc; }
  15026. if (this.options.ranges)
  15027. { node.range[1] = pos; }
  15028. return node
  15029. }
  15030. pp$6.finishNode = function(node, type) {
  15031. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  15032. };
  15033. // Finish node at given position
  15034. pp$6.finishNodeAt = function(node, type, pos, loc) {
  15035. return finishNodeAt.call(this, node, type, pos, loc)
  15036. };
  15037. pp$6.copyNode = function(node) {
  15038. var newNode = new Node(this, node.start, this.startLoc);
  15039. for (var prop in node) { newNode[prop] = node[prop]; }
  15040. return newNode
  15041. };
  15042. // The algorithm used to determine whether a regexp can appear at a
  15043. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  15044. this.token = token;
  15045. this.isExpr = !!isExpr;
  15046. this.preserveSpace = !!preserveSpace;
  15047. this.override = override;
  15048. this.generator = !!generator;
  15049. };
  15050. var types$1 = {
  15051. b_stat: new TokContext("{", false),
  15052. b_expr: new TokContext("{", true),
  15053. b_tmpl: new TokContext("${", false),
  15054. p_stat: new TokContext("(", false),
  15055. p_expr: new TokContext("(", true),
  15056. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  15057. f_stat: new TokContext("function", false),
  15058. f_expr: new TokContext("function", true),
  15059. f_expr_gen: new TokContext("function", true, false, null, true),
  15060. f_gen: new TokContext("function", false, false, null, true)
  15061. };
  15062. var pp$7 = Parser.prototype;
  15063. pp$7.initialContext = function() {
  15064. return [types$1.b_stat]
  15065. };
  15066. pp$7.braceIsBlock = function(prevType) {
  15067. var parent = this.curContext();
  15068. if (parent === types$1.f_expr || parent === types$1.f_stat)
  15069. { return true }
  15070. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  15071. { return !parent.isExpr }
  15072. // The check for `tt.name && exprAllowed` detects whether we are
  15073. // after a `yield` or `of` construct. See the `updateContext` for
  15074. // `tt.name`.
  15075. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  15076. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  15077. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  15078. { return true }
  15079. if (prevType === types.braceL)
  15080. { return parent === types$1.b_stat }
  15081. if (prevType === types._var || prevType === types._const || prevType === types.name)
  15082. { return false }
  15083. return !this.exprAllowed
  15084. };
  15085. pp$7.inGeneratorContext = function() {
  15086. for (var i = this.context.length - 1; i >= 1; i--) {
  15087. var context = this.context[i];
  15088. if (context.token === "function")
  15089. { return context.generator }
  15090. }
  15091. return false
  15092. };
  15093. pp$7.updateContext = function(prevType) {
  15094. var update, type = this.type;
  15095. if (type.keyword && prevType === types.dot)
  15096. { this.exprAllowed = false; }
  15097. else if (update = type.updateContext)
  15098. { update.call(this, prevType); }
  15099. else
  15100. { this.exprAllowed = type.beforeExpr; }
  15101. };
  15102. // Token-specific context update code
  15103. types.parenR.updateContext = types.braceR.updateContext = function() {
  15104. if (this.context.length === 1) {
  15105. this.exprAllowed = true;
  15106. return
  15107. }
  15108. var out = this.context.pop();
  15109. if (out === types$1.b_stat && this.curContext().token === "function") {
  15110. out = this.context.pop();
  15111. }
  15112. this.exprAllowed = !out.isExpr;
  15113. };
  15114. types.braceL.updateContext = function(prevType) {
  15115. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  15116. this.exprAllowed = true;
  15117. };
  15118. types.dollarBraceL.updateContext = function() {
  15119. this.context.push(types$1.b_tmpl);
  15120. this.exprAllowed = true;
  15121. };
  15122. types.parenL.updateContext = function(prevType) {
  15123. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  15124. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  15125. this.exprAllowed = true;
  15126. };
  15127. types.incDec.updateContext = function() {
  15128. // tokExprAllowed stays unchanged
  15129. };
  15130. types._function.updateContext = types._class.updateContext = function(prevType) {
  15131. if (prevType.beforeExpr && prevType !== types._else &&
  15132. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  15133. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  15134. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  15135. { this.context.push(types$1.f_expr); }
  15136. else
  15137. { this.context.push(types$1.f_stat); }
  15138. this.exprAllowed = false;
  15139. };
  15140. types.backQuote.updateContext = function() {
  15141. if (this.curContext() === types$1.q_tmpl)
  15142. { this.context.pop(); }
  15143. else
  15144. { this.context.push(types$1.q_tmpl); }
  15145. this.exprAllowed = false;
  15146. };
  15147. types.star.updateContext = function(prevType) {
  15148. if (prevType === types._function) {
  15149. var index = this.context.length - 1;
  15150. if (this.context[index] === types$1.f_expr)
  15151. { this.context[index] = types$1.f_expr_gen; }
  15152. else
  15153. { this.context[index] = types$1.f_gen; }
  15154. }
  15155. this.exprAllowed = true;
  15156. };
  15157. types.name.updateContext = function(prevType) {
  15158. var allowed = false;
  15159. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  15160. if (this.value === "of" && !this.exprAllowed ||
  15161. this.value === "yield" && this.inGeneratorContext())
  15162. { allowed = true; }
  15163. }
  15164. this.exprAllowed = allowed;
  15165. };
  15166. // This file contains Unicode properties extracted from the ECMAScript
  15167. // specification. The lists are extracted like so:
  15168. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  15169. // #table-binary-unicode-properties
  15170. 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";
  15171. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  15172. var ecma11BinaryProperties = ecma10BinaryProperties;
  15173. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  15174. var unicodeBinaryProperties = {
  15175. 9: ecma9BinaryProperties,
  15176. 10: ecma10BinaryProperties,
  15177. 11: ecma11BinaryProperties,
  15178. 12: ecma12BinaryProperties
  15179. };
  15180. // #table-unicode-general-category-values
  15181. 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";
  15182. // #table-unicode-script-values
  15183. 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";
  15184. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  15185. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  15186. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  15187. var unicodeScriptValues = {
  15188. 9: ecma9ScriptValues,
  15189. 10: ecma10ScriptValues,
  15190. 11: ecma11ScriptValues,
  15191. 12: ecma12ScriptValues
  15192. };
  15193. var data = {};
  15194. function buildUnicodeData(ecmaVersion) {
  15195. var d = data[ecmaVersion] = {
  15196. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  15197. nonBinary: {
  15198. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  15199. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  15200. }
  15201. };
  15202. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  15203. d.nonBinary.gc = d.nonBinary.General_Category;
  15204. d.nonBinary.sc = d.nonBinary.Script;
  15205. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  15206. }
  15207. buildUnicodeData(9);
  15208. buildUnicodeData(10);
  15209. buildUnicodeData(11);
  15210. buildUnicodeData(12);
  15211. var pp$8 = Parser.prototype;
  15212. var RegExpValidationState = function RegExpValidationState(parser) {
  15213. this.parser = parser;
  15214. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
  15215. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  15216. this.source = "";
  15217. this.flags = "";
  15218. this.start = 0;
  15219. this.switchU = false;
  15220. this.switchN = false;
  15221. this.pos = 0;
  15222. this.lastIntValue = 0;
  15223. this.lastStringValue = "";
  15224. this.lastAssertionIsQuantifiable = false;
  15225. this.numCapturingParens = 0;
  15226. this.maxBackReference = 0;
  15227. this.groupNames = [];
  15228. this.backReferenceNames = [];
  15229. };
  15230. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  15231. var unicode = flags.indexOf("u") !== -1;
  15232. this.start = start | 0;
  15233. this.source = pattern + "";
  15234. this.flags = flags;
  15235. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  15236. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  15237. };
  15238. RegExpValidationState.prototype.raise = function raise (message) {
  15239. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  15240. };
  15241. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  15242. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  15243. RegExpValidationState.prototype.at = function at (i, forceU) {
  15244. if ( forceU === void 0 ) forceU = false;
  15245. var s = this.source;
  15246. var l = s.length;
  15247. if (i >= l) {
  15248. return -1
  15249. }
  15250. var c = s.charCodeAt(i);
  15251. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  15252. return c
  15253. }
  15254. var next = s.charCodeAt(i + 1);
  15255. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  15256. };
  15257. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  15258. if ( forceU === void 0 ) forceU = false;
  15259. var s = this.source;
  15260. var l = s.length;
  15261. if (i >= l) {
  15262. return l
  15263. }
  15264. var c = s.charCodeAt(i), next;
  15265. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  15266. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  15267. return i + 1
  15268. }
  15269. return i + 2
  15270. };
  15271. RegExpValidationState.prototype.current = function current (forceU) {
  15272. if ( forceU === void 0 ) forceU = false;
  15273. return this.at(this.pos, forceU)
  15274. };
  15275. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  15276. if ( forceU === void 0 ) forceU = false;
  15277. return this.at(this.nextIndex(this.pos, forceU), forceU)
  15278. };
  15279. RegExpValidationState.prototype.advance = function advance (forceU) {
  15280. if ( forceU === void 0 ) forceU = false;
  15281. this.pos = this.nextIndex(this.pos, forceU);
  15282. };
  15283. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  15284. if ( forceU === void 0 ) forceU = false;
  15285. if (this.current(forceU) === ch) {
  15286. this.advance(forceU);
  15287. return true
  15288. }
  15289. return false
  15290. };
  15291. function codePointToString(ch) {
  15292. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  15293. ch -= 0x10000;
  15294. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  15295. }
  15296. /**
  15297. * Validate the flags part of a given RegExpLiteral.
  15298. *
  15299. * @param {RegExpValidationState} state The state to validate RegExp.
  15300. * @returns {void}
  15301. */
  15302. pp$8.validateRegExpFlags = function(state) {
  15303. var validFlags = state.validFlags;
  15304. var flags = state.flags;
  15305. for (var i = 0; i < flags.length; i++) {
  15306. var flag = flags.charAt(i);
  15307. if (validFlags.indexOf(flag) === -1) {
  15308. this.raise(state.start, "Invalid regular expression flag");
  15309. }
  15310. if (flags.indexOf(flag, i + 1) > -1) {
  15311. this.raise(state.start, "Duplicate regular expression flag");
  15312. }
  15313. }
  15314. };
  15315. /**
  15316. * Validate the pattern part of a given RegExpLiteral.
  15317. *
  15318. * @param {RegExpValidationState} state The state to validate RegExp.
  15319. * @returns {void}
  15320. */
  15321. pp$8.validateRegExpPattern = function(state) {
  15322. this.regexp_pattern(state);
  15323. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  15324. // parsing contains a |GroupName|, reparse with the goal symbol
  15325. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  15326. // exception if _P_ did not conform to the grammar, if any elements of _P_
  15327. // were not matched by the parse, or if any Early Error conditions exist.
  15328. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  15329. state.switchN = true;
  15330. this.regexp_pattern(state);
  15331. }
  15332. };
  15333. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  15334. pp$8.regexp_pattern = function(state) {
  15335. state.pos = 0;
  15336. state.lastIntValue = 0;
  15337. state.lastStringValue = "";
  15338. state.lastAssertionIsQuantifiable = false;
  15339. state.numCapturingParens = 0;
  15340. state.maxBackReference = 0;
  15341. state.groupNames.length = 0;
  15342. state.backReferenceNames.length = 0;
  15343. this.regexp_disjunction(state);
  15344. if (state.pos !== state.source.length) {
  15345. // Make the same messages as V8.
  15346. if (state.eat(0x29 /* ) */)) {
  15347. state.raise("Unmatched ')'");
  15348. }
  15349. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  15350. state.raise("Lone quantifier brackets");
  15351. }
  15352. }
  15353. if (state.maxBackReference > state.numCapturingParens) {
  15354. state.raise("Invalid escape");
  15355. }
  15356. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  15357. var name = list[i];
  15358. if (state.groupNames.indexOf(name) === -1) {
  15359. state.raise("Invalid named capture referenced");
  15360. }
  15361. }
  15362. };
  15363. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  15364. pp$8.regexp_disjunction = function(state) {
  15365. this.regexp_alternative(state);
  15366. while (state.eat(0x7C /* | */)) {
  15367. this.regexp_alternative(state);
  15368. }
  15369. // Make the same message as V8.
  15370. if (this.regexp_eatQuantifier(state, true)) {
  15371. state.raise("Nothing to repeat");
  15372. }
  15373. if (state.eat(0x7B /* { */)) {
  15374. state.raise("Lone quantifier brackets");
  15375. }
  15376. };
  15377. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  15378. pp$8.regexp_alternative = function(state) {
  15379. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  15380. { }
  15381. };
  15382. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  15383. pp$8.regexp_eatTerm = function(state) {
  15384. if (this.regexp_eatAssertion(state)) {
  15385. // Handle `QuantifiableAssertion Quantifier` alternative.
  15386. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  15387. // is a QuantifiableAssertion.
  15388. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  15389. // Make the same message as V8.
  15390. if (state.switchU) {
  15391. state.raise("Invalid quantifier");
  15392. }
  15393. }
  15394. return true
  15395. }
  15396. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  15397. this.regexp_eatQuantifier(state);
  15398. return true
  15399. }
  15400. return false
  15401. };
  15402. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  15403. pp$8.regexp_eatAssertion = function(state) {
  15404. var start = state.pos;
  15405. state.lastAssertionIsQuantifiable = false;
  15406. // ^, $
  15407. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  15408. return true
  15409. }
  15410. // \b \B
  15411. if (state.eat(0x5C /* \ */)) {
  15412. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  15413. return true
  15414. }
  15415. state.pos = start;
  15416. }
  15417. // Lookahead / Lookbehind
  15418. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  15419. var lookbehind = false;
  15420. if (this.options.ecmaVersion >= 9) {
  15421. lookbehind = state.eat(0x3C /* < */);
  15422. }
  15423. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  15424. this.regexp_disjunction(state);
  15425. if (!state.eat(0x29 /* ) */)) {
  15426. state.raise("Unterminated group");
  15427. }
  15428. state.lastAssertionIsQuantifiable = !lookbehind;
  15429. return true
  15430. }
  15431. }
  15432. state.pos = start;
  15433. return false
  15434. };
  15435. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  15436. pp$8.regexp_eatQuantifier = function(state, noError) {
  15437. if ( noError === void 0 ) noError = false;
  15438. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  15439. state.eat(0x3F /* ? */);
  15440. return true
  15441. }
  15442. return false
  15443. };
  15444. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  15445. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  15446. return (
  15447. state.eat(0x2A /* * */) ||
  15448. state.eat(0x2B /* + */) ||
  15449. state.eat(0x3F /* ? */) ||
  15450. this.regexp_eatBracedQuantifier(state, noError)
  15451. )
  15452. };
  15453. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  15454. var start = state.pos;
  15455. if (state.eat(0x7B /* { */)) {
  15456. var min = 0, max = -1;
  15457. if (this.regexp_eatDecimalDigits(state)) {
  15458. min = state.lastIntValue;
  15459. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  15460. max = state.lastIntValue;
  15461. }
  15462. if (state.eat(0x7D /* } */)) {
  15463. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  15464. if (max !== -1 && max < min && !noError) {
  15465. state.raise("numbers out of order in {} quantifier");
  15466. }
  15467. return true
  15468. }
  15469. }
  15470. if (state.switchU && !noError) {
  15471. state.raise("Incomplete quantifier");
  15472. }
  15473. state.pos = start;
  15474. }
  15475. return false
  15476. };
  15477. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  15478. pp$8.regexp_eatAtom = function(state) {
  15479. return (
  15480. this.regexp_eatPatternCharacters(state) ||
  15481. state.eat(0x2E /* . */) ||
  15482. this.regexp_eatReverseSolidusAtomEscape(state) ||
  15483. this.regexp_eatCharacterClass(state) ||
  15484. this.regexp_eatUncapturingGroup(state) ||
  15485. this.regexp_eatCapturingGroup(state)
  15486. )
  15487. };
  15488. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  15489. var start = state.pos;
  15490. if (state.eat(0x5C /* \ */)) {
  15491. if (this.regexp_eatAtomEscape(state)) {
  15492. return true
  15493. }
  15494. state.pos = start;
  15495. }
  15496. return false
  15497. };
  15498. pp$8.regexp_eatUncapturingGroup = function(state) {
  15499. var start = state.pos;
  15500. if (state.eat(0x28 /* ( */)) {
  15501. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  15502. this.regexp_disjunction(state);
  15503. if (state.eat(0x29 /* ) */)) {
  15504. return true
  15505. }
  15506. state.raise("Unterminated group");
  15507. }
  15508. state.pos = start;
  15509. }
  15510. return false
  15511. };
  15512. pp$8.regexp_eatCapturingGroup = function(state) {
  15513. if (state.eat(0x28 /* ( */)) {
  15514. if (this.options.ecmaVersion >= 9) {
  15515. this.regexp_groupSpecifier(state);
  15516. } else if (state.current() === 0x3F /* ? */) {
  15517. state.raise("Invalid group");
  15518. }
  15519. this.regexp_disjunction(state);
  15520. if (state.eat(0x29 /* ) */)) {
  15521. state.numCapturingParens += 1;
  15522. return true
  15523. }
  15524. state.raise("Unterminated group");
  15525. }
  15526. return false
  15527. };
  15528. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  15529. pp$8.regexp_eatExtendedAtom = function(state) {
  15530. return (
  15531. state.eat(0x2E /* . */) ||
  15532. this.regexp_eatReverseSolidusAtomEscape(state) ||
  15533. this.regexp_eatCharacterClass(state) ||
  15534. this.regexp_eatUncapturingGroup(state) ||
  15535. this.regexp_eatCapturingGroup(state) ||
  15536. this.regexp_eatInvalidBracedQuantifier(state) ||
  15537. this.regexp_eatExtendedPatternCharacter(state)
  15538. )
  15539. };
  15540. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  15541. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  15542. if (this.regexp_eatBracedQuantifier(state, true)) {
  15543. state.raise("Nothing to repeat");
  15544. }
  15545. return false
  15546. };
  15547. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  15548. pp$8.regexp_eatSyntaxCharacter = function(state) {
  15549. var ch = state.current();
  15550. if (isSyntaxCharacter(ch)) {
  15551. state.lastIntValue = ch;
  15552. state.advance();
  15553. return true
  15554. }
  15555. return false
  15556. };
  15557. function isSyntaxCharacter(ch) {
  15558. return (
  15559. ch === 0x24 /* $ */ ||
  15560. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  15561. ch === 0x2E /* . */ ||
  15562. ch === 0x3F /* ? */ ||
  15563. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  15564. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  15565. )
  15566. }
  15567. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  15568. // But eat eager.
  15569. pp$8.regexp_eatPatternCharacters = function(state) {
  15570. var start = state.pos;
  15571. var ch = 0;
  15572. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  15573. state.advance();
  15574. }
  15575. return state.pos !== start
  15576. };
  15577. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  15578. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  15579. var ch = state.current();
  15580. if (
  15581. ch !== -1 &&
  15582. ch !== 0x24 /* $ */ &&
  15583. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  15584. ch !== 0x2E /* . */ &&
  15585. ch !== 0x3F /* ? */ &&
  15586. ch !== 0x5B /* [ */ &&
  15587. ch !== 0x5E /* ^ */ &&
  15588. ch !== 0x7C /* | */
  15589. ) {
  15590. state.advance();
  15591. return true
  15592. }
  15593. return false
  15594. };
  15595. // GroupSpecifier ::
  15596. // [empty]
  15597. // `?` GroupName
  15598. pp$8.regexp_groupSpecifier = function(state) {
  15599. if (state.eat(0x3F /* ? */)) {
  15600. if (this.regexp_eatGroupName(state)) {
  15601. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  15602. state.raise("Duplicate capture group name");
  15603. }
  15604. state.groupNames.push(state.lastStringValue);
  15605. return
  15606. }
  15607. state.raise("Invalid group");
  15608. }
  15609. };
  15610. // GroupName ::
  15611. // `<` RegExpIdentifierName `>`
  15612. // Note: this updates `state.lastStringValue` property with the eaten name.
  15613. pp$8.regexp_eatGroupName = function(state) {
  15614. state.lastStringValue = "";
  15615. if (state.eat(0x3C /* < */)) {
  15616. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  15617. return true
  15618. }
  15619. state.raise("Invalid capture group name");
  15620. }
  15621. return false
  15622. };
  15623. // RegExpIdentifierName ::
  15624. // RegExpIdentifierStart
  15625. // RegExpIdentifierName RegExpIdentifierPart
  15626. // Note: this updates `state.lastStringValue` property with the eaten name.
  15627. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  15628. state.lastStringValue = "";
  15629. if (this.regexp_eatRegExpIdentifierStart(state)) {
  15630. state.lastStringValue += codePointToString(state.lastIntValue);
  15631. while (this.regexp_eatRegExpIdentifierPart(state)) {
  15632. state.lastStringValue += codePointToString(state.lastIntValue);
  15633. }
  15634. return true
  15635. }
  15636. return false
  15637. };
  15638. // RegExpIdentifierStart ::
  15639. // UnicodeIDStart
  15640. // `$`
  15641. // `_`
  15642. // `\` RegExpUnicodeEscapeSequence[+U]
  15643. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  15644. var start = state.pos;
  15645. var forceU = this.options.ecmaVersion >= 11;
  15646. var ch = state.current(forceU);
  15647. state.advance(forceU);
  15648. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  15649. ch = state.lastIntValue;
  15650. }
  15651. if (isRegExpIdentifierStart(ch)) {
  15652. state.lastIntValue = ch;
  15653. return true
  15654. }
  15655. state.pos = start;
  15656. return false
  15657. };
  15658. function isRegExpIdentifierStart(ch) {
  15659. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  15660. }
  15661. // RegExpIdentifierPart ::
  15662. // UnicodeIDContinue
  15663. // `$`
  15664. // `_`
  15665. // `\` RegExpUnicodeEscapeSequence[+U]
  15666. // <ZWNJ>
  15667. // <ZWJ>
  15668. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  15669. var start = state.pos;
  15670. var forceU = this.options.ecmaVersion >= 11;
  15671. var ch = state.current(forceU);
  15672. state.advance(forceU);
  15673. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  15674. ch = state.lastIntValue;
  15675. }
  15676. if (isRegExpIdentifierPart(ch)) {
  15677. state.lastIntValue = ch;
  15678. return true
  15679. }
  15680. state.pos = start;
  15681. return false
  15682. };
  15683. function isRegExpIdentifierPart(ch) {
  15684. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  15685. }
  15686. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  15687. pp$8.regexp_eatAtomEscape = function(state) {
  15688. if (
  15689. this.regexp_eatBackReference(state) ||
  15690. this.regexp_eatCharacterClassEscape(state) ||
  15691. this.regexp_eatCharacterEscape(state) ||
  15692. (state.switchN && this.regexp_eatKGroupName(state))
  15693. ) {
  15694. return true
  15695. }
  15696. if (state.switchU) {
  15697. // Make the same message as V8.
  15698. if (state.current() === 0x63 /* c */) {
  15699. state.raise("Invalid unicode escape");
  15700. }
  15701. state.raise("Invalid escape");
  15702. }
  15703. return false
  15704. };
  15705. pp$8.regexp_eatBackReference = function(state) {
  15706. var start = state.pos;
  15707. if (this.regexp_eatDecimalEscape(state)) {
  15708. var n = state.lastIntValue;
  15709. if (state.switchU) {
  15710. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  15711. if (n > state.maxBackReference) {
  15712. state.maxBackReference = n;
  15713. }
  15714. return true
  15715. }
  15716. if (n <= state.numCapturingParens) {
  15717. return true
  15718. }
  15719. state.pos = start;
  15720. }
  15721. return false
  15722. };
  15723. pp$8.regexp_eatKGroupName = function(state) {
  15724. if (state.eat(0x6B /* k */)) {
  15725. if (this.regexp_eatGroupName(state)) {
  15726. state.backReferenceNames.push(state.lastStringValue);
  15727. return true
  15728. }
  15729. state.raise("Invalid named reference");
  15730. }
  15731. return false
  15732. };
  15733. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  15734. pp$8.regexp_eatCharacterEscape = function(state) {
  15735. return (
  15736. this.regexp_eatControlEscape(state) ||
  15737. this.regexp_eatCControlLetter(state) ||
  15738. this.regexp_eatZero(state) ||
  15739. this.regexp_eatHexEscapeSequence(state) ||
  15740. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  15741. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  15742. this.regexp_eatIdentityEscape(state)
  15743. )
  15744. };
  15745. pp$8.regexp_eatCControlLetter = function(state) {
  15746. var start = state.pos;
  15747. if (state.eat(0x63 /* c */)) {
  15748. if (this.regexp_eatControlLetter(state)) {
  15749. return true
  15750. }
  15751. state.pos = start;
  15752. }
  15753. return false
  15754. };
  15755. pp$8.regexp_eatZero = function(state) {
  15756. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  15757. state.lastIntValue = 0;
  15758. state.advance();
  15759. return true
  15760. }
  15761. return false
  15762. };
  15763. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  15764. pp$8.regexp_eatControlEscape = function(state) {
  15765. var ch = state.current();
  15766. if (ch === 0x74 /* t */) {
  15767. state.lastIntValue = 0x09; /* \t */
  15768. state.advance();
  15769. return true
  15770. }
  15771. if (ch === 0x6E /* n */) {
  15772. state.lastIntValue = 0x0A; /* \n */
  15773. state.advance();
  15774. return true
  15775. }
  15776. if (ch === 0x76 /* v */) {
  15777. state.lastIntValue = 0x0B; /* \v */
  15778. state.advance();
  15779. return true
  15780. }
  15781. if (ch === 0x66 /* f */) {
  15782. state.lastIntValue = 0x0C; /* \f */
  15783. state.advance();
  15784. return true
  15785. }
  15786. if (ch === 0x72 /* r */) {
  15787. state.lastIntValue = 0x0D; /* \r */
  15788. state.advance();
  15789. return true
  15790. }
  15791. return false
  15792. };
  15793. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  15794. pp$8.regexp_eatControlLetter = function(state) {
  15795. var ch = state.current();
  15796. if (isControlLetter(ch)) {
  15797. state.lastIntValue = ch % 0x20;
  15798. state.advance();
  15799. return true
  15800. }
  15801. return false
  15802. };
  15803. function isControlLetter(ch) {
  15804. return (
  15805. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  15806. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  15807. )
  15808. }
  15809. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  15810. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  15811. if ( forceU === void 0 ) forceU = false;
  15812. var start = state.pos;
  15813. var switchU = forceU || state.switchU;
  15814. if (state.eat(0x75 /* u */)) {
  15815. if (this.regexp_eatFixedHexDigits(state, 4)) {
  15816. var lead = state.lastIntValue;
  15817. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  15818. var leadSurrogateEnd = state.pos;
  15819. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  15820. var trail = state.lastIntValue;
  15821. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  15822. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  15823. return true
  15824. }
  15825. }
  15826. state.pos = leadSurrogateEnd;
  15827. state.lastIntValue = lead;
  15828. }
  15829. return true
  15830. }
  15831. if (
  15832. switchU &&
  15833. state.eat(0x7B /* { */) &&
  15834. this.regexp_eatHexDigits(state) &&
  15835. state.eat(0x7D /* } */) &&
  15836. isValidUnicode(state.lastIntValue)
  15837. ) {
  15838. return true
  15839. }
  15840. if (switchU) {
  15841. state.raise("Invalid unicode escape");
  15842. }
  15843. state.pos = start;
  15844. }
  15845. return false
  15846. };
  15847. function isValidUnicode(ch) {
  15848. return ch >= 0 && ch <= 0x10FFFF
  15849. }
  15850. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  15851. pp$8.regexp_eatIdentityEscape = function(state) {
  15852. if (state.switchU) {
  15853. if (this.regexp_eatSyntaxCharacter(state)) {
  15854. return true
  15855. }
  15856. if (state.eat(0x2F /* / */)) {
  15857. state.lastIntValue = 0x2F; /* / */
  15858. return true
  15859. }
  15860. return false
  15861. }
  15862. var ch = state.current();
  15863. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  15864. state.lastIntValue = ch;
  15865. state.advance();
  15866. return true
  15867. }
  15868. return false
  15869. };
  15870. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  15871. pp$8.regexp_eatDecimalEscape = function(state) {
  15872. state.lastIntValue = 0;
  15873. var ch = state.current();
  15874. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  15875. do {
  15876. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  15877. state.advance();
  15878. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  15879. return true
  15880. }
  15881. return false
  15882. };
  15883. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  15884. pp$8.regexp_eatCharacterClassEscape = function(state) {
  15885. var ch = state.current();
  15886. if (isCharacterClassEscape(ch)) {
  15887. state.lastIntValue = -1;
  15888. state.advance();
  15889. return true
  15890. }
  15891. if (
  15892. state.switchU &&
  15893. this.options.ecmaVersion >= 9 &&
  15894. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  15895. ) {
  15896. state.lastIntValue = -1;
  15897. state.advance();
  15898. if (
  15899. state.eat(0x7B /* { */) &&
  15900. this.regexp_eatUnicodePropertyValueExpression(state) &&
  15901. state.eat(0x7D /* } */)
  15902. ) {
  15903. return true
  15904. }
  15905. state.raise("Invalid property name");
  15906. }
  15907. return false
  15908. };
  15909. function isCharacterClassEscape(ch) {
  15910. return (
  15911. ch === 0x64 /* d */ ||
  15912. ch === 0x44 /* D */ ||
  15913. ch === 0x73 /* s */ ||
  15914. ch === 0x53 /* S */ ||
  15915. ch === 0x77 /* w */ ||
  15916. ch === 0x57 /* W */
  15917. )
  15918. }
  15919. // UnicodePropertyValueExpression ::
  15920. // UnicodePropertyName `=` UnicodePropertyValue
  15921. // LoneUnicodePropertyNameOrValue
  15922. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  15923. var start = state.pos;
  15924. // UnicodePropertyName `=` UnicodePropertyValue
  15925. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  15926. var name = state.lastStringValue;
  15927. if (this.regexp_eatUnicodePropertyValue(state)) {
  15928. var value = state.lastStringValue;
  15929. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  15930. return true
  15931. }
  15932. }
  15933. state.pos = start;
  15934. // LoneUnicodePropertyNameOrValue
  15935. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  15936. var nameOrValue = state.lastStringValue;
  15937. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  15938. return true
  15939. }
  15940. return false
  15941. };
  15942. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  15943. if (!has(state.unicodeProperties.nonBinary, name))
  15944. { state.raise("Invalid property name"); }
  15945. if (!state.unicodeProperties.nonBinary[name].test(value))
  15946. { state.raise("Invalid property value"); }
  15947. };
  15948. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  15949. if (!state.unicodeProperties.binary.test(nameOrValue))
  15950. { state.raise("Invalid property name"); }
  15951. };
  15952. // UnicodePropertyName ::
  15953. // UnicodePropertyNameCharacters
  15954. pp$8.regexp_eatUnicodePropertyName = function(state) {
  15955. var ch = 0;
  15956. state.lastStringValue = "";
  15957. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  15958. state.lastStringValue += codePointToString(ch);
  15959. state.advance();
  15960. }
  15961. return state.lastStringValue !== ""
  15962. };
  15963. function isUnicodePropertyNameCharacter(ch) {
  15964. return isControlLetter(ch) || ch === 0x5F /* _ */
  15965. }
  15966. // UnicodePropertyValue ::
  15967. // UnicodePropertyValueCharacters
  15968. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  15969. var ch = 0;
  15970. state.lastStringValue = "";
  15971. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  15972. state.lastStringValue += codePointToString(ch);
  15973. state.advance();
  15974. }
  15975. return state.lastStringValue !== ""
  15976. };
  15977. function isUnicodePropertyValueCharacter(ch) {
  15978. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  15979. }
  15980. // LoneUnicodePropertyNameOrValue ::
  15981. // UnicodePropertyValueCharacters
  15982. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  15983. return this.regexp_eatUnicodePropertyValue(state)
  15984. };
  15985. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  15986. pp$8.regexp_eatCharacterClass = function(state) {
  15987. if (state.eat(0x5B /* [ */)) {
  15988. state.eat(0x5E /* ^ */);
  15989. this.regexp_classRanges(state);
  15990. if (state.eat(0x5D /* ] */)) {
  15991. return true
  15992. }
  15993. // Unreachable since it threw "unterminated regular expression" error before.
  15994. state.raise("Unterminated character class");
  15995. }
  15996. return false
  15997. };
  15998. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  15999. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  16000. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  16001. pp$8.regexp_classRanges = function(state) {
  16002. while (this.regexp_eatClassAtom(state)) {
  16003. var left = state.lastIntValue;
  16004. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  16005. var right = state.lastIntValue;
  16006. if (state.switchU && (left === -1 || right === -1)) {
  16007. state.raise("Invalid character class");
  16008. }
  16009. if (left !== -1 && right !== -1 && left > right) {
  16010. state.raise("Range out of order in character class");
  16011. }
  16012. }
  16013. }
  16014. };
  16015. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  16016. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  16017. pp$8.regexp_eatClassAtom = function(state) {
  16018. var start = state.pos;
  16019. if (state.eat(0x5C /* \ */)) {
  16020. if (this.regexp_eatClassEscape(state)) {
  16021. return true
  16022. }
  16023. if (state.switchU) {
  16024. // Make the same message as V8.
  16025. var ch$1 = state.current();
  16026. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  16027. state.raise("Invalid class escape");
  16028. }
  16029. state.raise("Invalid escape");
  16030. }
  16031. state.pos = start;
  16032. }
  16033. var ch = state.current();
  16034. if (ch !== 0x5D /* ] */) {
  16035. state.lastIntValue = ch;
  16036. state.advance();
  16037. return true
  16038. }
  16039. return false
  16040. };
  16041. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  16042. pp$8.regexp_eatClassEscape = function(state) {
  16043. var start = state.pos;
  16044. if (state.eat(0x62 /* b */)) {
  16045. state.lastIntValue = 0x08; /* <BS> */
  16046. return true
  16047. }
  16048. if (state.switchU && state.eat(0x2D /* - */)) {
  16049. state.lastIntValue = 0x2D; /* - */
  16050. return true
  16051. }
  16052. if (!state.switchU && state.eat(0x63 /* c */)) {
  16053. if (this.regexp_eatClassControlLetter(state)) {
  16054. return true
  16055. }
  16056. state.pos = start;
  16057. }
  16058. return (
  16059. this.regexp_eatCharacterClassEscape(state) ||
  16060. this.regexp_eatCharacterEscape(state)
  16061. )
  16062. };
  16063. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  16064. pp$8.regexp_eatClassControlLetter = function(state) {
  16065. var ch = state.current();
  16066. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  16067. state.lastIntValue = ch % 0x20;
  16068. state.advance();
  16069. return true
  16070. }
  16071. return false
  16072. };
  16073. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  16074. pp$8.regexp_eatHexEscapeSequence = function(state) {
  16075. var start = state.pos;
  16076. if (state.eat(0x78 /* x */)) {
  16077. if (this.regexp_eatFixedHexDigits(state, 2)) {
  16078. return true
  16079. }
  16080. if (state.switchU) {
  16081. state.raise("Invalid escape");
  16082. }
  16083. state.pos = start;
  16084. }
  16085. return false
  16086. };
  16087. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  16088. pp$8.regexp_eatDecimalDigits = function(state) {
  16089. var start = state.pos;
  16090. var ch = 0;
  16091. state.lastIntValue = 0;
  16092. while (isDecimalDigit(ch = state.current())) {
  16093. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  16094. state.advance();
  16095. }
  16096. return state.pos !== start
  16097. };
  16098. function isDecimalDigit(ch) {
  16099. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  16100. }
  16101. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  16102. pp$8.regexp_eatHexDigits = function(state) {
  16103. var start = state.pos;
  16104. var ch = 0;
  16105. state.lastIntValue = 0;
  16106. while (isHexDigit(ch = state.current())) {
  16107. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  16108. state.advance();
  16109. }
  16110. return state.pos !== start
  16111. };
  16112. function isHexDigit(ch) {
  16113. return (
  16114. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  16115. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  16116. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  16117. )
  16118. }
  16119. function hexToInt(ch) {
  16120. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  16121. return 10 + (ch - 0x41 /* A */)
  16122. }
  16123. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  16124. return 10 + (ch - 0x61 /* a */)
  16125. }
  16126. return ch - 0x30 /* 0 */
  16127. }
  16128. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  16129. // Allows only 0-377(octal) i.e. 0-255(decimal).
  16130. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  16131. if (this.regexp_eatOctalDigit(state)) {
  16132. var n1 = state.lastIntValue;
  16133. if (this.regexp_eatOctalDigit(state)) {
  16134. var n2 = state.lastIntValue;
  16135. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  16136. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  16137. } else {
  16138. state.lastIntValue = n1 * 8 + n2;
  16139. }
  16140. } else {
  16141. state.lastIntValue = n1;
  16142. }
  16143. return true
  16144. }
  16145. return false
  16146. };
  16147. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  16148. pp$8.regexp_eatOctalDigit = function(state) {
  16149. var ch = state.current();
  16150. if (isOctalDigit(ch)) {
  16151. state.lastIntValue = ch - 0x30; /* 0 */
  16152. state.advance();
  16153. return true
  16154. }
  16155. state.lastIntValue = 0;
  16156. return false
  16157. };
  16158. function isOctalDigit(ch) {
  16159. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  16160. }
  16161. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  16162. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  16163. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  16164. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  16165. var start = state.pos;
  16166. state.lastIntValue = 0;
  16167. for (var i = 0; i < length; ++i) {
  16168. var ch = state.current();
  16169. if (!isHexDigit(ch)) {
  16170. state.pos = start;
  16171. return false
  16172. }
  16173. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  16174. state.advance();
  16175. }
  16176. return true
  16177. };
  16178. // Object type used to represent tokens. Note that normally, tokens
  16179. // simply exist as properties on the parser object. This is only
  16180. // used for the onToken callback and the external tokenizer.
  16181. var Token = function Token(p) {
  16182. this.type = p.type;
  16183. this.value = p.value;
  16184. this.start = p.start;
  16185. this.end = p.end;
  16186. if (p.options.locations)
  16187. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  16188. if (p.options.ranges)
  16189. { this.range = [p.start, p.end]; }
  16190. };
  16191. // ## Tokenizer
  16192. var pp$9 = Parser.prototype;
  16193. // Move to the next token
  16194. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  16195. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  16196. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  16197. if (this.options.onToken)
  16198. { this.options.onToken(new Token(this)); }
  16199. this.lastTokEnd = this.end;
  16200. this.lastTokStart = this.start;
  16201. this.lastTokEndLoc = this.endLoc;
  16202. this.lastTokStartLoc = this.startLoc;
  16203. this.nextToken();
  16204. };
  16205. pp$9.getToken = function() {
  16206. this.next();
  16207. return new Token(this)
  16208. };
  16209. // If we're in an ES6 environment, make parsers iterable
  16210. if (typeof Symbol !== "undefined")
  16211. { pp$9[Symbol.iterator] = function() {
  16212. var this$1 = this;
  16213. return {
  16214. next: function () {
  16215. var token = this$1.getToken();
  16216. return {
  16217. done: token.type === types.eof,
  16218. value: token
  16219. }
  16220. }
  16221. }
  16222. }; }
  16223. // Toggle strict mode. Re-reads the next number or string to please
  16224. // pedantic tests (`"use strict"; 010;` should fail).
  16225. pp$9.curContext = function() {
  16226. return this.context[this.context.length - 1]
  16227. };
  16228. // Read a single token, updating the parser object's token-related
  16229. // properties.
  16230. pp$9.nextToken = function() {
  16231. var curContext = this.curContext();
  16232. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  16233. this.start = this.pos;
  16234. if (this.options.locations) { this.startLoc = this.curPosition(); }
  16235. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  16236. if (curContext.override) { return curContext.override(this) }
  16237. else { this.readToken(this.fullCharCodeAtPos()); }
  16238. };
  16239. pp$9.readToken = function(code) {
  16240. // Identifier or keyword. '\uXXXX' sequences are allowed in
  16241. // identifiers, so '\' also dispatches to that.
  16242. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  16243. { return this.readWord() }
  16244. return this.getTokenFromCode(code)
  16245. };
  16246. pp$9.fullCharCodeAtPos = function() {
  16247. var code = this.input.charCodeAt(this.pos);
  16248. if (code <= 0xd7ff || code >= 0xe000) { return code }
  16249. var next = this.input.charCodeAt(this.pos + 1);
  16250. return (code << 10) + next - 0x35fdc00
  16251. };
  16252. pp$9.skipBlockComment = function() {
  16253. var startLoc = this.options.onComment && this.curPosition();
  16254. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  16255. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  16256. this.pos = end + 2;
  16257. if (this.options.locations) {
  16258. lineBreakG.lastIndex = start;
  16259. var match;
  16260. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  16261. ++this.curLine;
  16262. this.lineStart = match.index + match[0].length;
  16263. }
  16264. }
  16265. if (this.options.onComment)
  16266. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  16267. startLoc, this.curPosition()); }
  16268. };
  16269. pp$9.skipLineComment = function(startSkip) {
  16270. var start = this.pos;
  16271. var startLoc = this.options.onComment && this.curPosition();
  16272. var ch = this.input.charCodeAt(this.pos += startSkip);
  16273. while (this.pos < this.input.length && !isNewLine(ch)) {
  16274. ch = this.input.charCodeAt(++this.pos);
  16275. }
  16276. if (this.options.onComment)
  16277. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  16278. startLoc, this.curPosition()); }
  16279. };
  16280. // Called at the start of the parse and after every token. Skips
  16281. // whitespace and comments, and.
  16282. pp$9.skipSpace = function() {
  16283. loop: while (this.pos < this.input.length) {
  16284. var ch = this.input.charCodeAt(this.pos);
  16285. switch (ch) {
  16286. case 32: case 160: // ' '
  16287. ++this.pos;
  16288. break
  16289. case 13:
  16290. if (this.input.charCodeAt(this.pos + 1) === 10) {
  16291. ++this.pos;
  16292. }
  16293. case 10: case 8232: case 8233:
  16294. ++this.pos;
  16295. if (this.options.locations) {
  16296. ++this.curLine;
  16297. this.lineStart = this.pos;
  16298. }
  16299. break
  16300. case 47: // '/'
  16301. switch (this.input.charCodeAt(this.pos + 1)) {
  16302. case 42: // '*'
  16303. this.skipBlockComment();
  16304. break
  16305. case 47:
  16306. this.skipLineComment(2);
  16307. break
  16308. default:
  16309. break loop
  16310. }
  16311. break
  16312. default:
  16313. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  16314. ++this.pos;
  16315. } else {
  16316. break loop
  16317. }
  16318. }
  16319. }
  16320. };
  16321. // Called at the end of every token. Sets `end`, `val`, and
  16322. // maintains `context` and `exprAllowed`, and skips the space after
  16323. // the token, so that the next one's `start` will point at the
  16324. // right position.
  16325. pp$9.finishToken = function(type, val) {
  16326. this.end = this.pos;
  16327. if (this.options.locations) { this.endLoc = this.curPosition(); }
  16328. var prevType = this.type;
  16329. this.type = type;
  16330. this.value = val;
  16331. this.updateContext(prevType);
  16332. };
  16333. // ### Token reading
  16334. // This is the function that is called to fetch the next token. It
  16335. // is somewhat obscure, because it works in character codes rather
  16336. // than characters, and because operator parsing has been inlined
  16337. // into it.
  16338. //
  16339. // All in the name of speed.
  16340. //
  16341. pp$9.readToken_dot = function() {
  16342. var next = this.input.charCodeAt(this.pos + 1);
  16343. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  16344. var next2 = this.input.charCodeAt(this.pos + 2);
  16345. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  16346. this.pos += 3;
  16347. return this.finishToken(types.ellipsis)
  16348. } else {
  16349. ++this.pos;
  16350. return this.finishToken(types.dot)
  16351. }
  16352. };
  16353. pp$9.readToken_slash = function() { // '/'
  16354. var next = this.input.charCodeAt(this.pos + 1);
  16355. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  16356. if (next === 61) { return this.finishOp(types.assign, 2) }
  16357. return this.finishOp(types.slash, 1)
  16358. };
  16359. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  16360. var next = this.input.charCodeAt(this.pos + 1);
  16361. var size = 1;
  16362. var tokentype = code === 42 ? types.star : types.modulo;
  16363. // exponentiation operator ** and **=
  16364. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  16365. ++size;
  16366. tokentype = types.starstar;
  16367. next = this.input.charCodeAt(this.pos + 2);
  16368. }
  16369. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  16370. return this.finishOp(tokentype, size)
  16371. };
  16372. pp$9.readToken_pipe_amp = function(code) { // '|&'
  16373. var next = this.input.charCodeAt(this.pos + 1);
  16374. if (next === code) {
  16375. if (this.options.ecmaVersion >= 12) {
  16376. var next2 = this.input.charCodeAt(this.pos + 2);
  16377. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  16378. }
  16379. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  16380. }
  16381. if (next === 61) { return this.finishOp(types.assign, 2) }
  16382. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  16383. };
  16384. pp$9.readToken_caret = function() { // '^'
  16385. var next = this.input.charCodeAt(this.pos + 1);
  16386. if (next === 61) { return this.finishOp(types.assign, 2) }
  16387. return this.finishOp(types.bitwiseXOR, 1)
  16388. };
  16389. pp$9.readToken_plus_min = function(code) { // '+-'
  16390. var next = this.input.charCodeAt(this.pos + 1);
  16391. if (next === code) {
  16392. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  16393. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  16394. // A `-->` line comment
  16395. this.skipLineComment(3);
  16396. this.skipSpace();
  16397. return this.nextToken()
  16398. }
  16399. return this.finishOp(types.incDec, 2)
  16400. }
  16401. if (next === 61) { return this.finishOp(types.assign, 2) }
  16402. return this.finishOp(types.plusMin, 1)
  16403. };
  16404. pp$9.readToken_lt_gt = function(code) { // '<>'
  16405. var next = this.input.charCodeAt(this.pos + 1);
  16406. var size = 1;
  16407. if (next === code) {
  16408. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  16409. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  16410. return this.finishOp(types.bitShift, size)
  16411. }
  16412. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  16413. this.input.charCodeAt(this.pos + 3) === 45) {
  16414. // `<!--`, an XML-style comment that should be interpreted as a line comment
  16415. this.skipLineComment(4);
  16416. this.skipSpace();
  16417. return this.nextToken()
  16418. }
  16419. if (next === 61) { size = 2; }
  16420. return this.finishOp(types.relational, size)
  16421. };
  16422. pp$9.readToken_eq_excl = function(code) { // '=!'
  16423. var next = this.input.charCodeAt(this.pos + 1);
  16424. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  16425. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  16426. this.pos += 2;
  16427. return this.finishToken(types.arrow)
  16428. }
  16429. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  16430. };
  16431. pp$9.readToken_question = function() { // '?'
  16432. var ecmaVersion = this.options.ecmaVersion;
  16433. if (ecmaVersion >= 11) {
  16434. var next = this.input.charCodeAt(this.pos + 1);
  16435. if (next === 46) {
  16436. var next2 = this.input.charCodeAt(this.pos + 2);
  16437. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  16438. }
  16439. if (next === 63) {
  16440. if (ecmaVersion >= 12) {
  16441. var next2$1 = this.input.charCodeAt(this.pos + 2);
  16442. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  16443. }
  16444. return this.finishOp(types.coalesce, 2)
  16445. }
  16446. }
  16447. return this.finishOp(types.question, 1)
  16448. };
  16449. pp$9.getTokenFromCode = function(code) {
  16450. switch (code) {
  16451. // The interpretation of a dot depends on whether it is followed
  16452. // by a digit or another two dots.
  16453. case 46: // '.'
  16454. return this.readToken_dot()
  16455. // Punctuation tokens.
  16456. case 40: ++this.pos; return this.finishToken(types.parenL)
  16457. case 41: ++this.pos; return this.finishToken(types.parenR)
  16458. case 59: ++this.pos; return this.finishToken(types.semi)
  16459. case 44: ++this.pos; return this.finishToken(types.comma)
  16460. case 91: ++this.pos; return this.finishToken(types.bracketL)
  16461. case 93: ++this.pos; return this.finishToken(types.bracketR)
  16462. case 123: ++this.pos; return this.finishToken(types.braceL)
  16463. case 125: ++this.pos; return this.finishToken(types.braceR)
  16464. case 58: ++this.pos; return this.finishToken(types.colon)
  16465. case 96: // '`'
  16466. if (this.options.ecmaVersion < 6) { break }
  16467. ++this.pos;
  16468. return this.finishToken(types.backQuote)
  16469. case 48: // '0'
  16470. var next = this.input.charCodeAt(this.pos + 1);
  16471. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  16472. if (this.options.ecmaVersion >= 6) {
  16473. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  16474. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  16475. }
  16476. // Anything else beginning with a digit is an integer, octal
  16477. // number, or float.
  16478. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  16479. return this.readNumber(false)
  16480. // Quotes produce strings.
  16481. case 34: case 39: // '"', "'"
  16482. return this.readString(code)
  16483. // Operators are parsed inline in tiny state machines. '=' (61) is
  16484. // often referred to. `finishOp` simply skips the amount of
  16485. // characters it is given as second argument, and returns a token
  16486. // of the type given by its first argument.
  16487. case 47: // '/'
  16488. return this.readToken_slash()
  16489. case 37: case 42: // '%*'
  16490. return this.readToken_mult_modulo_exp(code)
  16491. case 124: case 38: // '|&'
  16492. return this.readToken_pipe_amp(code)
  16493. case 94: // '^'
  16494. return this.readToken_caret()
  16495. case 43: case 45: // '+-'
  16496. return this.readToken_plus_min(code)
  16497. case 60: case 62: // '<>'
  16498. return this.readToken_lt_gt(code)
  16499. case 61: case 33: // '=!'
  16500. return this.readToken_eq_excl(code)
  16501. case 63: // '?'
  16502. return this.readToken_question()
  16503. case 126: // '~'
  16504. return this.finishOp(types.prefix, 1)
  16505. }
  16506. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  16507. };
  16508. pp$9.finishOp = function(type, size) {
  16509. var str = this.input.slice(this.pos, this.pos + size);
  16510. this.pos += size;
  16511. return this.finishToken(type, str)
  16512. };
  16513. pp$9.readRegexp = function() {
  16514. var escaped, inClass, start = this.pos;
  16515. for (;;) {
  16516. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  16517. var ch = this.input.charAt(this.pos);
  16518. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  16519. if (!escaped) {
  16520. if (ch === "[") { inClass = true; }
  16521. else if (ch === "]" && inClass) { inClass = false; }
  16522. else if (ch === "/" && !inClass) { break }
  16523. escaped = ch === "\\";
  16524. } else { escaped = false; }
  16525. ++this.pos;
  16526. }
  16527. var pattern = this.input.slice(start, this.pos);
  16528. ++this.pos;
  16529. var flagsStart = this.pos;
  16530. var flags = this.readWord1();
  16531. if (this.containsEsc) { this.unexpected(flagsStart); }
  16532. // Validate pattern
  16533. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  16534. state.reset(start, pattern, flags);
  16535. this.validateRegExpFlags(state);
  16536. this.validateRegExpPattern(state);
  16537. // Create Literal#value property value.
  16538. var value = null;
  16539. try {
  16540. value = new RegExp(pattern, flags);
  16541. } catch (e) {
  16542. // ESTree requires null if it failed to instantiate RegExp object.
  16543. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  16544. }
  16545. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  16546. };
  16547. // Read an integer in the given radix. Return null if zero digits
  16548. // were read, the integer value otherwise. When `len` is given, this
  16549. // will return `null` unless the integer has exactly `len` digits.
  16550. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  16551. // `len` is used for character escape sequences. In that case, disallow separators.
  16552. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  16553. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  16554. // and isn't fraction part nor exponent part. In that case, if the first digit
  16555. // is zero then disallow separators.
  16556. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  16557. var start = this.pos, total = 0, lastCode = 0;
  16558. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  16559. var code = this.input.charCodeAt(this.pos), val = (void 0);
  16560. if (allowSeparators && code === 95) {
  16561. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  16562. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  16563. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  16564. lastCode = code;
  16565. continue
  16566. }
  16567. if (code >= 97) { val = code - 97 + 10; } // a
  16568. else if (code >= 65) { val = code - 65 + 10; } // A
  16569. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  16570. else { val = Infinity; }
  16571. if (val >= radix) { break }
  16572. lastCode = code;
  16573. total = total * radix + val;
  16574. }
  16575. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  16576. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  16577. return total
  16578. };
  16579. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  16580. if (isLegacyOctalNumericLiteral) {
  16581. return parseInt(str, 8)
  16582. }
  16583. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  16584. return parseFloat(str.replace(/_/g, ""))
  16585. }
  16586. function stringToBigInt(str) {
  16587. if (typeof BigInt !== "function") {
  16588. return null
  16589. }
  16590. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  16591. return BigInt(str.replace(/_/g, ""))
  16592. }
  16593. pp$9.readRadixNumber = function(radix) {
  16594. var start = this.pos;
  16595. this.pos += 2; // 0x
  16596. var val = this.readInt(radix);
  16597. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  16598. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  16599. val = stringToBigInt(this.input.slice(start, this.pos));
  16600. ++this.pos;
  16601. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16602. return this.finishToken(types.num, val)
  16603. };
  16604. // Read an integer, octal integer, or floating-point number.
  16605. pp$9.readNumber = function(startsWithDot) {
  16606. var start = this.pos;
  16607. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  16608. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  16609. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  16610. var next = this.input.charCodeAt(this.pos);
  16611. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  16612. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  16613. ++this.pos;
  16614. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16615. return this.finishToken(types.num, val$1)
  16616. }
  16617. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  16618. if (next === 46 && !octal) { // '.'
  16619. ++this.pos;
  16620. this.readInt(10);
  16621. next = this.input.charCodeAt(this.pos);
  16622. }
  16623. if ((next === 69 || next === 101) && !octal) { // 'eE'
  16624. next = this.input.charCodeAt(++this.pos);
  16625. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  16626. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  16627. }
  16628. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16629. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  16630. return this.finishToken(types.num, val)
  16631. };
  16632. // Read a string value, interpreting backslash-escapes.
  16633. pp$9.readCodePoint = function() {
  16634. var ch = this.input.charCodeAt(this.pos), code;
  16635. if (ch === 123) { // '{'
  16636. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  16637. var codePos = ++this.pos;
  16638. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  16639. ++this.pos;
  16640. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  16641. } else {
  16642. code = this.readHexChar(4);
  16643. }
  16644. return code
  16645. };
  16646. function codePointToString$1(code) {
  16647. // UTF-16 Decoding
  16648. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  16649. code -= 0x10000;
  16650. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  16651. }
  16652. pp$9.readString = function(quote) {
  16653. var out = "", chunkStart = ++this.pos;
  16654. for (;;) {
  16655. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  16656. var ch = this.input.charCodeAt(this.pos);
  16657. if (ch === quote) { break }
  16658. if (ch === 92) { // '\'
  16659. out += this.input.slice(chunkStart, this.pos);
  16660. out += this.readEscapedChar(false);
  16661. chunkStart = this.pos;
  16662. } else {
  16663. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  16664. ++this.pos;
  16665. }
  16666. }
  16667. out += this.input.slice(chunkStart, this.pos++);
  16668. return this.finishToken(types.string, out)
  16669. };
  16670. // Reads template string tokens.
  16671. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  16672. pp$9.tryReadTemplateToken = function() {
  16673. this.inTemplateElement = true;
  16674. try {
  16675. this.readTmplToken();
  16676. } catch (err) {
  16677. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  16678. this.readInvalidTemplateToken();
  16679. } else {
  16680. throw err
  16681. }
  16682. }
  16683. this.inTemplateElement = false;
  16684. };
  16685. pp$9.invalidStringToken = function(position, message) {
  16686. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  16687. throw INVALID_TEMPLATE_ESCAPE_ERROR
  16688. } else {
  16689. this.raise(position, message);
  16690. }
  16691. };
  16692. pp$9.readTmplToken = function() {
  16693. var out = "", chunkStart = this.pos;
  16694. for (;;) {
  16695. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  16696. var ch = this.input.charCodeAt(this.pos);
  16697. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  16698. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  16699. if (ch === 36) {
  16700. this.pos += 2;
  16701. return this.finishToken(types.dollarBraceL)
  16702. } else {
  16703. ++this.pos;
  16704. return this.finishToken(types.backQuote)
  16705. }
  16706. }
  16707. out += this.input.slice(chunkStart, this.pos);
  16708. return this.finishToken(types.template, out)
  16709. }
  16710. if (ch === 92) { // '\'
  16711. out += this.input.slice(chunkStart, this.pos);
  16712. out += this.readEscapedChar(true);
  16713. chunkStart = this.pos;
  16714. } else if (isNewLine(ch)) {
  16715. out += this.input.slice(chunkStart, this.pos);
  16716. ++this.pos;
  16717. switch (ch) {
  16718. case 13:
  16719. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  16720. case 10:
  16721. out += "\n";
  16722. break
  16723. default:
  16724. out += String.fromCharCode(ch);
  16725. break
  16726. }
  16727. if (this.options.locations) {
  16728. ++this.curLine;
  16729. this.lineStart = this.pos;
  16730. }
  16731. chunkStart = this.pos;
  16732. } else {
  16733. ++this.pos;
  16734. }
  16735. }
  16736. };
  16737. // Reads a template token to search for the end, without validating any escape sequences
  16738. pp$9.readInvalidTemplateToken = function() {
  16739. for (; this.pos < this.input.length; this.pos++) {
  16740. switch (this.input[this.pos]) {
  16741. case "\\":
  16742. ++this.pos;
  16743. break
  16744. case "$":
  16745. if (this.input[this.pos + 1] !== "{") {
  16746. break
  16747. }
  16748. // falls through
  16749. case "`":
  16750. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  16751. // no default
  16752. }
  16753. }
  16754. this.raise(this.start, "Unterminated template");
  16755. };
  16756. // Used to read escaped characters
  16757. pp$9.readEscapedChar = function(inTemplate) {
  16758. var ch = this.input.charCodeAt(++this.pos);
  16759. ++this.pos;
  16760. switch (ch) {
  16761. case 110: return "\n" // 'n' -> '\n'
  16762. case 114: return "\r" // 'r' -> '\r'
  16763. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  16764. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  16765. case 116: return "\t" // 't' -> '\t'
  16766. case 98: return "\b" // 'b' -> '\b'
  16767. case 118: return "\u000b" // 'v' -> '\u000b'
  16768. case 102: return "\f" // 'f' -> '\f'
  16769. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  16770. case 10: // ' \n'
  16771. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  16772. return ""
  16773. case 56:
  16774. case 57:
  16775. if (this.strict) {
  16776. this.invalidStringToken(
  16777. this.pos - 1,
  16778. "Invalid escape sequence"
  16779. );
  16780. }
  16781. if (inTemplate) {
  16782. var codePos = this.pos - 1;
  16783. this.invalidStringToken(
  16784. codePos,
  16785. "Invalid escape sequence in template string"
  16786. );
  16787. return null
  16788. }
  16789. default:
  16790. if (ch >= 48 && ch <= 55) {
  16791. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  16792. var octal = parseInt(octalStr, 8);
  16793. if (octal > 255) {
  16794. octalStr = octalStr.slice(0, -1);
  16795. octal = parseInt(octalStr, 8);
  16796. }
  16797. this.pos += octalStr.length - 1;
  16798. ch = this.input.charCodeAt(this.pos);
  16799. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  16800. this.invalidStringToken(
  16801. this.pos - 1 - octalStr.length,
  16802. inTemplate
  16803. ? "Octal literal in template string"
  16804. : "Octal literal in strict mode"
  16805. );
  16806. }
  16807. return String.fromCharCode(octal)
  16808. }
  16809. if (isNewLine(ch)) {
  16810. // Unicode new line characters after \ get removed from output in both
  16811. // template literals and strings
  16812. return ""
  16813. }
  16814. return String.fromCharCode(ch)
  16815. }
  16816. };
  16817. // Used to read character escape sequences ('\x', '\u', '\U').
  16818. pp$9.readHexChar = function(len) {
  16819. var codePos = this.pos;
  16820. var n = this.readInt(16, len);
  16821. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  16822. return n
  16823. };
  16824. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  16825. // to whether the word contained a '\u' escape.
  16826. //
  16827. // Incrementally adds only escaped chars, adding other chunks as-is
  16828. // as a micro-optimization.
  16829. pp$9.readWord1 = function() {
  16830. this.containsEsc = false;
  16831. var word = "", first = true, chunkStart = this.pos;
  16832. var astral = this.options.ecmaVersion >= 6;
  16833. while (this.pos < this.input.length) {
  16834. var ch = this.fullCharCodeAtPos();
  16835. if (isIdentifierChar(ch, astral)) {
  16836. this.pos += ch <= 0xffff ? 1 : 2;
  16837. } else if (ch === 92) { // "\"
  16838. this.containsEsc = true;
  16839. word += this.input.slice(chunkStart, this.pos);
  16840. var escStart = this.pos;
  16841. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  16842. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  16843. ++this.pos;
  16844. var esc = this.readCodePoint();
  16845. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  16846. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  16847. word += codePointToString$1(esc);
  16848. chunkStart = this.pos;
  16849. } else {
  16850. break
  16851. }
  16852. first = false;
  16853. }
  16854. return word + this.input.slice(chunkStart, this.pos)
  16855. };
  16856. // Read an identifier or keyword token. Will check for reserved
  16857. // words when necessary.
  16858. pp$9.readWord = function() {
  16859. var word = this.readWord1();
  16860. var type = types.name;
  16861. if (this.keywords.test(word)) {
  16862. type = keywords$1[word];
  16863. }
  16864. return this.finishToken(type, word)
  16865. };
  16866. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  16867. var version = "8.0.5";
  16868. Parser.acorn = {
  16869. Parser: Parser,
  16870. version: version,
  16871. defaultOptions: defaultOptions,
  16872. Position: Position,
  16873. SourceLocation: SourceLocation,
  16874. getLineInfo: getLineInfo,
  16875. Node: Node,
  16876. TokenType: TokenType,
  16877. tokTypes: types,
  16878. keywordTypes: keywords$1,
  16879. TokContext: TokContext,
  16880. tokContexts: types$1,
  16881. isIdentifierChar: isIdentifierChar,
  16882. isIdentifierStart: isIdentifierStart,
  16883. Token: Token,
  16884. isNewLine: isNewLine,
  16885. lineBreak: lineBreak,
  16886. lineBreakG: lineBreakG,
  16887. nonASCIIwhitespace: nonASCIIwhitespace
  16888. };
  16889. // The main exported interface (under `self.acorn` when in the
  16890. // browser) is a `parse` function that takes a code string and
  16891. // returns an abstract syntax tree as specified by [Mozilla parser
  16892. // API][api].
  16893. //
  16894. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  16895. function parse(input, options) {
  16896. return Parser.parse(input, options)
  16897. }
  16898. // This function tries to parse a single expression at a given
  16899. // offset in a string. Useful for parsing mixed-language formats
  16900. // that embed JavaScript expressions.
  16901. function parseExpressionAt(input, pos, options) {
  16902. return Parser.parseExpressionAt(input, pos, options)
  16903. }
  16904. // Acorn is organized as a tokenizer and a recursive-descent parser.
  16905. // The `tokenizer` export provides an interface to the tokenizer.
  16906. function tokenizer(input, options) {
  16907. return Parser.tokenizer(input, options)
  16908. }
  16909. var acorn = {
  16910. __proto__: null,
  16911. Node: Node,
  16912. Parser: Parser,
  16913. Position: Position,
  16914. SourceLocation: SourceLocation,
  16915. TokContext: TokContext,
  16916. Token: Token,
  16917. TokenType: TokenType,
  16918. defaultOptions: defaultOptions,
  16919. getLineInfo: getLineInfo,
  16920. isIdentifierChar: isIdentifierChar,
  16921. isIdentifierStart: isIdentifierStart,
  16922. isNewLine: isNewLine,
  16923. keywordTypes: keywords$1,
  16924. lineBreak: lineBreak,
  16925. lineBreakG: lineBreakG,
  16926. nonASCIIwhitespace: nonASCIIwhitespace,
  16927. parse: parse,
  16928. parseExpressionAt: parseExpressionAt,
  16929. tokContexts: types$1,
  16930. tokTypes: types,
  16931. tokenizer: tokenizer,
  16932. version: version
  16933. };
  16934. class GlobalScope extends Scope$1 {
  16935. constructor() {
  16936. super();
  16937. this.variables.set('undefined', new UndefinedVariable());
  16938. }
  16939. findVariable(name) {
  16940. let variable = this.variables.get(name);
  16941. if (!variable) {
  16942. variable = new GlobalVariable(name);
  16943. this.variables.set(name, variable);
  16944. }
  16945. return variable;
  16946. }
  16947. }
  16948. const readFile = (file) => new Promise((fulfil, reject) => readFile$1(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
  16949. function mkdirpath(path) {
  16950. const dir = dirname(path);
  16951. try {
  16952. readdirSync(dir);
  16953. }
  16954. catch (err) {
  16955. mkdirpath(dir);
  16956. try {
  16957. mkdirSync(dir);
  16958. }
  16959. catch (err2) {
  16960. if (err2.code !== 'EEXIST') {
  16961. throw err2;
  16962. }
  16963. }
  16964. }
  16965. }
  16966. function writeFile(dest, data) {
  16967. return new Promise((fulfil, reject) => {
  16968. mkdirpath(dest);
  16969. writeFile$1(dest, data, err => {
  16970. if (err) {
  16971. reject(err);
  16972. }
  16973. else {
  16974. fulfil();
  16975. }
  16976. });
  16977. });
  16978. }
  16979. async function resolveId(source, importer, preserveSymlinks, pluginDriver, skip, customOptions) {
  16980. const pluginResult = await pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], null, skip);
  16981. if (pluginResult != null)
  16982. return pluginResult;
  16983. // external modules (non-entry modules that start with neither '.' or '/')
  16984. // are skipped at this stage.
  16985. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  16986. return null;
  16987. // `resolve` processes paths from right to left, prepending them until an
  16988. // absolute path is created. Absolute importees therefore shortcircuit the
  16989. // resolve call and require no special handing on our part.
  16990. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  16991. return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
  16992. }
  16993. function addJsExtensionIfNecessary(file, preserveSymlinks) {
  16994. let found = findFile(file, preserveSymlinks);
  16995. if (found)
  16996. return found;
  16997. found = findFile(file + '.mjs', preserveSymlinks);
  16998. if (found)
  16999. return found;
  17000. found = findFile(file + '.js', preserveSymlinks);
  17001. return found;
  17002. }
  17003. function findFile(file, preserveSymlinks) {
  17004. try {
  17005. const stats = lstatSync(file);
  17006. if (!preserveSymlinks && stats.isSymbolicLink())
  17007. return findFile(realpathSync(file), preserveSymlinks);
  17008. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  17009. // check case
  17010. const name = basename(file);
  17011. const files = readdirSync(dirname(file));
  17012. if (files.indexOf(name) !== -1)
  17013. return file;
  17014. }
  17015. }
  17016. catch (_a) {
  17017. // suppress
  17018. }
  17019. }
  17020. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  17021. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  17022. function throwPluginError(err, plugin, { hook, id } = {}) {
  17023. if (typeof err === 'string')
  17024. err = { message: err };
  17025. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  17026. err.pluginCode = err.code;
  17027. }
  17028. err.code = Errors.PLUGIN_ERROR;
  17029. err.plugin = plugin;
  17030. if (hook) {
  17031. err.hook = hook;
  17032. }
  17033. if (id) {
  17034. err.id = id;
  17035. }
  17036. return error(err);
  17037. }
  17038. const deprecatedHooks = [
  17039. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  17040. ];
  17041. function warnDeprecatedHooks(plugins, options) {
  17042. for (const { active, deprecated, replacement } of deprecatedHooks) {
  17043. for (const plugin of plugins) {
  17044. if (deprecated in plugin) {
  17045. warnDeprecation({
  17046. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  17047. plugin: plugin.name
  17048. }, active, options);
  17049. }
  17050. }
  17051. }
  17052. }
  17053. function createPluginCache(cache) {
  17054. return {
  17055. has(id) {
  17056. const item = cache[id];
  17057. if (!item)
  17058. return false;
  17059. item[0] = 0;
  17060. return true;
  17061. },
  17062. get(id) {
  17063. const item = cache[id];
  17064. if (!item)
  17065. return undefined;
  17066. item[0] = 0;
  17067. return item[1];
  17068. },
  17069. set(id, value) {
  17070. cache[id] = [0, value];
  17071. },
  17072. delete(id) {
  17073. return delete cache[id];
  17074. }
  17075. };
  17076. }
  17077. function getTrackedPluginCache(pluginCache, onUse) {
  17078. return {
  17079. has(id) {
  17080. onUse();
  17081. return pluginCache.has(id);
  17082. },
  17083. get(id) {
  17084. onUse();
  17085. return pluginCache.get(id);
  17086. },
  17087. set(id, value) {
  17088. onUse();
  17089. return pluginCache.set(id, value);
  17090. },
  17091. delete(id) {
  17092. onUse();
  17093. return pluginCache.delete(id);
  17094. }
  17095. };
  17096. }
  17097. const NO_CACHE = {
  17098. has() {
  17099. return false;
  17100. },
  17101. get() {
  17102. return undefined;
  17103. },
  17104. set() { },
  17105. delete() {
  17106. return false;
  17107. }
  17108. };
  17109. function uncacheablePluginError(pluginName) {
  17110. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  17111. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  17112. return error({
  17113. code: 'ANONYMOUS_PLUGIN_CACHE',
  17114. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  17115. });
  17116. }
  17117. return error({
  17118. code: 'DUPLICATE_PLUGIN_NAME',
  17119. 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).`
  17120. });
  17121. }
  17122. function getCacheForUncacheablePlugin(pluginName) {
  17123. return {
  17124. has() {
  17125. return uncacheablePluginError(pluginName);
  17126. },
  17127. get() {
  17128. return uncacheablePluginError(pluginName);
  17129. },
  17130. set() {
  17131. return uncacheablePluginError(pluginName);
  17132. },
  17133. delete() {
  17134. return uncacheablePluginError(pluginName);
  17135. }
  17136. };
  17137. }
  17138. function transform(source, module, pluginDriver, warn) {
  17139. const id = module.id;
  17140. const sourcemapChain = [];
  17141. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  17142. const originalCode = source.code;
  17143. let ast = source.ast;
  17144. const transformDependencies = [];
  17145. const emittedFiles = [];
  17146. let customTransformCache = false;
  17147. const useCustomTransformCache = () => (customTransformCache = true);
  17148. let curPlugin;
  17149. const curSource = source.code;
  17150. function transformReducer(previousCode, result, plugin) {
  17151. let code;
  17152. let map;
  17153. if (typeof result === 'string') {
  17154. code = result;
  17155. }
  17156. else if (result && typeof result === 'object') {
  17157. module.updateOptions(result);
  17158. if (result.code == null) {
  17159. if (result.map || result.ast) {
  17160. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  17161. }
  17162. return previousCode;
  17163. }
  17164. ({ code, map, ast } = result);
  17165. }
  17166. else {
  17167. return previousCode;
  17168. }
  17169. // strict null check allows 'null' maps to not be pushed to the chain,
  17170. // while 'undefined' gets the missing map warning
  17171. if (map !== null) {
  17172. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  17173. missing: true,
  17174. plugin: plugin.name
  17175. });
  17176. }
  17177. return code;
  17178. }
  17179. return pluginDriver
  17180. .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  17181. curPlugin = plugin;
  17182. return {
  17183. ...pluginContext,
  17184. cache: customTransformCache
  17185. ? pluginContext.cache
  17186. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  17187. warn(warning, pos) {
  17188. if (typeof warning === 'string')
  17189. warning = { message: warning };
  17190. if (pos)
  17191. augmentCodeLocation(warning, pos, curSource, id);
  17192. warning.id = id;
  17193. warning.hook = 'transform';
  17194. pluginContext.warn(warning);
  17195. },
  17196. error(err, pos) {
  17197. if (typeof err === 'string')
  17198. err = { message: err };
  17199. if (pos)
  17200. augmentCodeLocation(err, pos, curSource, id);
  17201. err.id = id;
  17202. err.hook = 'transform';
  17203. return pluginContext.error(err);
  17204. },
  17205. emitAsset(name, source) {
  17206. emittedFiles.push({ type: 'asset', name, source });
  17207. return pluginContext.emitAsset(name, source);
  17208. },
  17209. emitChunk(id, options) {
  17210. emittedFiles.push({ type: 'chunk', id, name: options && options.name });
  17211. return pluginContext.emitChunk(id, options);
  17212. },
  17213. emitFile(emittedFile) {
  17214. emittedFiles.push(emittedFile);
  17215. return pluginDriver.emitFile(emittedFile);
  17216. },
  17217. addWatchFile(id) {
  17218. transformDependencies.push(id);
  17219. pluginContext.addWatchFile(id);
  17220. },
  17221. setAssetSource() {
  17222. return this.error({
  17223. code: 'INVALID_SETASSETSOURCE',
  17224. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  17225. });
  17226. },
  17227. getCombinedSourcemap() {
  17228. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  17229. if (!combinedMap) {
  17230. const magicString = new MagicString(originalCode);
  17231. return magicString.generateMap({ includeContent: true, hires: true, source: id });
  17232. }
  17233. if (originalSourcemap !== combinedMap) {
  17234. originalSourcemap = combinedMap;
  17235. sourcemapChain.length = 0;
  17236. }
  17237. return new SourceMap({
  17238. ...combinedMap,
  17239. file: null,
  17240. sourcesContent: combinedMap.sourcesContent
  17241. });
  17242. }
  17243. };
  17244. })
  17245. .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
  17246. .then(code => {
  17247. if (!customTransformCache) {
  17248. // files emitted by a transform hook need to be emitted again if the hook is skipped
  17249. if (emittedFiles.length)
  17250. module.transformFiles = emittedFiles;
  17251. }
  17252. return {
  17253. ast,
  17254. code,
  17255. customTransformCache,
  17256. meta: module.info.meta,
  17257. originalCode,
  17258. originalSourcemap,
  17259. sourcemapChain,
  17260. transformDependencies
  17261. };
  17262. });
  17263. }
  17264. class ModuleLoader {
  17265. constructor(graph, modulesById, options, pluginDriver) {
  17266. this.graph = graph;
  17267. this.modulesById = modulesById;
  17268. this.options = options;
  17269. this.pluginDriver = pluginDriver;
  17270. this.implicitEntryModules = new Set();
  17271. this.indexedEntryModules = [];
  17272. this.latestLoadModulesPromise = Promise.resolve();
  17273. this.nextEntryModuleIndex = 0;
  17274. this.hasModuleSideEffects = options.treeshake
  17275. ? options.treeshake.moduleSideEffects
  17276. : () => true;
  17277. }
  17278. async addAdditionalModules(unresolvedModules) {
  17279. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  17280. await this.awaitLoadModulesPromise();
  17281. return result;
  17282. }
  17283. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  17284. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  17285. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  17286. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  17287. let moduleIndex = firstEntryModuleIndex;
  17288. for (let index = 0; index < entryModules.length; index++) {
  17289. const entryModule = entryModules[index];
  17290. entryModule.isUserDefinedEntryPoint =
  17291. entryModule.isUserDefinedEntryPoint || isUserDefined;
  17292. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
  17293. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  17294. if (!existingIndexedModule) {
  17295. this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
  17296. }
  17297. else {
  17298. existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
  17299. }
  17300. moduleIndex++;
  17301. }
  17302. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  17303. return entryModules;
  17304. }));
  17305. await this.awaitLoadModulesPromise();
  17306. return {
  17307. entryModules: this.indexedEntryModules.map(({ module }) => module),
  17308. implicitEntryModules: [...this.implicitEntryModules],
  17309. newEntryModules
  17310. };
  17311. }
  17312. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  17313. const unresolvedModule = {
  17314. fileName: fileName || null,
  17315. id,
  17316. importer,
  17317. name: name || null
  17318. };
  17319. const module = implicitlyLoadedAfterOneOf
  17320. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  17321. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  17322. if (preserveSignature != null) {
  17323. module.preserveSignature = preserveSignature;
  17324. }
  17325. return module;
  17326. }
  17327. async resolveId(source, importer, customOptions, skip = null) {
  17328. return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  17329. ? false
  17330. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, skip, customOptions), importer, source));
  17331. }
  17332. addDefaultsToResolvedId(resolvedId) {
  17333. var _a, _b;
  17334. if (!resolvedId) {
  17335. return null;
  17336. }
  17337. const external = resolvedId.external || false;
  17338. return {
  17339. external,
  17340. id: resolvedId.id,
  17341. meta: resolvedId.meta || EMPTY_OBJECT,
  17342. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, external),
  17343. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  17344. };
  17345. }
  17346. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  17347. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  17348. addChunkNamesToModule(entryModule, unresolvedModule, false);
  17349. if (!entryModule.info.isEntry) {
  17350. this.implicitEntryModules.add(entryModule);
  17351. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  17352. for (const module of implicitlyLoadedAfterModules) {
  17353. entryModule.implicitlyLoadedAfter.add(module);
  17354. }
  17355. for (const dependant of entryModule.implicitlyLoadedAfter) {
  17356. dependant.implicitlyLoadedBefore.add(entryModule);
  17357. }
  17358. }
  17359. return entryModule;
  17360. }));
  17361. }
  17362. async addModuleSource(id, importer, module) {
  17363. var _a;
  17364. timeStart('load modules', 3);
  17365. let source;
  17366. try {
  17367. source = (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id));
  17368. }
  17369. catch (err) {
  17370. timeEnd('load modules', 3);
  17371. let msg = `Could not load ${id}`;
  17372. if (importer)
  17373. msg += ` (imported by ${relativeId(importer)})`;
  17374. msg += `: ${err.message}`;
  17375. err.message = msg;
  17376. throw err;
  17377. }
  17378. timeEnd('load modules', 3);
  17379. const sourceDescription = typeof source === 'string'
  17380. ? { code: source }
  17381. : typeof source === 'object' && typeof source.code === 'string'
  17382. ? source
  17383. : error(errBadLoader(id));
  17384. const cachedModule = this.graph.cachedModules.get(id);
  17385. if (cachedModule &&
  17386. !cachedModule.customTransformCache &&
  17387. cachedModule.originalCode === sourceDescription.code) {
  17388. if (cachedModule.transformFiles) {
  17389. for (const emittedFile of cachedModule.transformFiles)
  17390. this.pluginDriver.emitFile(emittedFile);
  17391. }
  17392. module.setSource(cachedModule);
  17393. }
  17394. else {
  17395. module.updateOptions(sourceDescription);
  17396. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  17397. }
  17398. }
  17399. async awaitLoadModulesPromise() {
  17400. let startingPromise;
  17401. do {
  17402. startingPromise = this.latestLoadModulesPromise;
  17403. await startingPromise;
  17404. } while (startingPromise !== this.latestLoadModulesPromise);
  17405. }
  17406. extendLoadModulesPromise(loadNewModulesPromise) {
  17407. this.latestLoadModulesPromise = Promise.all([
  17408. loadNewModulesPromise,
  17409. this.latestLoadModulesPromise
  17410. ]);
  17411. this.latestLoadModulesPromise.catch(() => {
  17412. /* Avoid unhandled Promise rejections */
  17413. });
  17414. return loadNewModulesPromise;
  17415. }
  17416. async fetchDynamicDependencies(module) {
  17417. const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
  17418. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  17419. ? dynamicImport.argument
  17420. : dynamicImport.argument.esTreeNode, module.id);
  17421. if (resolvedId === null)
  17422. return null;
  17423. if (typeof resolvedId === 'string') {
  17424. dynamicImport.resolution = resolvedId;
  17425. return null;
  17426. }
  17427. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  17428. }));
  17429. for (const dependency of dependencies) {
  17430. if (dependency) {
  17431. module.dynamicDependencies.add(dependency);
  17432. dependency.dynamicImporters.push(module.id);
  17433. }
  17434. }
  17435. }
  17436. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
  17437. const existingModule = this.modulesById.get(id);
  17438. if (existingModule instanceof Module) {
  17439. if (isEntry) {
  17440. existingModule.info.isEntry = true;
  17441. this.implicitEntryModules.delete(existingModule);
  17442. for (const dependant of existingModule.implicitlyLoadedAfter) {
  17443. dependant.implicitlyLoadedBefore.delete(existingModule);
  17444. }
  17445. existingModule.implicitlyLoadedAfter.clear();
  17446. }
  17447. return existingModule;
  17448. }
  17449. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  17450. this.modulesById.set(id, module);
  17451. this.graph.watchFiles[id] = true;
  17452. await this.addModuleSource(id, importer, module);
  17453. await this.pluginDriver.hookParallel('moduleParsed', [module.info]);
  17454. await Promise.all([
  17455. this.fetchStaticDependencies(module),
  17456. this.fetchDynamicDependencies(module)
  17457. ]);
  17458. module.linkImports();
  17459. return module;
  17460. }
  17461. fetchResolvedDependency(source, importer, resolvedId) {
  17462. if (resolvedId.external) {
  17463. if (!this.modulesById.has(resolvedId.id)) {
  17464. this.modulesById.set(resolvedId.id, new ExternalModule(this.options, resolvedId.id, resolvedId.moduleSideEffects, resolvedId.meta));
  17465. }
  17466. const externalModule = this.modulesById.get(resolvedId.id);
  17467. if (!(externalModule instanceof ExternalModule)) {
  17468. return error(errInternalIdCannotBeExternal(source, importer));
  17469. }
  17470. return Promise.resolve(externalModule);
  17471. }
  17472. else {
  17473. return this.fetchModule(resolvedId, importer, false);
  17474. }
  17475. }
  17476. async fetchStaticDependencies(module) {
  17477. for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
  17478. module.resolvedIds[source] ||
  17479. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
  17480. module.dependencies.add(dependency);
  17481. dependency.importers.push(module.id);
  17482. }
  17483. }
  17484. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  17485. if (resolveIdResult) {
  17486. if (typeof resolveIdResult === 'object') {
  17487. return {
  17488. ...resolveIdResult,
  17489. external: resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true)
  17490. };
  17491. }
  17492. const external = this.options.external(resolveIdResult, importer, true);
  17493. return {
  17494. external,
  17495. id: external ? normalizeRelativeExternalId(resolveIdResult, importer) : resolveIdResult
  17496. };
  17497. }
  17498. const id = normalizeRelativeExternalId(source, importer);
  17499. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  17500. return null;
  17501. }
  17502. return {
  17503. external: true,
  17504. id
  17505. };
  17506. }
  17507. handleResolveId(resolvedId, source, importer) {
  17508. if (resolvedId === null) {
  17509. if (isRelative(source)) {
  17510. return error(errUnresolvedImport(source, importer));
  17511. }
  17512. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  17513. return {
  17514. external: true,
  17515. id: source,
  17516. meta: EMPTY_OBJECT,
  17517. moduleSideEffects: this.hasModuleSideEffects(source, true),
  17518. syntheticNamedExports: false
  17519. };
  17520. }
  17521. else {
  17522. if (resolvedId.external && resolvedId.syntheticNamedExports) {
  17523. this.options.onwarn(errExternalSyntheticExports(source, importer));
  17524. }
  17525. }
  17526. return resolvedId;
  17527. }
  17528. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  17529. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, null, EMPTY_OBJECT);
  17530. if (resolveIdResult == null) {
  17531. return error(implicitlyLoadedBefore === null
  17532. ? errUnresolvedEntry(unresolvedId)
  17533. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  17534. }
  17535. if (resolveIdResult === false ||
  17536. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  17537. return error(implicitlyLoadedBefore === null
  17538. ? errEntryCannotBeExternal(unresolvedId)
  17539. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  17540. }
  17541. return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object' ? resolveIdResult : { id: resolveIdResult }), undefined, isEntry);
  17542. }
  17543. async resolveDynamicImport(module, specifier, importer) {
  17544. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  17545. specifier,
  17546. importer
  17547. ]);
  17548. if (typeof specifier !== 'string') {
  17549. if (typeof resolution === 'string') {
  17550. return resolution;
  17551. }
  17552. if (!resolution) {
  17553. return null;
  17554. }
  17555. return {
  17556. external: false,
  17557. moduleSideEffects: true,
  17558. ...resolution
  17559. };
  17560. }
  17561. if (resolution == null) {
  17562. return (module.resolvedIds[specifier] =
  17563. module.resolvedIds[specifier] ||
  17564. this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
  17565. }
  17566. return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  17567. }
  17568. }
  17569. function normalizeRelativeExternalId(source, importer) {
  17570. return isRelative(source)
  17571. ? importer
  17572. ? resolve(importer, '..', source)
  17573. : resolve(source)
  17574. : source;
  17575. }
  17576. function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
  17577. if (fileName !== null) {
  17578. module.chunkFileNames.add(fileName);
  17579. }
  17580. else if (name !== null) {
  17581. if (module.chunkName === null) {
  17582. module.chunkName = name;
  17583. }
  17584. if (isUserDefined) {
  17585. module.userChunkNames.add(name);
  17586. }
  17587. }
  17588. }
  17589. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  17590. let deprecationWarningShown = false;
  17591. return ((...args) => {
  17592. if (!deprecationWarningShown) {
  17593. deprecationWarningShown = true;
  17594. warnDeprecation({
  17595. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  17596. plugin: pluginName
  17597. }, activeDeprecation, options);
  17598. }
  17599. return handler(...args);
  17600. });
  17601. }
  17602. function getPluginContexts(pluginCache, graph, options, fileEmitter) {
  17603. const existingPluginNames = new Set();
  17604. return (plugin, pidx) => {
  17605. let cacheable = true;
  17606. if (typeof plugin.cacheKey !== 'string') {
  17607. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  17608. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  17609. existingPluginNames.has(plugin.name)) {
  17610. cacheable = false;
  17611. }
  17612. else {
  17613. existingPluginNames.add(plugin.name);
  17614. }
  17615. }
  17616. let cacheInstance;
  17617. if (!pluginCache) {
  17618. cacheInstance = NO_CACHE;
  17619. }
  17620. else if (cacheable) {
  17621. const cacheKey = plugin.cacheKey || plugin.name;
  17622. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  17623. }
  17624. else {
  17625. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  17626. }
  17627. const context = {
  17628. addWatchFile(id) {
  17629. if (graph.phase >= BuildPhase.GENERATE) {
  17630. return this.error(errInvalidRollupPhaseForAddWatchFile());
  17631. }
  17632. graph.watchFiles[id] = true;
  17633. },
  17634. cache: cacheInstance,
  17635. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, true, options),
  17636. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, true, options),
  17637. emitFile: fileEmitter.emitFile,
  17638. error(err) {
  17639. return throwPluginError(err, plugin.name);
  17640. },
  17641. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  17642. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  17643. getFileName: fileEmitter.getFileName,
  17644. getModuleIds: () => graph.modulesById.keys(),
  17645. getModuleInfo: graph.getModuleInfo,
  17646. getWatchFiles: () => Object.keys(graph.watchFiles),
  17647. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  17648. meta: {
  17649. rollupVersion: version$1,
  17650. watchMode: graph.watchMode
  17651. },
  17652. get moduleIds() {
  17653. function* wrappedModuleIds() {
  17654. warnDeprecation({
  17655. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  17656. plugin: plugin.name
  17657. }, false, options);
  17658. yield* moduleIds;
  17659. }
  17660. const moduleIds = graph.modulesById.keys();
  17661. return wrappedModuleIds();
  17662. },
  17663. parse: graph.contextParse,
  17664. resolve(source, importer, { custom, skipSelf } = BLANK) {
  17665. return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null);
  17666. },
  17667. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  17668. .resolveId(source, importer, BLANK)
  17669. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  17670. setAssetSource: fileEmitter.setAssetSource,
  17671. warn(warning) {
  17672. if (typeof warning === 'string')
  17673. warning = { message: warning };
  17674. if (warning.code)
  17675. warning.pluginCode = warning.code;
  17676. warning.code = 'PLUGIN_WARNING';
  17677. warning.plugin = plugin.name;
  17678. options.onwarn(warning);
  17679. }
  17680. };
  17681. return context;
  17682. };
  17683. }
  17684. const inputHookNames = {
  17685. buildEnd: 1,
  17686. buildStart: 1,
  17687. closeBundle: 1,
  17688. closeWatcher: 1,
  17689. load: 1,
  17690. moduleParsed: 1,
  17691. options: 1,
  17692. resolveDynamicImport: 1,
  17693. resolveId: 1,
  17694. transform: 1,
  17695. watchChange: 1
  17696. };
  17697. const inputHooks = Object.keys(inputHookNames);
  17698. function throwInvalidHookError(hookName, pluginName) {
  17699. return error({
  17700. code: 'INVALID_PLUGIN_HOOK',
  17701. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  17702. });
  17703. }
  17704. class PluginDriver {
  17705. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  17706. this.graph = graph;
  17707. this.options = options;
  17708. warnDeprecatedHooks(userPlugins, options);
  17709. this.pluginCache = pluginCache;
  17710. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  17711. this.emitFile = this.fileEmitter.emitFile;
  17712. this.getFileName = this.fileEmitter.getFileName;
  17713. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
  17714. this.setOutputBundle = this.fileEmitter.setOutputBundle;
  17715. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  17716. this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, options, this.fileEmitter));
  17717. if (basePluginDriver) {
  17718. for (const plugin of userPlugins) {
  17719. for (const hook of inputHooks) {
  17720. if (hook in plugin) {
  17721. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  17722. }
  17723. }
  17724. }
  17725. }
  17726. }
  17727. createOutputPluginDriver(plugins) {
  17728. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  17729. }
  17730. // chains, first non-null result stops and returns
  17731. hookFirst(hookName, args, replaceContext, skip) {
  17732. let promise = Promise.resolve(undefined);
  17733. for (let i = 0; i < this.plugins.length; i++) {
  17734. if (skip === i)
  17735. continue;
  17736. promise = promise.then(result => {
  17737. if (result != null)
  17738. return result;
  17739. return this.runHook(hookName, args, i, false, replaceContext);
  17740. });
  17741. }
  17742. return promise;
  17743. }
  17744. // chains synchronously, first non-null result stops and returns
  17745. hookFirstSync(hookName, args, replaceContext) {
  17746. for (let i = 0; i < this.plugins.length; i++) {
  17747. const result = this.runHookSync(hookName, args, i, replaceContext);
  17748. if (result != null)
  17749. return result;
  17750. }
  17751. return null;
  17752. }
  17753. // parallel, ignores returns
  17754. hookParallel(hookName, args, replaceContext) {
  17755. const promises = [];
  17756. for (let i = 0; i < this.plugins.length; i++) {
  17757. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  17758. if (!hookPromise)
  17759. continue;
  17760. promises.push(hookPromise);
  17761. }
  17762. return Promise.all(promises).then(() => { });
  17763. }
  17764. // chains, reduces returned value, handling the reduced value as the first hook argument
  17765. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  17766. let promise = Promise.resolve(arg0);
  17767. for (let i = 0; i < this.plugins.length; i++) {
  17768. promise = promise.then(arg0 => {
  17769. const args = [arg0, ...rest];
  17770. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  17771. if (!hookPromise)
  17772. return arg0;
  17773. return hookPromise.then(result => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
  17774. });
  17775. }
  17776. return promise;
  17777. }
  17778. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  17779. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  17780. for (let i = 0; i < this.plugins.length; i++) {
  17781. const args = [arg0, ...rest];
  17782. const result = this.runHookSync(hookName, args, i, replaceContext);
  17783. arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
  17784. }
  17785. return arg0;
  17786. }
  17787. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  17788. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  17789. let promise = Promise.resolve(initialValue);
  17790. for (let i = 0; i < this.plugins.length; i++) {
  17791. promise = promise.then(value => {
  17792. const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
  17793. if (!hookPromise)
  17794. return value;
  17795. return hookPromise.then(result => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
  17796. });
  17797. }
  17798. return promise;
  17799. }
  17800. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  17801. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  17802. let acc = initialValue;
  17803. for (let i = 0; i < this.plugins.length; i++) {
  17804. const result = this.runHookSync(hookName, args, i, replaceContext);
  17805. acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
  17806. }
  17807. return acc;
  17808. }
  17809. // chains, ignores returns
  17810. hookSeq(hookName, args, replaceContext) {
  17811. let promise = Promise.resolve();
  17812. for (let i = 0; i < this.plugins.length; i++) {
  17813. promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
  17814. }
  17815. return promise;
  17816. }
  17817. // chains synchronously, ignores returns
  17818. hookSeqSync(hookName, args, replaceContext) {
  17819. for (let i = 0; i < this.plugins.length; i++) {
  17820. this.runHookSync(hookName, args, i, replaceContext);
  17821. }
  17822. }
  17823. runHook(hookName, args, pluginIndex, permitValues, hookContext) {
  17824. const plugin = this.plugins[pluginIndex];
  17825. const hook = plugin[hookName];
  17826. if (!hook)
  17827. return undefined;
  17828. let context = this.pluginContexts[pluginIndex];
  17829. if (hookContext) {
  17830. context = hookContext(context, plugin);
  17831. }
  17832. return Promise.resolve()
  17833. .then(() => {
  17834. // permit values allows values to be returned instead of a functional hook
  17835. if (typeof hook !== 'function') {
  17836. if (permitValues)
  17837. return hook;
  17838. return throwInvalidHookError(hookName, plugin.name);
  17839. }
  17840. return hook.apply(context, args);
  17841. })
  17842. .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
  17843. }
  17844. /**
  17845. * Run a sync plugin hook and return the result.
  17846. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  17847. * @param args Arguments passed to the plugin hook.
  17848. * @param pluginIndex Index of the plugin inside `this.plugins[]`.
  17849. * @param hookContext When passed, the plugin context can be overridden.
  17850. */
  17851. runHookSync(hookName, args, pluginIndex, hookContext) {
  17852. const plugin = this.plugins[pluginIndex];
  17853. const hook = plugin[hookName];
  17854. if (!hook)
  17855. return undefined;
  17856. let context = this.pluginContexts[pluginIndex];
  17857. if (hookContext) {
  17858. context = hookContext(context, plugin);
  17859. }
  17860. try {
  17861. // permit values allows values to be returned instead of a functional hook
  17862. if (typeof hook !== 'function') {
  17863. return throwInvalidHookError(hookName, plugin.name);
  17864. }
  17865. return hook.apply(context, args);
  17866. }
  17867. catch (err) {
  17868. return throwPluginError(err, plugin.name, { hook: hookName });
  17869. }
  17870. }
  17871. }
  17872. function normalizeEntryModules(entryModules) {
  17873. if (Array.isArray(entryModules)) {
  17874. return entryModules.map(id => ({
  17875. fileName: null,
  17876. id,
  17877. implicitlyLoadedAfter: [],
  17878. importer: undefined,
  17879. name: null
  17880. }));
  17881. }
  17882. return Object.keys(entryModules).map(name => ({
  17883. fileName: null,
  17884. id: entryModules[name],
  17885. implicitlyLoadedAfter: [],
  17886. importer: undefined,
  17887. name
  17888. }));
  17889. }
  17890. class Graph {
  17891. constructor(options, watcher) {
  17892. var _a, _b;
  17893. this.options = options;
  17894. this.entryModules = [];
  17895. this.modulesById = new Map();
  17896. this.needsTreeshakingPass = false;
  17897. this.phase = BuildPhase.LOAD_AND_PARSE;
  17898. this.watchFiles = Object.create(null);
  17899. this.watchMode = false;
  17900. this.externalModules = [];
  17901. this.implicitEntryModules = [];
  17902. this.modules = [];
  17903. this.getModuleInfo = (moduleId) => {
  17904. const foundModule = this.modulesById.get(moduleId);
  17905. if (!foundModule)
  17906. return null;
  17907. return foundModule.info;
  17908. };
  17909. this.deoptimizationTracker = new PathTracker();
  17910. this.cachedModules = new Map();
  17911. if (options.cache !== false) {
  17912. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  17913. for (const module of options.cache.modules)
  17914. this.cachedModules.set(module.id, module);
  17915. }
  17916. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  17917. // increment access counter
  17918. for (const name in this.pluginCache) {
  17919. const cache = this.pluginCache[name];
  17920. for (const key of Object.keys(cache))
  17921. cache[key][0]++;
  17922. }
  17923. }
  17924. this.contextParse = (code, options = {}) => this.acornParser.parse(code, {
  17925. ...this.options.acorn,
  17926. ...options
  17927. });
  17928. if (watcher) {
  17929. this.watchMode = true;
  17930. const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
  17931. const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
  17932. watcher.on('change', handleChange);
  17933. watcher.on('close', handleClose);
  17934. watcher.once('restart', () => {
  17935. watcher.removeListener('change', handleChange);
  17936. watcher.removeListener('close', handleClose);
  17937. });
  17938. }
  17939. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  17940. this.scope = new GlobalScope();
  17941. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  17942. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  17943. }
  17944. async build() {
  17945. timeStart('generate module graph', 2);
  17946. await this.generateModuleGraph();
  17947. timeEnd('generate module graph', 2);
  17948. timeStart('sort modules', 2);
  17949. this.phase = BuildPhase.ANALYSE;
  17950. this.sortModules();
  17951. timeEnd('sort modules', 2);
  17952. timeStart('mark included statements', 2);
  17953. this.includeStatements();
  17954. timeEnd('mark included statements', 2);
  17955. this.phase = BuildPhase.GENERATE;
  17956. }
  17957. getCache() {
  17958. // handle plugin cache eviction
  17959. for (const name in this.pluginCache) {
  17960. const cache = this.pluginCache[name];
  17961. let allDeleted = true;
  17962. for (const key of Object.keys(cache)) {
  17963. if (cache[key][0] >= this.options.experimentalCacheExpiry)
  17964. delete cache[key];
  17965. else
  17966. allDeleted = false;
  17967. }
  17968. if (allDeleted)
  17969. delete this.pluginCache[name];
  17970. }
  17971. return {
  17972. modules: this.modules.map(module => module.toJSON()),
  17973. plugins: this.pluginCache
  17974. };
  17975. }
  17976. async generateModuleGraph() {
  17977. ({
  17978. entryModules: this.entryModules,
  17979. implicitEntryModules: this.implicitEntryModules
  17980. } = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  17981. if (this.entryModules.length === 0) {
  17982. throw new Error('You must supply options.input to rollup');
  17983. }
  17984. for (const module of this.modulesById.values()) {
  17985. if (module instanceof Module) {
  17986. this.modules.push(module);
  17987. }
  17988. else {
  17989. this.externalModules.push(module);
  17990. }
  17991. }
  17992. }
  17993. includeStatements() {
  17994. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  17995. if (module.preserveSignature !== false) {
  17996. module.includeAllExports(false);
  17997. }
  17998. else {
  17999. markModuleAndImpureDependenciesAsExecuted(module);
  18000. }
  18001. }
  18002. if (this.options.treeshake) {
  18003. let treeshakingPass = 1;
  18004. do {
  18005. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  18006. this.needsTreeshakingPass = false;
  18007. for (const module of this.modules) {
  18008. if (module.isExecuted) {
  18009. if (module.info.hasModuleSideEffects === 'no-treeshake') {
  18010. module.includeAllInBundle();
  18011. }
  18012. else {
  18013. module.include();
  18014. }
  18015. }
  18016. }
  18017. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  18018. } while (this.needsTreeshakingPass);
  18019. }
  18020. else {
  18021. for (const module of this.modules)
  18022. module.includeAllInBundle();
  18023. }
  18024. for (const externalModule of this.externalModules)
  18025. externalModule.warnUnusedImports();
  18026. for (const module of this.implicitEntryModules) {
  18027. for (const dependant of module.implicitlyLoadedAfter) {
  18028. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  18029. error(errImplicitDependantIsNotIncluded(dependant));
  18030. }
  18031. }
  18032. }
  18033. }
  18034. sortModules() {
  18035. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  18036. for (const cyclePath of cyclePaths) {
  18037. this.options.onwarn({
  18038. code: 'CIRCULAR_DEPENDENCY',
  18039. cycle: cyclePath,
  18040. importer: cyclePath[0],
  18041. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  18042. });
  18043. }
  18044. this.modules = orderedModules;
  18045. for (const module of this.modules) {
  18046. module.bindReferences();
  18047. }
  18048. this.warnForMissingExports();
  18049. }
  18050. warnForMissingExports() {
  18051. for (const module of this.modules) {
  18052. for (const importName of Object.keys(module.importDescriptions)) {
  18053. const importDescription = module.importDescriptions[importName];
  18054. if (importDescription.name !== '*' &&
  18055. !importDescription.module.getVariableForExportName(importDescription.name)) {
  18056. module.warn({
  18057. code: 'NON_EXISTENT_EXPORT',
  18058. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  18059. name: importDescription.name,
  18060. source: importDescription.module.id
  18061. }, importDescription.start);
  18062. }
  18063. }
  18064. }
  18065. }
  18066. }
  18067. function ensureArray(items) {
  18068. if (Array.isArray(items)) {
  18069. return items.filter(Boolean);
  18070. }
  18071. if (items) {
  18072. return [items];
  18073. }
  18074. return [];
  18075. }
  18076. function getAugmentedNamespace(n) {
  18077. if (n.__esModule) return n;
  18078. var a = Object.defineProperty({}, '__esModule', {value: true});
  18079. Object.keys(n).forEach(function (k) {
  18080. var d = Object.getOwnPropertyDescriptor(n, k);
  18081. Object.defineProperty(a, k, d.get ? d : {
  18082. enumerable: true,
  18083. get: function () {
  18084. return n[k];
  18085. }
  18086. });
  18087. });
  18088. return a;
  18089. }
  18090. var require$$1 = /*@__PURE__*/getAugmentedNamespace(acorn);
  18091. const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
  18092. const getAcorn$1 = Parser => {
  18093. if (Parser.acorn) return Parser.acorn
  18094. const acorn = require$$1;
  18095. if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
  18096. throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
  18097. }
  18098. // Make sure `Parser` comes from the same acorn as we `require`d,
  18099. // otherwise the comparisons fail.
  18100. for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
  18101. if (cur !== acorn.Parser) {
  18102. throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
  18103. }
  18104. }
  18105. return acorn
  18106. };
  18107. var acornPrivateClassElements = function(Parser) {
  18108. // Only load this plugin once.
  18109. if (Parser.prototype.parsePrivateName) {
  18110. return Parser
  18111. }
  18112. const acorn = getAcorn$1(Parser);
  18113. Parser = class extends Parser {
  18114. _branch() {
  18115. this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
  18116. this.__branch.end = this.end;
  18117. this.__branch.pos = this.pos;
  18118. this.__branch.type = this.type;
  18119. this.__branch.value = this.value;
  18120. this.__branch.containsEsc = this.containsEsc;
  18121. return this.__branch
  18122. }
  18123. parsePrivateClassElementName(element) {
  18124. element.computed = false;
  18125. element.key = this.parsePrivateName();
  18126. if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
  18127. const accept = {get: "set", set: "get"}[element.kind];
  18128. const privateBoundNames = this._privateBoundNames;
  18129. if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
  18130. this.raise(element.start, "Duplicate private element");
  18131. }
  18132. privateBoundNames[element.key.name] = element.kind || true;
  18133. delete this._unresolvedPrivateNames[element.key.name];
  18134. return element.key
  18135. }
  18136. parsePrivateName() {
  18137. const node = this.startNode();
  18138. node.name = this.value;
  18139. this.next();
  18140. this.finishNode(node, "PrivateIdentifier");
  18141. if (this.options.allowReserved == "never") this.checkUnreserved(node);
  18142. return node
  18143. }
  18144. // Parse # token
  18145. getTokenFromCode(code) {
  18146. if (code === 35) {
  18147. ++this.pos;
  18148. const word = this.readWord1();
  18149. return this.finishToken(this.privateIdentifierToken, word)
  18150. }
  18151. return super.getTokenFromCode(code)
  18152. }
  18153. // Manage stacks and check for undeclared private names
  18154. parseClass(node, isStatement) {
  18155. const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
  18156. this._outerPrivateBoundNames = this._privateBoundNames;
  18157. this._privateBoundNames = Object.create(this._privateBoundNames || null);
  18158. const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  18159. this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
  18160. this._unresolvedPrivateNames = Object.create(null);
  18161. const _return = super.parseClass(node, isStatement);
  18162. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  18163. this._privateBoundNames = this._outerPrivateBoundNames;
  18164. this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
  18165. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  18166. this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
  18167. if (!this._unresolvedPrivateNames) {
  18168. const names = Object.keys(unresolvedPrivateNames);
  18169. if (names.length) {
  18170. names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
  18171. this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
  18172. }
  18173. } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
  18174. return _return
  18175. }
  18176. // Class heritage is evaluated with outer private environment
  18177. parseClassSuper(node) {
  18178. const privateBoundNames = this._privateBoundNames;
  18179. this._privateBoundNames = this._outerPrivateBoundNames;
  18180. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  18181. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  18182. const _return = super.parseClassSuper(node);
  18183. this._privateBoundNames = privateBoundNames;
  18184. this._unresolvedPrivateNames = unresolvedPrivateNames;
  18185. return _return
  18186. }
  18187. // Parse private element access
  18188. parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
  18189. const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
  18190. const branch = this._branch();
  18191. if (!(
  18192. (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
  18193. branch.type == this.privateIdentifierToken
  18194. )) {
  18195. return super.parseSubscript.apply(this, arguments)
  18196. }
  18197. let optional = false;
  18198. if (!this.eat(acorn.tokTypes.dot)) {
  18199. this.expect(acorn.tokTypes.questionDot);
  18200. optional = true;
  18201. }
  18202. let node = this.startNodeAt(startPos, startLoc);
  18203. node.object = base;
  18204. node.computed = false;
  18205. if (optionalSupported) {
  18206. node.optional = optional;
  18207. }
  18208. if (this.type == this.privateIdentifierToken) {
  18209. if (base.type == "Super") {
  18210. this.raise(this.start, "Cannot access private element on super");
  18211. }
  18212. node.property = this.parsePrivateName();
  18213. if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
  18214. if (!this._unresolvedPrivateNames) {
  18215. this.raise(node.property.start, "Usage of undeclared private name");
  18216. }
  18217. this._unresolvedPrivateNames[node.property.name] = node.property.start;
  18218. }
  18219. } else {
  18220. node.property = this.parseIdent(true);
  18221. }
  18222. return this.finishNode(node, "MemberExpression")
  18223. }
  18224. // Prohibit delete of private class elements
  18225. parseMaybeUnary(refDestructuringErrors, sawUnary) {
  18226. const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
  18227. if (_return.operator == "delete") {
  18228. if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateIdentifier") {
  18229. this.raise(_return.start, "Private elements may not be deleted");
  18230. }
  18231. }
  18232. return _return
  18233. }
  18234. };
  18235. Parser.prototype.privateIdentifierToken = new acorn.TokenType("privateIdentifier");
  18236. return Parser
  18237. };
  18238. const privateClassElements$1 = acornPrivateClassElements;
  18239. var acornClassFields = function(Parser) {
  18240. const acorn = Parser.acorn || require$$1;
  18241. const tt = acorn.tokTypes;
  18242. Parser = privateClassElements$1(Parser);
  18243. return class extends Parser {
  18244. _maybeParseFieldValue(field) {
  18245. if (this.eat(tt.eq)) {
  18246. const oldInFieldValue = this._inFieldValue;
  18247. this._inFieldValue = true;
  18248. if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
  18249. field.value = this.parseAwait();
  18250. } else field.value = this.parseExpression();
  18251. this._inFieldValue = oldInFieldValue;
  18252. } else field.value = null;
  18253. }
  18254. // Parse fields
  18255. parseClassElement(_constructorAllowsSuper) {
  18256. if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateIdentifierToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
  18257. const branch = this._branch();
  18258. if (branch.type == tt.bracketL) {
  18259. let count = 0;
  18260. do {
  18261. if (branch.eat(tt.bracketL)) ++count;
  18262. else if (branch.eat(tt.bracketR)) --count;
  18263. else branch.next();
  18264. } while (count > 0)
  18265. } else branch.next(true);
  18266. let isField = branch.type == tt.eq || branch.type == tt.semi;
  18267. if (!isField && branch.canInsertSemicolon()) {
  18268. isField = branch.type != tt.parenL;
  18269. }
  18270. if (isField) {
  18271. const node = this.startNode();
  18272. if (this.type == this.privateIdentifierToken) {
  18273. this.parsePrivateClassElementName(node);
  18274. } else {
  18275. this.parsePropertyName(node);
  18276. }
  18277. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  18278. (node.key.type === "Literal" && node.key.value === "constructor")) {
  18279. this.raise(node.key.start, "Classes may not have a field called constructor");
  18280. }
  18281. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  18282. this._maybeParseFieldValue(node);
  18283. this.exitScope();
  18284. this.finishNode(node, "PropertyDefinition");
  18285. this.semicolon();
  18286. return node
  18287. }
  18288. }
  18289. return super.parseClassElement.apply(this, arguments)
  18290. }
  18291. // Prohibit arguments in class field initializers
  18292. parseIdent(liberal, isBinding) {
  18293. const ident = super.parseIdent(liberal, isBinding);
  18294. if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
  18295. return ident
  18296. }
  18297. }
  18298. };
  18299. const privateClassElements = acornPrivateClassElements;
  18300. var acornStaticClassFeatures = function(Parser) {
  18301. const ExtendedParser = privateClassElements(Parser);
  18302. const acorn = Parser.acorn || require$$1;
  18303. const tt = acorn.tokTypes;
  18304. return class extends ExtendedParser {
  18305. _maybeParseFieldValue(field) {
  18306. if (this.eat(tt.eq)) {
  18307. const oldInFieldValue = this._inStaticFieldScope;
  18308. this._inStaticFieldScope = this.currentThisScope();
  18309. field.value = this.parseExpression();
  18310. this._inStaticFieldScope = oldInFieldValue;
  18311. } else field.value = null;
  18312. }
  18313. // Parse fields
  18314. parseClassElement(_constructorAllowsSuper) {
  18315. if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
  18316. return super.parseClassElement.apply(this, arguments)
  18317. }
  18318. const branch = this._branch();
  18319. branch.next();
  18320. if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateIdentifierToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
  18321. return super.parseClassElement.apply(this, arguments)
  18322. }
  18323. if (branch.type == tt.bracketL) {
  18324. let count = 0;
  18325. do {
  18326. if (branch.eat(tt.bracketL)) ++count;
  18327. else if (branch.eat(tt.bracketR)) --count;
  18328. else branch.next();
  18329. } while (count > 0)
  18330. } else branch.next();
  18331. if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
  18332. return super.parseClassElement.apply(this, arguments)
  18333. }
  18334. const node = this.startNode();
  18335. node.static = this.eatContextual("static");
  18336. if (this.type == this.privateIdentifierToken) {
  18337. this.parsePrivateClassElementName(node);
  18338. } else {
  18339. this.parsePropertyName(node);
  18340. }
  18341. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  18342. (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
  18343. this.raise(node.key.start, "Classes may not have a field called constructor");
  18344. }
  18345. if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
  18346. this.raise(node.key.start, "Classes may not have a static property named prototype");
  18347. }
  18348. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  18349. this._maybeParseFieldValue(node);
  18350. this.exitScope();
  18351. this.finishNode(node, "PropertyDefinition");
  18352. this.semicolon();
  18353. return node
  18354. }
  18355. // Parse private static methods
  18356. parsePropertyName(prop) {
  18357. if (prop.static && this.type == this.privateIdentifierToken) {
  18358. this.parsePrivateClassElementName(prop);
  18359. } else {
  18360. super.parsePropertyName(prop);
  18361. }
  18362. }
  18363. // Prohibit arguments in class field initializers
  18364. parseIdent(liberal, isBinding) {
  18365. const ident = super.parseIdent(liberal, isBinding);
  18366. if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
  18367. this.raise(ident.start, "A static class field initializer may not contain arguments");
  18368. }
  18369. return ident
  18370. }
  18371. }
  18372. };
  18373. const defaultOnWarn = warning => console.warn(warning.message || warning);
  18374. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  18375. const validOptionSet = new Set(validOptions);
  18376. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  18377. if (unknownOptions.length > 0) {
  18378. warn({
  18379. code: 'UNKNOWN_OPTION',
  18380. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  18381. ...validOptionSet
  18382. ]
  18383. .sort()
  18384. .join(', ')}`
  18385. });
  18386. }
  18387. }
  18388. function normalizeInputOptions(config) {
  18389. var _a, _b;
  18390. // These are options that may trigger special warnings or behaviour later
  18391. // if the user did not select an explicit value
  18392. const unsetOptions = new Set();
  18393. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  18394. const onwarn = getOnwarn(config);
  18395. const strictDeprecations = config.strictDeprecations || false;
  18396. const options = {
  18397. acorn: getAcorn(config),
  18398. acornInjectPlugins: getAcornInjectPlugins(config),
  18399. cache: getCache(config),
  18400. context,
  18401. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  18402. external: getIdMatcher(config.external),
  18403. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  18404. input: getInput(config),
  18405. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  18406. moduleContext: getModuleContext(config, context),
  18407. onwarn,
  18408. perf: config.perf || false,
  18409. plugins: ensureArray(config.plugins),
  18410. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  18411. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  18412. preserveSymlinks: config.preserveSymlinks || false,
  18413. shimMissingExports: config.shimMissingExports || false,
  18414. strictDeprecations,
  18415. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  18416. };
  18417. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  18418. return { options, unsetOptions };
  18419. }
  18420. const getOnwarn = (config) => {
  18421. return config.onwarn
  18422. ? warning => {
  18423. warning.toString = () => {
  18424. let str = '';
  18425. if (warning.plugin)
  18426. str += `(${warning.plugin} plugin) `;
  18427. if (warning.loc)
  18428. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  18429. str += warning.message;
  18430. return str;
  18431. };
  18432. config.onwarn(warning, defaultOnWarn);
  18433. }
  18434. : defaultOnWarn;
  18435. };
  18436. const getAcorn = (config) => ({
  18437. allowAwaitOutsideFunction: true,
  18438. ecmaVersion: 'latest',
  18439. preserveParens: false,
  18440. sourceType: 'module',
  18441. ...config.acorn
  18442. });
  18443. const getAcornInjectPlugins = (config) => [
  18444. acornClassFields,
  18445. acornStaticClassFeatures,
  18446. ...ensureArray(config.acornInjectPlugins)
  18447. ];
  18448. const getCache = (config) => {
  18449. var _a;
  18450. return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache;
  18451. };
  18452. const getIdMatcher = (option) => {
  18453. if (option === true) {
  18454. return () => true;
  18455. }
  18456. if (typeof option === 'function') {
  18457. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  18458. }
  18459. if (option) {
  18460. const ids = new Set();
  18461. const matchers = [];
  18462. for (const value of ensureArray(option)) {
  18463. if (value instanceof RegExp) {
  18464. matchers.push(value);
  18465. }
  18466. else {
  18467. ids.add(value);
  18468. }
  18469. }
  18470. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  18471. }
  18472. return () => false;
  18473. };
  18474. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  18475. const configInlineDynamicImports = config.inlineDynamicImports;
  18476. if (configInlineDynamicImports) {
  18477. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  18478. }
  18479. return configInlineDynamicImports;
  18480. };
  18481. const getInput = (config) => {
  18482. const configInput = config.input;
  18483. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  18484. };
  18485. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  18486. const configManualChunks = config.manualChunks;
  18487. if (configManualChunks) {
  18488. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  18489. }
  18490. return configManualChunks;
  18491. };
  18492. const getModuleContext = (config, context) => {
  18493. const configModuleContext = config.moduleContext;
  18494. if (typeof configModuleContext === 'function') {
  18495. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  18496. }
  18497. if (configModuleContext) {
  18498. const contextByModuleId = Object.create(null);
  18499. for (const key of Object.keys(configModuleContext)) {
  18500. contextByModuleId[resolve(key)] = configModuleContext[key];
  18501. }
  18502. return id => contextByModuleId[id] || context;
  18503. }
  18504. return () => context;
  18505. };
  18506. const getPreserveEntrySignatures = (config, unsetOptions) => {
  18507. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  18508. if (configPreserveEntrySignatures == null) {
  18509. unsetOptions.add('preserveEntrySignatures');
  18510. }
  18511. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  18512. };
  18513. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  18514. const configPreserveModules = config.preserveModules;
  18515. if (configPreserveModules) {
  18516. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  18517. }
  18518. return configPreserveModules;
  18519. };
  18520. const getTreeshake = (config, warn, strictDeprecations) => {
  18521. const configTreeshake = config.treeshake;
  18522. if (configTreeshake === false) {
  18523. return false;
  18524. }
  18525. if (configTreeshake && configTreeshake !== true) {
  18526. if (typeof configTreeshake.pureExternalModules !== 'undefined') {
  18527. 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);
  18528. }
  18529. return {
  18530. annotations: configTreeshake.annotations !== false,
  18531. moduleSideEffects: getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules, warn),
  18532. propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
  18533. tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
  18534. unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
  18535. };
  18536. }
  18537. return {
  18538. annotations: true,
  18539. moduleSideEffects: () => true,
  18540. propertyReadSideEffects: true,
  18541. tryCatchDeoptimization: true,
  18542. unknownGlobalSideEffects: true
  18543. };
  18544. };
  18545. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules, warn) => {
  18546. if (typeof moduleSideEffectsOption === 'boolean') {
  18547. return () => moduleSideEffectsOption;
  18548. }
  18549. if (moduleSideEffectsOption === 'no-external') {
  18550. return (_id, external) => !external;
  18551. }
  18552. if (typeof moduleSideEffectsOption === 'function') {
  18553. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  18554. }
  18555. if (Array.isArray(moduleSideEffectsOption)) {
  18556. const ids = new Set(moduleSideEffectsOption);
  18557. return id => ids.has(id);
  18558. }
  18559. if (moduleSideEffectsOption) {
  18560. warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
  18561. }
  18562. const isPureExternalModule = getIdMatcher(pureExternalModules);
  18563. return (id, external) => !(external && isPureExternalModule(id));
  18564. };
  18565. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  18566. var _a, _b, _c, _d, _e, _f, _g;
  18567. // These are options that may trigger special warnings or behaviour later
  18568. // if the user did not select an explicit value
  18569. const unsetOptions = new Set(unsetInputOptions);
  18570. const compact = config.compact || false;
  18571. const format = getFormat(config);
  18572. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  18573. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  18574. const file = getFile(config, preserveModules, inputOptions);
  18575. const outputOptions = {
  18576. amd: getAmd(config),
  18577. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  18578. banner: getAddon(config, 'banner'),
  18579. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  18580. compact,
  18581. dir: getDir(config, file),
  18582. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  18583. entryFileNames: getEntryFileNames(config, unsetOptions),
  18584. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  18585. exports: getExports(config, unsetOptions),
  18586. extend: config.extend || false,
  18587. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  18588. file,
  18589. footer: getAddon(config, 'footer'),
  18590. format,
  18591. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  18592. globals: config.globals || {},
  18593. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  18594. indent: getIndent(config, compact),
  18595. inlineDynamicImports,
  18596. interop: getInterop(config, inputOptions),
  18597. intro: getAddon(config, 'intro'),
  18598. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  18599. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  18600. name: config.name,
  18601. namespaceToStringTag: config.namespaceToStringTag || false,
  18602. noConflict: config.noConflict || false,
  18603. outro: getAddon(config, 'outro'),
  18604. paths: config.paths || {},
  18605. plugins: ensureArray(config.plugins),
  18606. preferConst: config.preferConst || false,
  18607. preserveModules,
  18608. preserveModulesRoot: getPreserveModulesRoot(config),
  18609. sourcemap: config.sourcemap || false,
  18610. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  18611. sourcemapFile: config.sourcemapFile,
  18612. sourcemapPathTransform: config.sourcemapPathTransform,
  18613. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  18614. systemNullSetters: config.systemNullSetters || false,
  18615. validate: config.validate || false
  18616. };
  18617. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  18618. return { options: outputOptions, unsetOptions };
  18619. }
  18620. const getFile = (config, preserveModules, inputOptions) => {
  18621. const file = config.file;
  18622. if (typeof file === 'string') {
  18623. if (preserveModules) {
  18624. return error({
  18625. code: 'INVALID_OPTION',
  18626. message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
  18627. });
  18628. }
  18629. if (!Array.isArray(inputOptions.input))
  18630. return error({
  18631. code: 'INVALID_OPTION',
  18632. message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
  18633. });
  18634. }
  18635. return file;
  18636. };
  18637. const getFormat = (config) => {
  18638. const configFormat = config.format;
  18639. switch (configFormat) {
  18640. case undefined:
  18641. case 'es':
  18642. case 'esm':
  18643. case 'module':
  18644. return 'es';
  18645. case 'cjs':
  18646. case 'commonjs':
  18647. return 'cjs';
  18648. case 'system':
  18649. case 'systemjs':
  18650. return 'system';
  18651. case 'amd':
  18652. case 'iife':
  18653. case 'umd':
  18654. return configFormat;
  18655. default:
  18656. return error({
  18657. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  18658. url: `https://rollupjs.org/guide/en/#outputformat`
  18659. });
  18660. }
  18661. };
  18662. const getInlineDynamicImports = (config, inputOptions) => {
  18663. var _a;
  18664. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) ||
  18665. false;
  18666. const { input } = inputOptions;
  18667. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  18668. return error({
  18669. code: 'INVALID_OPTION',
  18670. message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
  18671. });
  18672. }
  18673. return inlineDynamicImports;
  18674. };
  18675. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  18676. var _a;
  18677. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  18678. if (preserveModules) {
  18679. if (inlineDynamicImports) {
  18680. return error({
  18681. code: 'INVALID_OPTION',
  18682. message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
  18683. });
  18684. }
  18685. if (inputOptions.preserveEntrySignatures === false) {
  18686. return error({
  18687. code: 'INVALID_OPTION',
  18688. message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
  18689. });
  18690. }
  18691. }
  18692. return preserveModules;
  18693. };
  18694. const getPreserveModulesRoot = (config) => {
  18695. const preserveModulesRoot = config.preserveModulesRoot;
  18696. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  18697. return undefined;
  18698. }
  18699. return resolve(preserveModulesRoot);
  18700. };
  18701. const getAmd = (config) => {
  18702. const collection = {
  18703. autoId: false,
  18704. basePath: '',
  18705. define: 'define',
  18706. ...config.amd
  18707. };
  18708. if ((collection.autoId || collection.basePath) && collection.id) {
  18709. return error({
  18710. code: 'INVALID_OPTION',
  18711. message: '"output.amd.autoId"/"output.amd.basePath" and "output.amd.id" cannot be used together.'
  18712. });
  18713. }
  18714. if (collection.basePath && !collection.autoId) {
  18715. return error({
  18716. code: 'INVALID_OPTION',
  18717. message: '"output.amd.basePath" only works with "output.amd.autoId".'
  18718. });
  18719. }
  18720. let normalized;
  18721. if (collection.autoId) {
  18722. normalized = {
  18723. autoId: true,
  18724. basePath: collection.basePath,
  18725. define: collection.define
  18726. };
  18727. }
  18728. else {
  18729. normalized = {
  18730. autoId: false,
  18731. define: collection.define,
  18732. id: collection.id
  18733. };
  18734. }
  18735. return normalized;
  18736. };
  18737. const getAddon = (config, name) => {
  18738. const configAddon = config[name];
  18739. if (typeof configAddon === 'function') {
  18740. return configAddon;
  18741. }
  18742. return () => configAddon || '';
  18743. };
  18744. const getDir = (config, file) => {
  18745. const dir = config.dir;
  18746. if (typeof dir === 'string' && typeof file === 'string') {
  18747. return error({
  18748. code: 'INVALID_OPTION',
  18749. message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
  18750. });
  18751. }
  18752. return dir;
  18753. };
  18754. const getDynamicImportFunction = (config, inputOptions) => {
  18755. const configDynamicImportFunction = config.dynamicImportFunction;
  18756. if (configDynamicImportFunction) {
  18757. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  18758. }
  18759. return configDynamicImportFunction;
  18760. };
  18761. const getEntryFileNames = (config, unsetOptions) => {
  18762. const configEntryFileNames = config.entryFileNames;
  18763. if (configEntryFileNames == null) {
  18764. unsetOptions.add('entryFileNames');
  18765. }
  18766. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  18767. };
  18768. function getExports(config, unsetOptions) {
  18769. const configExports = config.exports;
  18770. if (configExports == null) {
  18771. unsetOptions.add('exports');
  18772. }
  18773. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  18774. return error(errInvalidExportOptionValue(configExports));
  18775. }
  18776. return configExports || 'auto';
  18777. }
  18778. const getIndent = (config, compact) => {
  18779. if (compact) {
  18780. return '';
  18781. }
  18782. const configIndent = config.indent;
  18783. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  18784. };
  18785. const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
  18786. const getInterop = (config, inputOptions) => {
  18787. const configInterop = config.interop;
  18788. const validatedInteropTypes = new Set();
  18789. const validateInterop = (interop) => {
  18790. if (!validatedInteropTypes.has(interop)) {
  18791. validatedInteropTypes.add(interop);
  18792. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  18793. return error({
  18794. code: 'INVALID_OPTION',
  18795. 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.`,
  18796. url: 'https://rollupjs.org/guide/en/#outputinterop'
  18797. });
  18798. }
  18799. if (typeof interop === 'boolean') {
  18800. warnDeprecation({
  18801. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  18802. url: 'https://rollupjs.org/guide/en/#outputinterop'
  18803. }, false, inputOptions);
  18804. }
  18805. }
  18806. return interop;
  18807. };
  18808. if (typeof configInterop === 'function') {
  18809. const interopPerId = Object.create(null);
  18810. let defaultInterop = null;
  18811. return id => id === null
  18812. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  18813. : id in interopPerId
  18814. ? interopPerId[id]
  18815. : validateInterop((interopPerId[id] = configInterop(id)));
  18816. }
  18817. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  18818. };
  18819. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  18820. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  18821. if (configManualChunks) {
  18822. if (inlineDynamicImports) {
  18823. return error({
  18824. code: 'INVALID_OPTION',
  18825. message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
  18826. });
  18827. }
  18828. if (preserveModules) {
  18829. return error({
  18830. code: 'INVALID_OPTION',
  18831. message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
  18832. });
  18833. }
  18834. }
  18835. return configManualChunks || {};
  18836. };
  18837. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  18838. function rollup(rawInputOptions) {
  18839. return rollupInternal(rawInputOptions, null);
  18840. }
  18841. async function rollupInternal(rawInputOptions, watcher) {
  18842. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  18843. initialiseTimers(inputOptions);
  18844. const graph = new Graph(inputOptions, watcher);
  18845. // remove the cache option from the memory after graph creation (cache is not used anymore)
  18846. const useCache = rawInputOptions.cache !== false;
  18847. delete inputOptions.cache;
  18848. delete rawInputOptions.cache;
  18849. timeStart('BUILD', 1);
  18850. try {
  18851. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  18852. await graph.build();
  18853. }
  18854. catch (err) {
  18855. const watchFiles = Object.keys(graph.watchFiles);
  18856. if (watchFiles.length > 0) {
  18857. err.watchFiles = watchFiles;
  18858. }
  18859. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  18860. await graph.pluginDriver.hookParallel('closeBundle', []);
  18861. throw err;
  18862. }
  18863. await graph.pluginDriver.hookParallel('buildEnd', []);
  18864. timeEnd('BUILD', 1);
  18865. const result = {
  18866. cache: useCache ? graph.getCache() : undefined,
  18867. closed: false,
  18868. async close() {
  18869. if (result.closed)
  18870. return;
  18871. result.closed = true;
  18872. await graph.pluginDriver.hookParallel('closeBundle', []);
  18873. },
  18874. async generate(rawOutputOptions) {
  18875. if (result.closed)
  18876. return error(errAlreadyClosed());
  18877. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  18878. },
  18879. watchFiles: Object.keys(graph.watchFiles),
  18880. async write(rawOutputOptions) {
  18881. if (result.closed)
  18882. return error(errAlreadyClosed());
  18883. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  18884. }
  18885. };
  18886. if (inputOptions.perf)
  18887. result.getTimings = getTimings;
  18888. return result;
  18889. }
  18890. async function getInputOptions(rawInputOptions, watchMode) {
  18891. if (!rawInputOptions) {
  18892. throw new Error('You must supply an options object to rollup');
  18893. }
  18894. const rawPlugins = ensureArray(rawInputOptions.plugins);
  18895. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  18896. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  18897. return { options, unsetOptions };
  18898. }
  18899. function applyOptionHook(watchMode) {
  18900. return async (inputOptions, plugin) => {
  18901. if (plugin.options)
  18902. return (plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions) || inputOptions);
  18903. return inputOptions;
  18904. };
  18905. }
  18906. function normalizePlugins(plugins, anonymousPrefix) {
  18907. for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
  18908. const plugin = plugins[pluginIndex];
  18909. if (!plugin.name) {
  18910. plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
  18911. }
  18912. }
  18913. }
  18914. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  18915. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  18916. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  18917. const generated = await bundle.generate(isWrite);
  18918. if (isWrite) {
  18919. if (!outputOptions.dir && !outputOptions.file) {
  18920. return error({
  18921. code: 'MISSING_OPTION',
  18922. message: 'You must specify "output.file" or "output.dir" for the build.'
  18923. });
  18924. }
  18925. await Promise.all(Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions)));
  18926. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  18927. }
  18928. return createOutput(generated);
  18929. }
  18930. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  18931. if (!rawOutputOptions) {
  18932. throw new Error('You must supply an options object');
  18933. }
  18934. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  18935. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  18936. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  18937. return {
  18938. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  18939. outputPluginDriver
  18940. };
  18941. }
  18942. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  18943. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  18944. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  18945. return {
  18946. ...pluginContext,
  18947. emitFile: emitError,
  18948. setAssetSource: emitError
  18949. };
  18950. }), inputOptions, unsetInputOptions);
  18951. }
  18952. function createOutput(outputBundle) {
  18953. return {
  18954. output: Object.keys(outputBundle)
  18955. .map(fileName => outputBundle[fileName])
  18956. .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  18957. const fileTypeA = getSortingFileType(outputFileA);
  18958. const fileTypeB = getSortingFileType(outputFileB);
  18959. if (fileTypeA === fileTypeB)
  18960. return 0;
  18961. return fileTypeA < fileTypeB ? -1 : 1;
  18962. })
  18963. };
  18964. }
  18965. var SortingFileType;
  18966. (function (SortingFileType) {
  18967. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  18968. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  18969. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  18970. })(SortingFileType || (SortingFileType = {}));
  18971. function getSortingFileType(file) {
  18972. if (file.type === 'asset') {
  18973. return SortingFileType.ASSET;
  18974. }
  18975. if (file.isEntry) {
  18976. return SortingFileType.ENTRY_CHUNK;
  18977. }
  18978. return SortingFileType.SECONDARY_CHUNK;
  18979. }
  18980. function writeOutputFile(outputFile, outputOptions) {
  18981. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  18982. let writeSourceMapPromise;
  18983. let source;
  18984. if (outputFile.type === 'asset') {
  18985. source = outputFile.source;
  18986. }
  18987. else {
  18988. source = outputFile.code;
  18989. if (outputOptions.sourcemap && outputFile.map) {
  18990. let url;
  18991. if (outputOptions.sourcemap === 'inline') {
  18992. url = outputFile.map.toUrl();
  18993. }
  18994. else {
  18995. url = `${basename(outputFile.fileName)}.map`;
  18996. writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
  18997. }
  18998. if (outputOptions.sourcemap !== 'hidden') {
  18999. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19000. }
  19001. }
  19002. }
  19003. return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
  19004. }
  19005. let fsEvents;
  19006. let fsEventsImportError;
  19007. function loadFsEvents() {
  19008. return import('fsevents')
  19009. .then(namespace => {
  19010. fsEvents = namespace.default;
  19011. })
  19012. .catch(err => {
  19013. fsEventsImportError = err;
  19014. });
  19015. }
  19016. // A call to this function will be injected into the chokidar code
  19017. function getFsEvents() {
  19018. if (fsEventsImportError)
  19019. throw fsEventsImportError;
  19020. return fsEvents;
  19021. }
  19022. var fseventsImporter = {
  19023. __proto__: null,
  19024. loadFsEvents: loadFsEvents,
  19025. getFsEvents: getFsEvents
  19026. };
  19027. class WatchEmitter extends EventEmitter {
  19028. constructor() {
  19029. super();
  19030. // Allows more than 10 bundles to be watched without
  19031. // showing the `MaxListenersExceededWarning` to the user.
  19032. this.setMaxListeners(Infinity);
  19033. }
  19034. close() { }
  19035. }
  19036. function watch(configs) {
  19037. const emitter = new WatchEmitter();
  19038. const configArray = ensureArray(configs);
  19039. const watchConfigs = configArray.filter(config => config.watch !== false);
  19040. if (watchConfigs.length === 0) {
  19041. throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
  19042. }
  19043. loadFsEvents()
  19044. .then(() => import('./watch.js'))
  19045. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  19046. return emitter;
  19047. }
  19048. export { defaultOnWarn, ensureArray, fseventsImporter, getAugmentedNamespace, rollup, rollupInternal, version$1 as version, warnUnknownOptions, watch };